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 TrackResize (0 && !ForRelease)
393 #define ManualRefresh (1 && !ForRelease)
394 #define ShowInternals (0 && !ForRelease)
395 #define IgnoreInstall (0 && !ForRelease)
396 #define RecycleWebViews 0
397 #define AlwaysReload (1 && !ForRelease)
401 #define _trace(args...)
403 #define _profile(name) {
406 #define PrintTimes() do {} while (false)
410 @interface NSMutableArray (Radix)
411 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
412 - (void) radixSortUsingFunction:(uint32_t (*)(id, void *))function withArgument:(void *)argument;
420 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
421 struct RadixItem_ *lhs(swap), *rhs(swap + count);
423 static const size_t width = 32;
424 static const size_t bits = 11;
425 static const size_t slots = 1 << bits;
426 static const size_t passes = (width + (bits - 1)) / bits;
428 size_t *hist(new size_t[slots]);
430 for (size_t pass(0); pass != passes; ++pass) {
431 memset(hist, 0, sizeof(size_t) * slots);
433 for (size_t i(0); i != count; ++i) {
434 uint32_t key(lhs[i].key);
436 key &= _not(uint32_t) >> width - bits;
441 for (size_t i(0); i != slots; ++i) {
442 size_t local(offset);
447 for (size_t i(0); i != count; ++i) {
448 uint32_t key(lhs[i].key);
450 key &= _not(uint32_t) >> width - bits;
451 rhs[hist[key]++] = lhs[i];
454 RadixItem_ *tmp(lhs);
461 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
462 for (size_t i(0); i != count; ++i)
463 [values addObject:[self objectAtIndex:lhs[i].index]];
464 [self setArray:values];
469 @implementation NSMutableArray (Radix)
471 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
472 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
473 [invocation setSelector:selector];
474 [invocation setArgument:&object atIndex:2];
476 size_t count([self count]);
477 struct RadixItem_ *swap(new RadixItem_[count * 2]);
479 for (size_t i(0); i != count; ++i) {
480 RadixItem_ &item(swap[i]);
483 id object([self objectAtIndex:i]);
484 [invocation setTarget:object];
487 [invocation getReturnValue:&item.key];
490 RadixSort_(self, count, swap);
493 - (void) radixSortUsingFunction:(uint32_t (*)(id, void *))function withArgument:(void *)argument {
494 size_t count([self count]);
495 struct RadixItem_ *swap(new RadixItem_[count * 2]);
497 for (size_t i(0); i != count; ++i) {
498 RadixItem_ &item(swap[i]);
501 id object([self objectAtIndex:i]);
502 item.key = function(object, argument);
505 RadixSort_(self, count, swap);
511 /* Apple Bug Fixes {{{ */
512 @implementation UIWebDocumentView (Cydia)
514 - (void) _setScrollerOffset:(CGPoint)offset {
515 UIScroller *scroller([self _scroller]);
517 CGSize size([scroller contentSize]);
518 CGSize bounds([scroller bounds].size);
521 max.x = size.width - bounds.width;
522 max.y = size.height - bounds.height;
530 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
531 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
533 [scroller setOffset:offset];
540 kUIControlEventMouseDown = 1 << 0,
541 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
542 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
543 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
544 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
545 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
546 } UIControlEventMasks;
548 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
549 size_t length([self length] - state->state);
552 else if (length > count)
554 for (size_t i(0); i != length; ++i)
555 objects[i] = [self item:state->state++];
556 state->itemsPtr = objects;
557 state->mutationsPtr = (unsigned long *) self;
561 @interface NSString (UIKit)
562 - (NSString *) stringByAddingPercentEscapes;
563 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
566 @interface NSString (Cydia)
567 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
568 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
569 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
570 - (NSComparisonResult) compareByPath:(NSString *)other;
571 - (NSString *) stringByCachingURLWithCurrentCDN;
572 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
575 @implementation NSString (Cydia)
577 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
578 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
581 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
582 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
583 memcpy(data, bytes, length);
584 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
587 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
588 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
591 - (NSComparisonResult) compareByPath:(NSString *)other {
592 NSString *prefix = [self commonPrefixWithString:other options:0];
593 size_t length = [prefix length];
595 NSRange lrange = NSMakeRange(length, [self length] - length);
596 NSRange rrange = NSMakeRange(length, [other length] - length);
598 lrange = [self rangeOfString:@"/" options:0 range:lrange];
599 rrange = [other rangeOfString:@"/" options:0 range:rrange];
601 NSComparisonResult value;
603 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
604 value = NSOrderedSame;
605 else if (lrange.location == NSNotFound)
606 value = NSOrderedAscending;
607 else if (rrange.location == NSNotFound)
608 value = NSOrderedDescending;
610 value = NSOrderedSame;
612 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
613 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
614 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
615 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
617 NSComparisonResult result = [lpath compare:rpath];
618 return result == NSOrderedSame ? value : result;
621 - (NSString *) stringByCachingURLWithCurrentCDN {
623 stringByReplacingOccurrencesOfString:@"://"
624 withString:@"://ne.edgecastcdn.net/8003A4/"
626 /* XXX: this is somewhat inaccurate */
627 range:NSMakeRange(0, 10)
631 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
632 return [(id)CFURLCreateStringByAddingPercentEscapes(
637 kCFStringEncodingUTF8
643 static inline NSString *CYLocalizeEx(NSString *key, NSString *value = nil) {
644 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:nil];
647 #define CYLocalize(key) CYLocalizeEx(@ key)
655 _finline void clear_() {
661 _finline bool empty() const {
665 _finline size_t size() const {
669 _finline char *data() const {
673 _finline void clear() {
678 _finline CYString() :
685 _finline ~CYString() {
689 void operator =(const CYString &rhs) {
693 if (rhs.cache_ == nil)
696 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
699 void set(apr_pool_t *pool, const char *data, size_t size) {
705 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size)));
706 memcpy(temp, data, size);
712 _finline void set(apr_pool_t *pool, const char *data) {
713 set(pool, data, data == NULL ? 0 : strlen(data));
716 _finline void set(apr_pool_t *pool, const std::string &rhs) {
717 set(pool, rhs.data(), rhs.size());
720 bool operator ==(const CYString &rhs) const {
721 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
725 if (cache_ == NULL) {
728 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
729 } return (id) cache_;
734 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
737 struct NSStringMapHash :
738 std::unary_function<NSString *, size_t>
740 _finline size_t operator ()(NSString *value) const {
741 return CFStringHashNSString((CFStringRef) value);
745 struct NSStringMapLess :
746 std::binary_function<NSString *, NSString *, bool>
748 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
749 return [lhs compare:rhs] == NSOrderedAscending;
753 struct NSStringMapEqual :
754 std::binary_function<NSString *, NSString *, bool>
756 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
757 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
758 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
759 //[lhs isEqualToString:rhs];
763 /* Perl-Compatible RegEx {{{ */
773 Pcre(const char *regex) :
778 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
781 lprintf("%d:%s\n", offset, error);
785 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
786 matches_ = new int[(capture_ + 1) * 3];
794 NSString *operator [](size_t match) {
795 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
798 bool operator ()(NSString *data) {
799 // XXX: length is for characters, not for bytes
800 return operator ()([data UTF8String], [data length]);
803 bool operator ()(const char *data, size_t size) {
805 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
809 /* Mime Addresses {{{ */
810 @interface Address : NSObject {
816 - (NSString *) address;
818 - (void) setAddress:(NSString *)address;
820 + (Address *) addressWithString:(NSString *)string;
821 - (Address *) initWithString:(NSString *)string;
824 @implementation Address
833 - (NSString *) name {
837 - (NSString *) address {
841 - (void) setAddress:(NSString *)address {
843 [address_ autorelease];
847 address_ = [address retain];
850 + (Address *) addressWithString:(NSString *)string {
851 return [[[Address alloc] initWithString:string] autorelease];
854 + (NSArray *) _attributeKeys {
855 return [NSArray arrayWithObjects:@"address", @"name", nil];
858 - (NSArray *) attributeKeys {
859 return [[self class] _attributeKeys];
862 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
863 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
866 - (Address *) initWithString:(NSString *)string {
867 if ((self = [super init]) != nil) {
868 const char *data = [string UTF8String];
869 size_t size = [string length];
871 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
873 if (address_r(data, size)) {
874 name_ = [address_r[1] retain];
875 address_ = [address_r[2] retain];
877 name_ = [string retain];
885 /* CoreGraphics Primitives {{{ */
896 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
899 Set(space, red, green, blue, alpha);
904 CGColorRelease(color_);
911 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
913 float color[] = {red, green, blue, alpha};
914 color_ = CGColorCreate(space, color);
917 operator CGColorRef() {
923 extern "C" void UISetColor(CGColorRef color);
925 /* Random Global Variables {{{ */
926 static const int PulseInterval_ = 50000;
927 static const int ButtonBarHeight_ = 48;
928 static const float KeyboardTime_ = 0.3f;
930 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
931 #define SandboxTemplate_ "/usr/share/sandbox/SandboxTemplate.sb"
932 #define NotifyConfig_ "/etc/notify.conf"
934 static bool Queuing_;
936 static CGColor Blue_;
937 static CGColor Blueish_;
938 static CGColor Black_;
940 static CGColor White_;
941 static CGColor Gray_;
942 static CGColor Green_;
943 static CGColor Purple_;
944 static CGColor Purplish_;
946 static UIColor *InstallingColor_;
947 static UIColor *RemovingColor_;
949 static NSString *App_;
950 static NSString *Home_;
951 static BOOL Sounds_Keyboard_;
953 static BOOL Advanced_;
955 static BOOL Ignored_;
957 static UIFont *Font12_;
958 static UIFont *Font12Bold_;
959 static UIFont *Font14_;
960 static UIFont *Font18Bold_;
961 static UIFont *Font22Bold_;
963 static const char *Machine_ = NULL;
964 static const NSString *UniqueID_ = nil;
965 static const NSString *Build_ = nil;
966 static const NSString *Product_ = nil;
967 static const NSString *Safari_ = nil;
971 CGColorSpaceRef space_;
976 static NSDictionary *SectionMap_;
977 static NSMutableDictionary *Metadata_;
978 static _transient NSMutableDictionary *Settings_;
979 static _transient NSString *Role_;
980 static _transient NSMutableDictionary *Packages_;
981 static _transient NSMutableDictionary *Sections_;
982 static _transient NSMutableDictionary *Sources_;
983 static bool Changed_;
987 static NSMutableArray *Documents_;
990 NSString *GetLastUpdate() {
991 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
994 return CYLocalize("NEVER_OR_UNKNOWN");
996 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
997 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
999 CFRelease(formatter);
1001 return [(NSString *) formatted autorelease];
1004 /* Display Helpers {{{ */
1005 inline float Interpolate(float begin, float end, float fraction) {
1006 return (end - begin) * fraction + begin;
1009 /* XXX: localize this! */
1010 NSString *SizeString(double size) {
1011 bool negative = size < 0;
1016 while (size > 1024) {
1021 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1023 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1026 NSString *StripVersion(const char *version) {
1027 const char *colon(strchr(version, ':'));
1029 version = colon + 1;
1030 return [NSString stringWithUTF8String:version];
1033 NSString *StripVersion(NSString *version) {
1034 NSRange colon = [version rangeOfString:@":"];
1035 if (colon.location != NSNotFound)
1036 version = [version substringFromIndex:(colon.location + 1)];
1040 NSString *LocalizeSection(NSString *section) {
1041 static Pcre title_r("^(.*?) \\((.*)\\)$");
1042 if (title_r(section))
1043 return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"),
1044 LocalizeSection(title_r[1]),
1045 LocalizeSection(title_r[2])
1048 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1051 NSString *Simplify(NSString *title) {
1052 const char *data = [title UTF8String];
1053 size_t size = [title length];
1055 static Pcre square_r("^\\[(.*)\\]$");
1056 if (square_r(data, size))
1057 return Simplify(square_r[1]);
1059 static Pcre paren_r("^\\((.*)\\)$");
1060 if (paren_r(data, size))
1061 return Simplify(paren_r[1]);
1063 static Pcre title_r("^(.*?) \\((.*)\\)$");
1064 if (title_r(data, size))
1065 return Simplify(title_r[1]);
1071 bool isSectionVisible(NSString *section) {
1072 NSDictionary *metadata = [Sections_ objectForKey:section];
1073 NSNumber *hidden = metadata == nil ? nil : [metadata objectForKey:@"Hidden"];
1074 return hidden == nil || ![hidden boolValue];
1077 /* Delegate Prototypes {{{ */
1081 @interface NSObject (ProgressDelegate)
1084 @implementation NSObject(ProgressDelegate)
1086 - (void) _setProgressError:(NSArray *)args {
1087 [self performSelector:@selector(setProgressError:forPackage:)
1088 withObject:[args objectAtIndex:0]
1089 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1095 @protocol ProgressDelegate
1096 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1097 - (void) setProgressTitle:(NSString *)title;
1098 - (void) setProgressPercent:(float)percent;
1099 - (void) startProgress;
1100 - (void) addProgressOutput:(NSString *)output;
1101 - (bool) isCancelling:(size_t)received;
1104 @protocol ConfigurationDelegate
1105 - (void) repairWithSelector:(SEL)selector;
1106 - (void) setConfigurationData:(NSString *)data;
1111 @protocol CydiaDelegate
1112 - (void) setPackageView:(PackageView *)view;
1113 - (void) clearPackage:(Package *)package;
1114 - (void) installPackage:(Package *)package;
1115 - (void) removePackage:(Package *)package;
1116 - (void) slideUp:(UIActionSheet *)alert;
1117 - (void) distUpgrade;
1118 - (void) updateData;
1120 - (void) askForSettings;
1121 - (UIProgressHUD *) addProgressHUD;
1122 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1123 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1124 - (RVPage *) pageForPackage:(NSString *)name;
1125 - (void) openMailToURL:(NSURL *)url;
1126 - (void) clearFirstResponder;
1127 - (PackageView *) packageView;
1131 /* Status Delegation {{{ */
1133 public pkgAcquireStatus
1136 _transient NSObject<ProgressDelegate> *delegate_;
1144 void setDelegate(id delegate) {
1145 delegate_ = delegate;
1148 virtual bool MediaChange(std::string media, std::string drive) {
1152 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1155 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1156 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1157 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1160 virtual void Done(pkgAcquire::ItemDesc &item) {
1163 virtual void Fail(pkgAcquire::ItemDesc &item) {
1165 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1166 item.Owner->Status == pkgAcquire::Item::StatDone
1170 std::string &error(item.Owner->ErrorText);
1174 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1175 NSArray *fields([description componentsSeparatedByString:@" "]);
1176 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1178 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1179 withObject:[NSArray arrayWithObjects:
1180 [NSString stringWithUTF8String:error.c_str()],
1187 virtual bool Pulse(pkgAcquire *Owner) {
1188 bool value = pkgAcquireStatus::Pulse(Owner);
1191 double(CurrentBytes + CurrentItems) /
1192 double(TotalBytes + TotalItems)
1195 [delegate_ setProgressPercent:percent];
1196 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1199 virtual void Start() {
1200 [delegate_ startProgress];
1203 virtual void Stop() {
1207 /* Progress Delegation {{{ */
1212 _transient id<ProgressDelegate> delegate_;
1215 virtual void Update() {
1216 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1217 [delegate_ setProgressPercent:(Percent / 100)];*/
1226 void setDelegate(id delegate) {
1227 delegate_ = delegate;
1230 virtual void Done() {
1231 //[delegate_ setProgressPercent:1];
1236 /* Database Interface {{{ */
1237 @interface Database : NSObject {
1243 pkgCacheFile cache_;
1244 pkgDepCache::Policy *policy_;
1245 pkgRecords *records_;
1246 pkgProblemResolver *resolver_;
1247 pkgAcquire *fetcher_;
1249 SPtr<pkgPackageManager> manager_;
1250 pkgSourceList *list_;
1252 NSMutableDictionary *sources_;
1253 NSMutableArray *packages_;
1255 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1264 + (Database *) sharedInstance;
1267 - (void) _readCydia:(NSNumber *)fd;
1268 - (void) _readStatus:(NSNumber *)fd;
1269 - (void) _readOutput:(NSNumber *)fd;
1273 - (Package *) packageWithName:(NSString *)name;
1275 - (pkgCacheFile &) cache;
1276 - (pkgDepCache::Policy *) policy;
1277 - (pkgRecords *) records;
1278 - (pkgProblemResolver *) resolver;
1279 - (pkgAcquire &) fetcher;
1280 - (pkgSourceList &) list;
1281 - (NSArray *) packages;
1282 - (NSArray *) sources;
1283 - (void) reloadData;
1291 - (void) updateWithStatus:(Status &)status;
1293 - (void) setDelegate:(id)delegate;
1294 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1298 /* Source Class {{{ */
1299 @interface Source : NSObject {
1300 NSString *description_;
1306 NSString *distribution_;
1310 NSString *defaultIcon_;
1312 NSDictionary *record_;
1316 - (Source *) initWithMetaIndex:(metaIndex *)index;
1318 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1320 - (NSString *) supportForPackage:(NSString *)package;
1322 - (NSDictionary *) record;
1326 - (NSString *) distribution;
1327 - (NSString *) type;
1329 - (NSString *) host;
1331 - (NSString *) name;
1332 - (NSString *) description;
1333 - (NSString *) label;
1334 - (NSString *) origin;
1335 - (NSString *) version;
1337 - (NSString *) defaultIcon;
1341 @implementation Source
1343 #define _clear(field) \
1350 _clear(distribution_)
1353 _clear(description_)
1358 _clear(defaultIcon_)
1367 + (NSArray *) _attributeKeys {
1368 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1371 - (NSArray *) attributeKeys {
1372 return [[self class] _attributeKeys];
1375 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1376 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1379 - (void) setMetaIndex:(metaIndex *)index {
1382 trusted_ = index->IsTrusted();
1384 uri_ = [[NSString stringWithUTF8String:index->GetURI().c_str()] retain];
1385 distribution_ = [[NSString stringWithUTF8String:index->GetDist().c_str()] retain];
1386 type_ = [[NSString stringWithUTF8String:index->GetType()] retain];
1388 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1389 if (dindex != NULL) {
1390 std::ifstream release(dindex->MetaIndexFile("Release").c_str());
1392 while (std::getline(release, line)) {
1393 std::string::size_type colon(line.find(':'));
1394 if (colon == std::string::npos)
1397 std::string name(line.substr(0, colon));
1398 std::string value(line.substr(colon + 1));
1399 while (!value.empty() && value[0] == ' ')
1400 value = value.substr(1);
1402 if (name == "Default-Icon")
1403 defaultIcon_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1404 else if (name == "Description")
1405 description_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1406 else if (name == "Label")
1407 label_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1408 else if (name == "Origin")
1409 origin_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1410 else if (name == "Support")
1411 support_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1412 else if (name == "Version")
1413 version_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1417 record_ = [Sources_ objectForKey:[self key]];
1419 record_ = [record_ retain];
1422 - (Source *) initWithMetaIndex:(metaIndex *)index {
1423 if ((self = [super init]) != nil) {
1424 [self setMetaIndex:index];
1428 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1429 NSDictionary *lhr = [self record];
1430 NSDictionary *rhr = [source record];
1433 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1435 NSString *lhs = [self name];
1436 NSString *rhs = [source name];
1438 if ([lhs length] != 0 && [rhs length] != 0) {
1439 unichar lhc = [lhs characterAtIndex:0];
1440 unichar rhc = [rhs characterAtIndex:0];
1442 if (isalpha(lhc) && !isalpha(rhc))
1443 return NSOrderedAscending;
1444 else if (!isalpha(lhc) && isalpha(rhc))
1445 return NSOrderedDescending;
1448 return [lhs compare:rhs options:LaxCompareOptions_];
1451 - (NSString *) supportForPackage:(NSString *)package {
1452 return support_ == nil ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1455 - (NSDictionary *) record {
1463 - (NSString *) uri {
1467 - (NSString *) distribution {
1468 return distribution_;
1471 - (NSString *) type {
1475 - (NSString *) key {
1476 return [NSString stringWithFormat:@"%@:%@:%@", type_, uri_, distribution_];
1479 - (NSString *) host {
1480 return [[[NSURL URLWithString:[self uri]] host] lowercaseString];
1483 - (NSString *) name {
1484 return origin_ == nil ? [self host] : origin_;
1487 - (NSString *) description {
1488 return description_;
1491 - (NSString *) label {
1492 return label_ == nil ? [self host] : label_;
1495 - (NSString *) origin {
1499 - (NSString *) version {
1503 - (NSString *) defaultIcon {
1504 return defaultIcon_;
1509 /* Relationship Class {{{ */
1510 @interface Relationship : NSObject {
1515 - (NSString *) type;
1517 - (NSString *) name;
1521 @implementation Relationship
1529 - (NSString *) type {
1537 - (NSString *) name {
1544 /* Package Class {{{ */
1545 @interface Package : NSObject {
1548 pkgCache::VerIterator version_;
1549 pkgCache::PkgIterator iterator_;
1550 _transient Database *database_;
1551 pkgCache::VerFileIterator file_;
1557 NSString *section$_;
1561 NSString *installed_;
1567 CYString depiction_;
1580 NSArray *relationships_;
1581 NSMutableDictionary *metadata_;
1584 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1585 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1587 - (pkgCache::PkgIterator) iterator;
1589 - (NSString *) section;
1590 - (NSString *) simpleSection;
1592 - (NSString *) longSection;
1593 - (NSString *) shortSection;
1597 - (Address *) maintainer;
1599 - (NSString *) description;
1602 - (NSMutableDictionary *) metadata;
1604 - (BOOL) subscribed;
1607 - (NSString *) latest;
1608 - (NSString *) installed;
1611 - (BOOL) upgradableAndEssential:(BOOL)essential;
1614 - (BOOL) unfiltered;
1618 - (BOOL) halfConfigured;
1619 - (BOOL) halfInstalled;
1621 - (NSString *) mode;
1624 - (NSString *) name;
1625 - (NSString *) tagline;
1627 - (NSString *) homepage;
1628 - (NSString *) depiction;
1629 - (Address *) author;
1631 - (NSString *) support;
1633 - (NSArray *) files;
1634 - (NSArray *) relationships;
1635 - (NSArray *) warnings;
1636 - (NSArray *) applications;
1638 - (Source *) source;
1639 - (NSString *) role;
1641 - (BOOL) matches:(NSString *)text;
1643 - (bool) hasSupportingRole;
1644 - (BOOL) hasTag:(NSString *)tag;
1645 - (NSString *) primaryPurpose;
1646 - (NSArray *) purposes;
1647 - (bool) isCommercial;
1649 - (uint32_t) compareByPrefix;
1650 - (NSComparisonResult) compareByName:(Package *)package;
1651 - (uint32_t) compareBySection:(NSArray *)sections;
1653 - (uint32_t) compareForChanges;
1658 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1659 - (bool) isInstalledAndVisible:(NSNumber *)number;
1660 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1661 - (bool) isVisibleInSource:(Source *)source;
1665 uint32_t PackageChangesRadix(Package *self, void *) {
1670 uint32_t timestamp : 30;
1671 uint32_t ignored : 1;
1672 uint32_t upgradable : 1;
1676 bool upgradable([self upgradableAndEssential:YES]);
1677 value.bits.upgradable = upgradable ? 1 : 0;
1680 value.bits.timestamp = 0;
1681 value.bits.ignored = [self ignored] ? 0 : 1;
1682 value.bits.upgradable = 1;
1684 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1685 value.bits.ignored = 0;
1686 value.bits.upgradable = 0;
1689 return _not(uint32_t) - value.key;
1692 @implementation Package
1697 if (section$_ != nil)
1698 [section$_ release];
1702 if (installed_ != nil)
1703 [installed_ release];
1707 if (sponsor$_ != nil)
1708 [sponsor$_ release];
1709 if (author$_ != nil)
1716 if (relationships_ != nil)
1717 [relationships_ release];
1718 if (metadata_ != nil)
1719 [metadata_ release];
1724 + (NSString *) webScriptNameForSelector:(SEL)selector {
1725 if (selector == @selector(hasTag:))
1731 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1732 return [self webScriptNameForSelector:selector] == nil;
1735 + (NSArray *) _attributeKeys {
1736 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];
1739 - (NSArray *) attributeKeys {
1740 return [[self class] _attributeKeys];
1743 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1744 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1747 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
1748 if ((self = [super init]) != nil) {
1749 _profile(Package$initWithVersion)
1750 @synchronized (database) {
1751 era_ = [database era];
1754 iterator_ = version.ParentPkg();
1755 database_ = database;
1757 _profile(Package$initWithVersion$Latest)
1758 latest_ = [StripVersion(version_.VerStr()) retain];
1761 pkgCache::VerIterator current(iterator_.CurrentVer());
1763 installed_ = [StripVersion(current.VerStr()) retain];
1765 if (!version_.end())
1766 file_ = version_.FileList();
1768 pkgCache &cache([database_ cache]);
1769 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
1772 _profile(Package$initWithVersion$Name)
1773 id_ = [[NSString stringWithUTF8String:iterator_.Name()] retain];
1777 source_ = [database_ getSource:file_.File()];
1782 _profile(Package$initWithVersion$Parse)
1783 pkgRecords::Parser *parser;
1785 _profile(Package$initWithVersion$Parse$Lookup)
1786 parser = &[database_ records]->Lookup(file_);
1792 _profile(Package$initWithVersion$Parse$Find)
1799 {"depiction", &depiction_},
1800 {"homepage", &homepage_},
1801 {"website", &website},
1802 {"support", &support_},
1803 {"sponsor", &sponsor_},
1804 {"author", &author_},
1808 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1809 const char *start, *end;
1811 if (parser->Find(names[i].name_, start, end)) {
1812 CYString &value(*names[i].value_);
1813 _profile(Package$initWithVersion$Parse$Value)
1814 value.set(pool, start, end - start);
1820 _profile(Package$initWithVersion$Parse$Tagline)
1821 tagline_.set(pool, parser->ShortDesc());
1824 _profile(Package$initWithVersion$Parse$Retain)
1825 if (!homepage_.empty())
1826 homepage_ = website;
1827 if (homepage_ == depiction_)
1830 tags_ = [[tag componentsSeparatedByString:@", "] retain];
1834 _profile(Package$initWithVersion$Tags)
1836 for (NSString *tag in tags_)
1837 if ([tag hasPrefix:@"role::"]) {
1838 role_ = [[tag substringFromIndex:6] retain];
1843 bool changed(false);
1844 NSString *key([id_ lowercaseString]);
1846 _profile(Package$initWithVersion$Metadata)
1847 metadata_ = [Packages_ objectForKey:key];
1848 if (metadata_ == nil) {
1849 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
1853 [metadata_ setObject:latest_ forKey:@"LastVersion"];
1856 NSDate *first([metadata_ objectForKey:@"FirstSeen"]);
1857 NSDate *last([metadata_ objectForKey:@"LastSeen"]);
1858 NSString *version([metadata_ objectForKey:@"LastVersion"]);
1861 first = last == nil ? now_ : last;
1862 [metadata_ setObject:first forKey:@"FirstSeen"];
1866 if (version == nil) {
1867 [metadata_ setObject:latest_ forKey:@"LastVersion"];
1869 } else if (![version isEqualToString:latest_]) {
1870 [metadata_ setObject:latest_ forKey:@"LastVersion"];
1872 [metadata_ setObject:last forKey:@"LastSeen"];
1877 metadata_ = [metadata_ retain];
1880 [Packages_ setObject:metadata_ forKey:key];
1885 _profile(Package$initWithVersion$Section)
1886 section_.set(pool, iterator_.Section());
1889 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
1890 } _end } return self;
1893 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
1894 pkgCache::VerIterator version;
1896 _profile(Package$packageWithIterator$GetCandidateVer)
1897 version = [database policy]->GetCandidateVer(iterator);
1903 return [[[Package alloc]
1904 initWithVersion:version
1911 - (pkgCache::PkgIterator) iterator {
1915 - (NSString *) section {
1916 if (section$_ == nil) {
1917 if (section_.empty())
1920 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
1921 NSString *name(section_);
1924 if (NSDictionary *value = [SectionMap_ objectForKey:name])
1925 if (NSString *rename = [value objectForKey:@"Rename"]) {
1930 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
1934 - (NSString *) simpleSection {
1935 if (NSString *section = [self section])
1936 return Simplify(section);
1941 - (NSString *) longSection {
1942 return LocalizeSection(section_);
1945 - (NSString *) shortSection {
1946 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
1949 - (NSString *) uri {
1952 pkgIndexFile *index;
1953 pkgCache::PkgFileIterator file(file_.File());
1954 if (![database_ list].FindIndex(file, index))
1956 return [NSString stringWithUTF8String:iterator_->Path];
1957 //return [NSString stringWithUTF8String:file.Site()];
1958 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
1962 - (Address *) maintainer {
1965 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
1966 const std::string &maintainer(parser->Maintainer());
1967 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
1971 return version_.end() ? 0 : version_->InstalledSize;
1974 - (NSString *) description {
1977 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
1978 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
1980 NSArray *lines = [description componentsSeparatedByString:@"\n"];
1981 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
1982 if ([lines count] < 2)
1985 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
1986 for (size_t i(1), e([lines count]); i != e; ++i) {
1987 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
1988 [trimmed addObject:trim];
1991 return [trimmed componentsJoinedByString:@"\n"];
1995 _profile(Package$index)
1996 NSString *name([self name]);
1997 if ([name length] == 0)
1999 unichar character([name characterAtIndex:0]);
2000 if (!isalpha(character))
2002 return toupper(character);
2006 - (NSMutableDictionary *) metadata {
2007 if (metadata_ == nil)
2008 metadata_ = [[Packages_ objectForKey:[id_ lowercaseString]] retain];
2013 NSDictionary *metadata([self metadata]);
2014 if ([self subscribed])
2015 if (NSDate *last = [metadata objectForKey:@"LastSeen"])
2017 return [metadata objectForKey:@"FirstSeen"];
2020 - (BOOL) subscribed {
2021 NSDictionary *metadata([self metadata]);
2022 if (NSNumber *subscribed = [metadata objectForKey:@"IsSubscribed"])
2023 return [subscribed boolValue];
2029 NSDictionary *metadata([self metadata]);
2030 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2031 return [ignored boolValue];
2036 - (NSString *) latest {
2040 - (NSString *) installed {
2045 return !version_.end();
2048 - (BOOL) upgradableAndEssential:(BOOL)essential {
2049 pkgCache::VerIterator current = iterator_.CurrentVer();
2053 value = essential && [self essential] && [self visible];
2055 value = !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2059 - (BOOL) essential {
2064 return [database_ cache][iterator_].InstBroken();
2067 - (BOOL) unfiltered {
2068 NSString *section = [self section];
2069 return section == nil || isSectionVisible(section);
2073 return [self hasSupportingRole] && [self unfiltered];
2077 unsigned char current = iterator_->CurrentState;
2078 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2081 - (BOOL) halfConfigured {
2082 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2085 - (BOOL) halfInstalled {
2086 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2090 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2091 return state.Mode != pkgDepCache::ModeKeep;
2094 - (NSString *) mode {
2095 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2097 switch (state.Mode) {
2098 case pkgDepCache::ModeDelete:
2099 if ((state.iFlags & pkgDepCache::Purge) != 0)
2103 case pkgDepCache::ModeKeep:
2104 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2105 return @"REINSTALL";
2106 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2110 case pkgDepCache::ModeInstall:
2111 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2112 return @"REINSTALL";
2113 else*/ switch (state.Status) {
2115 return @"DOWNGRADE";
2121 return @"NEW_INSTALL";
2134 - (NSString *) name {
2135 return name_ == nil ? id_ : name_;
2138 - (NSString *) tagline {
2142 - (UIImage *) icon {
2143 NSString *section = [self simpleSection];
2147 if ([icon_ hasPrefix:@"file:///"])
2148 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2149 if (icon == nil) if (section != nil)
2150 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2151 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2152 if ([dicon hasPrefix:@"file:///"])
2153 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2155 icon = [UIImage applicationImageNamed:@"unknown.png"];
2159 - (NSString *) homepage {
2163 - (NSString *) depiction {
2167 - (Address *) sponsor {
2168 if (sponsor$_ == nil) {
2169 if (sponsor_.empty())
2171 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2175 - (Address *) author {
2176 if (author$_ == nil) {
2177 if (author_.empty())
2179 author$_ = [[Address addressWithString:author_] retain];
2183 - (NSString *) support {
2184 return support_ != nil ? support_ : [[self source] supportForPackage:id_];
2187 - (NSArray *) files {
2188 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", id_];
2189 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2192 fin.open([path UTF8String]);
2197 while (std::getline(fin, line))
2198 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2203 - (NSArray *) relationships {
2204 return relationships_;
2207 - (NSArray *) warnings {
2208 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2209 const char *name(iterator_.Name());
2211 size_t length(strlen(name));
2212 if (length < 2) invalid:
2213 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2214 else for (size_t i(0); i != length; ++i)
2216 /* XXX: technically this is not allowed */
2217 (name[i] < 'A' || name[i] > 'Z') &&
2218 (name[i] < 'a' || name[i] > 'z') &&
2219 (name[i] < '0' || name[i] > '9') &&
2220 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2223 if (strcmp(name, "cydia") != 0) {
2225 bool _private = false;
2228 bool repository = [[self section] isEqualToString:@"Repositories"];
2230 if (NSArray *files = [self files])
2231 for (NSString *file in files)
2232 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2234 else if (!_private && [file isEqualToString:@"/private"])
2236 else if (!stash && [file isEqualToString:@"/var/stash"])
2239 /* XXX: this is not sensitive enough. only some folders are valid. */
2240 if (cydia && !repository)
2241 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2243 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2245 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2248 return [warnings count] == 0 ? nil : warnings;
2251 - (NSArray *) applications {
2252 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2254 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2256 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2257 if (NSArray *files = [self files])
2258 for (NSString *file in files)
2259 if (application_r(file)) {
2260 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2261 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2262 if ([id isEqualToString:me])
2265 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2267 display = application_r[1];
2269 NSString *bundle([file stringByDeletingLastPathComponent]);
2270 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2271 if (icon == nil || [icon length] == 0)
2273 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2275 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2276 [applications addObject:application];
2278 [application addObject:id];
2279 [application addObject:display];
2280 [application addObject:url];
2283 return [applications count] == 0 ? nil : applications;
2286 - (Source *) source {
2288 @synchronized (database_) {
2289 if ([database_ era] != era_ || file_.end())
2292 source_ = [database_ getSource:file_.File()];
2304 - (NSString *) role {
2308 - (BOOL) matches:(NSString *)text {
2314 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2315 if (range.location != NSNotFound)
2318 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2319 if (range.location != NSNotFound)
2322 range = [[self tagline] rangeOfString:text options:MatchCompareOptions_];
2323 if (range.location != NSNotFound)
2329 - (bool) hasSupportingRole {
2332 if ([role_ isEqualToString:@"enduser"])
2334 if ([Role_ isEqualToString:@"User"])
2336 if ([role_ isEqualToString:@"hacker"])
2338 if ([Role_ isEqualToString:@"Hacker"])
2340 if ([role_ isEqualToString:@"developer"])
2342 if ([Role_ isEqualToString:@"Developer"])
2347 - (BOOL) hasTag:(NSString *)tag {
2348 return tags_ == nil ? NO : [tags_ containsObject:tag];
2351 - (NSString *) primaryPurpose {
2352 for (NSString *tag in tags_)
2353 if ([tag hasPrefix:@"purpose::"])
2354 return [tag substringFromIndex:9];
2358 - (NSArray *) purposes {
2359 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2360 for (NSString *tag in tags_)
2361 if ([tag hasPrefix:@"purpose::"])
2362 [purposes addObject:[tag substringFromIndex:9]];
2363 return [purposes count] == 0 ? nil : purposes;
2366 - (bool) isCommercial {
2367 return [self hasTag:@"cydia::commercial"];
2370 - (uint32_t) compareByPrefix {
2374 - (NSComparisonResult) compareByName:(Package *)package {
2375 NSString *lhs = [self name];
2376 NSString *rhs = [package name];
2378 if ([lhs length] != 0 && [rhs length] != 0) {
2379 unichar lhc = [lhs characterAtIndex:0];
2380 unichar rhc = [rhs characterAtIndex:0];
2382 if (isalpha(lhc) && !isalpha(rhc))
2383 return NSOrderedAscending;
2384 else if (!isalpha(lhc) && isalpha(rhc))
2385 return NSOrderedDescending;
2388 return [lhs compare:rhs options:LaxCompareOptions_];
2391 - (uint32_t) compareBySection:(NSArray *)sections {
2392 NSString *section([self section]);
2393 for (size_t i(0), e([sections count]); i != e; ++i) {
2394 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2398 return _not(uint32_t);
2401 - (uint32_t) compareForChanges {
2406 uint32_t timestamp : 30;
2407 uint32_t ignored : 1;
2408 uint32_t upgradable : 1;
2412 bool upgradable([self upgradableAndEssential:YES]);
2413 value.bits.upgradable = upgradable ? 1 : 0;
2416 value.bits.timestamp = 0;
2417 value.bits.ignored = [self ignored] ? 0 : 1;
2418 value.bits.upgradable = 1;
2420 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2421 value.bits.ignored = 0;
2422 value.bits.upgradable = 0;
2425 return _not(uint32_t) - value.key;
2429 pkgProblemResolver *resolver = [database_ resolver];
2430 resolver->Clear(iterator_);
2431 resolver->Protect(iterator_);
2435 pkgProblemResolver *resolver = [database_ resolver];
2436 resolver->Clear(iterator_);
2437 resolver->Protect(iterator_);
2438 pkgCacheFile &cache([database_ cache]);
2439 cache->MarkInstall(iterator_, false);
2440 pkgDepCache::StateCache &state((*cache)[iterator_]);
2441 if (!state.Install())
2442 cache->SetReInstall(iterator_, true);
2446 pkgProblemResolver *resolver = [database_ resolver];
2447 resolver->Clear(iterator_);
2448 resolver->Protect(iterator_);
2449 resolver->Remove(iterator_);
2450 [database_ cache]->MarkDelete(iterator_, true);
2453 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2454 _profile(Package$isUnfilteredAndSearchedForBy)
2457 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2458 value &= [self unfiltered];
2461 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2462 value &= [self matches:search];
2469 - (bool) isInstalledAndVisible:(NSNumber *)number {
2470 return (![number boolValue] || [self visible]) && [self installed] != nil;
2473 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2474 NSString *section = [self section];
2478 [self installed] == nil && (
2480 section == nil && [name length] == 0 ||
2481 [name isEqualToString:section]
2485 - (bool) isVisibleInSource:(Source *)source {
2486 return [self source] == source && [self visible];
2491 /* Section Class {{{ */
2492 @interface Section : NSObject {
2497 NSString *localized_;
2500 - (NSComparisonResult) compareByName:(Section *)section;
2501 - (Section *) initWithName:(NSString *)name;
2502 - (Section *) initWithName:(NSString *)name row:(size_t)row;
2503 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2504 - (NSString *) name;
2511 - (void) addToCount;
2513 - (void) setCount:(size_t)count;
2517 @implementation Section
2521 if (localized_ != nil)
2522 [localized_ release];
2526 - (NSComparisonResult) compareByName:(Section *)section {
2527 NSString *lhs = [self name];
2528 NSString *rhs = [section name];
2530 if ([lhs length] != 0 && [rhs length] != 0) {
2531 unichar lhc = [lhs characterAtIndex:0];
2532 unichar rhc = [rhs characterAtIndex:0];
2534 if (isalpha(lhc) && !isalpha(rhc))
2535 return NSOrderedAscending;
2536 else if (!isalpha(lhc) && isalpha(rhc))
2537 return NSOrderedDescending;
2540 return [lhs compare:rhs options:LaxCompareOptions_];
2543 - (Section *) initWithName:(NSString *)name {
2544 return [self initWithName:name row:0];
2547 - (Section *) initWithName:(NSString *)name row:(size_t)row {
2548 if ((self = [super init]) != nil) {
2549 name_ = [name retain];
2552 localized_ = [LocalizeSection(name_) retain];
2556 /* XXX: localize the index thingees */
2557 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2558 if ((self = [super init]) != nil) {
2559 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2565 - (NSString *) name {
2585 - (void) addToCount {
2589 - (void) setCount:(size_t)count {
2593 - (NSString *) localized {
2601 static NSArray *Finishes_;
2603 /* Database Implementation {{{ */
2604 @implementation Database
2606 + (Database *) sharedInstance {
2607 static Database *instance;
2608 if (instance == nil)
2609 instance = [[Database alloc] init];
2619 NSRecycleZone(zone_);
2620 // XXX: malloc_destroy_zone(zone_);
2621 apr_pool_destroy(pool_);
2625 - (void) _readCydia:(NSNumber *)fd { _pooled
2626 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2627 std::istream is(&ib);
2630 static Pcre finish_r("^finish:([^:]*)$");
2632 while (std::getline(is, line)) {
2633 const char *data(line.c_str());
2634 size_t size = line.size();
2635 lprintf("C:%s\n", data);
2637 if (finish_r(data, size)) {
2638 NSString *finish = finish_r[1];
2639 int index = [Finishes_ indexOfObject:finish];
2640 if (index != INT_MAX && index > Finish_)
2648 - (void) _readStatus:(NSNumber *)fd { _pooled
2649 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2650 std::istream is(&ib);
2653 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2654 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2656 while (std::getline(is, line)) {
2657 const char *data(line.c_str());
2658 size_t size = line.size();
2659 lprintf("S:%s\n", data);
2661 if (conffile_r(data, size)) {
2662 [delegate_ setConfigurationData:conffile_r[1]];
2663 } else if (strncmp(data, "status: ", 8) == 0) {
2664 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2665 [delegate_ setProgressTitle:string];
2666 } else if (pmstatus_r(data, size)) {
2667 std::string type([pmstatus_r[1] UTF8String]);
2668 NSString *id = pmstatus_r[2];
2670 float percent([pmstatus_r[3] floatValue]);
2671 [delegate_ setProgressPercent:(percent / 100)];
2673 NSString *string = pmstatus_r[4];
2675 if (type == "pmerror")
2676 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2677 withObject:[NSArray arrayWithObjects:string, id, nil]
2680 else if (type == "pmstatus") {
2681 [delegate_ setProgressTitle:string];
2682 } else if (type == "pmconffile")
2683 [delegate_ setConfigurationData:string];
2684 else _assert(false);
2685 } else _assert(false);
2691 - (void) _readOutput:(NSNumber *)fd { _pooled
2692 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2693 std::istream is(&ib);
2696 while (std::getline(is, line)) {
2697 lprintf("O:%s\n", line.c_str());
2698 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2708 - (Package *) packageWithName:(NSString *)name {
2709 if (static_cast<pkgDepCache *>(cache_) == NULL)
2711 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2712 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2715 - (Database *) init {
2716 if ((self = [super init]) != nil) {
2723 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2724 apr_pool_create(&pool_, NULL);
2726 sources_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];
2727 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
2731 _assert(pipe(fds) != -1);
2734 _config->Set("APT::Keep-Fds::", cydiafd_);
2735 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
2738 detachNewThreadSelector:@selector(_readCydia:)
2740 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2743 _assert(pipe(fds) != -1);
2747 detachNewThreadSelector:@selector(_readStatus:)
2749 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2752 _assert(pipe(fds) != -1);
2753 _assert(dup2(fds[0], 0) != -1);
2754 _assert(close(fds[0]) != -1);
2756 input_ = fdopen(fds[1], "a");
2758 _assert(pipe(fds) != -1);
2759 _assert(dup2(fds[1], 1) != -1);
2760 _assert(close(fds[1]) != -1);
2763 detachNewThreadSelector:@selector(_readOutput:)
2765 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2770 - (pkgCacheFile &) cache {
2774 - (pkgDepCache::Policy *) policy {
2778 - (pkgRecords *) records {
2782 - (pkgProblemResolver *) resolver {
2786 - (pkgAcquire &) fetcher {
2790 - (pkgSourceList &) list {
2794 - (NSArray *) packages {
2798 - (NSArray *) sources {
2799 return [sources_ allValues];
2802 - (NSArray *) issues {
2803 if (cache_->BrokenCount() == 0)
2806 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
2808 for (Package *package in packages_) {
2809 if (![package broken])
2811 pkgCache::PkgIterator pkg([package iterator]);
2813 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
2814 [entry addObject:[package name]];
2815 [issues addObject:entry];
2817 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
2821 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
2822 pkgCache::DepIterator start;
2823 pkgCache::DepIterator end;
2824 dep.GlobOr(start, end); // ++dep
2826 if (!cache_->IsImportantDep(end))
2828 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
2831 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
2832 [entry addObject:failure];
2833 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
2835 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
2836 [failure addObject:[package name]];
2838 pkgCache::PkgIterator target(start.TargetPkg());
2839 if (target->ProvidesList != 0)
2840 [failure addObject:@"?"];
2842 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
2844 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
2845 else if (!cache_[target].CandidateVerIter(cache_).end())
2846 [failure addObject:@"-"];
2847 else if (target->ProvidesList == 0)
2848 [failure addObject:@"!"];
2850 [failure addObject:@"%"];
2854 if (start.TargetVer() != 0)
2855 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
2866 - (void) reloadData { _pooled
2867 @synchronized (self) {
2889 apr_pool_clear(pool_);
2890 NSRecycleZone(zone_);
2892 int chk(creat("/tmp/cydia.chk", 0644));
2897 if (!cache_.Open(progress_, true)) {
2899 if (!_error->PopMessage(error))
2902 lprintf("cache_.Open():[%s]\n", error.c_str());
2904 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
2905 [delegate_ repairWithSelector:@selector(configure)];
2906 else if (error == "The package lists or status file could not be parsed or opened.")
2907 [delegate_ repairWithSelector:@selector(update)];
2908 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
2909 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
2910 // else if (error == "The list of sources could not be read.")
2911 else _assert(false);
2917 unlink("/tmp/cydia.chk");
2919 now_ = [[NSDate date] retain];
2921 policy_ = new pkgDepCache::Policy();
2922 records_ = new pkgRecords(cache_);
2923 resolver_ = new pkgProblemResolver(cache_);
2924 fetcher_ = new pkgAcquire(&status_);
2927 list_ = new pkgSourceList();
2928 _assert(list_->ReadMainList());
2930 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
2931 _assert(pkgApplyStatus(cache_));
2933 if (cache_->BrokenCount() != 0) {
2934 _assert(pkgFixBroken(cache_));
2935 _assert(cache_->BrokenCount() == 0);
2936 _assert(pkgMinimizeUpgrade(cache_));
2941 std::string lists(_config->FindDir("Dir::State::lists"));
2943 [sources_ removeAllObjects];
2944 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
2945 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
2946 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
2947 if (debPackagesIndex *packages = dynamic_cast<debPackagesIndex *>(*index))
2949 setObject:[[[Source alloc] initWithMetaIndex:*source] autorelease]
2950 forKey:[NSString stringWithFormat:@"%s%s",
2952 URItoFileName(packages->IndexURI("Packages")).c_str()
2959 [packages_ removeAllObjects];
2961 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
2962 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
2963 [packages_ addObject:package];
2965 [packages_ sortUsingSelector:@selector(compareByName:)];
2968 _config->Set("Acquire::http::Timeout", 15);
2969 _config->Set("Acquire::http::MaxParallel", 4);
2972 - (void) configure {
2973 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
2974 system([dpkg UTF8String]);
2982 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
2983 _assert(!_error->PendingError());
2986 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
2989 public pkgArchiveCleaner
2992 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
2997 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
2999 while (_error->PopMessage(error))
3000 lprintf("ArchiveCleaner: %s\n", error.c_str());
3005 pkgRecords records(cache_);
3007 lock_ = new FileFd();
3008 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3009 _assert(!_error->PendingError());
3012 // XXX: explain this with an error message
3013 _assert(list.ReadMainList());
3015 manager_ = (_system->CreatePM(cache_));
3016 _assert(manager_->GetArchives(fetcher_, &list, &records));
3017 _assert(!_error->PendingError());
3021 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3023 _assert(list.ReadMainList());
3024 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3025 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3028 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3033 bool failed = false;
3034 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3035 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3038 std::string uri = (*item)->DescURI();
3039 std::string error = (*item)->ErrorText;
3041 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3044 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3045 withObject:[NSArray arrayWithObjects:
3046 [NSString stringWithUTF8String:error.c_str()],
3058 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3060 if (_error->PendingError()) {
3065 if (result == pkgPackageManager::Failed) {
3070 if (result != pkgPackageManager::Completed) {
3075 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3077 _assert(list.ReadMainList());
3078 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3079 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3082 if (![before isEqualToArray:after])
3087 _assert(pkgDistUpgrade(cache_));
3091 [self updateWithStatus:status_];
3094 - (void) updateWithStatus:(Status &)status {
3096 _assert(list.ReadMainList());
3099 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3100 _assert(!_error->PendingError());
3102 pkgAcquire fetcher(&status);
3103 _assert(list.GetIndexes(&fetcher));
3105 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3106 bool failed = false;
3107 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3108 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3109 (*item)->Finished();
3113 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3114 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3115 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3118 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3123 - (void) setDelegate:(id)delegate {
3124 delegate_ = delegate;
3125 status_.setDelegate(delegate);
3126 progress_.setDelegate(delegate);
3129 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3130 if (const char *name = file.FileName())
3131 if (Source *source = [sources_ objectForKey:[NSString stringWithUTF8String:name]])
3139 /* PopUp Windows {{{ */
3140 @interface PopUpView : UIView {
3141 _transient id delegate_;
3142 UITransitionView *transition_;
3147 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3151 @implementation PopUpView
3154 [transition_ setDelegate:nil];
3155 [transition_ release];
3161 [transition_ transition:UITransitionPushFromTop toView:nil];
3164 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3165 if (from != nil && to == nil)
3166 [self removeFromSuperview];
3169 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3170 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3171 delegate_ = delegate;
3173 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3174 [self addSubview:transition_];
3176 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3178 [view addSubview:self];
3180 [transition_ setDelegate:self];
3182 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3183 [transition_ transition:UITransitionNone toView:blank];
3184 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3192 /* Mail Composition {{{ */
3193 @interface MailToView : PopUpView {
3194 MailComposeController *controller_;
3197 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3201 @implementation MailToView
3204 [controller_ release];
3208 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3212 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3213 NSLog(@"did:%@", delivery);
3214 // [UIApp setStatusBarShowsProgress:NO];
3215 if ([controller error]){
3216 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3217 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3218 [mailAlertSheet setBodyText:[controller error]];
3219 [mailAlertSheet popupAlertAnimated:YES];
3223 - (void) showError {
3224 NSLog(@"%@", [controller_ error]);
3225 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3226 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3227 [mailAlertSheet setBodyText:[controller_ error]];
3228 [mailAlertSheet popupAlertAnimated:YES];
3231 - (void) deliverMessage { _pooled
3235 if (![controller_ deliverMessage])
3236 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3239 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3240 if ([controller_ needsDelivery])
3241 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3246 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3247 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3248 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3249 [controller_ setDelegate:self];
3250 [controller_ initializeUI];
3251 [controller_ setupForURL:url];
3253 UIView *view([controller_ view]);
3254 [overlay_ addSubview:view];
3262 /* Confirmation View {{{ */
3263 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3264 if (!iterator.end())
3265 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3266 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3268 pkgCache::PkgIterator package(dep.TargetPkg());
3271 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3278 @protocol ConfirmationViewDelegate
3284 @interface ConfirmationView : BrowserView {
3285 _transient Database *database_;
3286 UIActionSheet *essential_;
3293 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3297 @implementation ConfirmationView
3304 if (essential_ != nil)
3305 [essential_ release];
3311 [book_ popFromSuperviewAnimated:YES];
3314 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3315 NSString *context([sheet context]);
3317 if ([context isEqualToString:@"remove"]) {
3325 [delegate_ confirm];
3332 } else if ([context isEqualToString:@"unable"]) {
3336 [super alertSheet:sheet buttonClicked:button];
3339 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3340 [super webView:sender didClearWindowObject:window forFrame:frame];
3341 [window setValue:changes_ forKey:@"changes"];
3342 [window setValue:issues_ forKey:@"issues"];
3343 [window setValue:sizes_ forKey:@"sizes"];
3346 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3347 if ((self = [super initWithBook:book]) != nil) {
3348 database_ = database;
3350 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3351 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3352 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3353 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3354 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3358 pkgDepCache::Policy *policy([database_ policy]);
3360 pkgCacheFile &cache([database_ cache]);
3361 NSArray *packages = [database_ packages];
3362 for (Package *package in packages) {
3363 pkgCache::PkgIterator iterator = [package iterator];
3364 pkgDepCache::StateCache &state(cache[iterator]);
3366 NSString *name([package name]);
3368 if (state.NewInstall())
3369 [installing addObject:name];
3370 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3371 [reinstalling addObject:name];
3372 else if (state.Upgrade())
3373 [upgrading addObject:name];
3374 else if (state.Downgrade())
3375 [downgrading addObject:name];
3376 else if (state.Delete()) {
3377 if ([package essential])
3379 [removing addObject:name];
3382 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3383 substrate_ |= DepSubstrate(iterator.CurrentVer());
3388 else if (Advanced_ || true) {
3389 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3391 essential_ = [[UIActionSheet alloc]
3392 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3393 buttons:[NSArray arrayWithObjects:
3394 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3395 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3397 defaultButtonIndex:0
3403 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3405 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3407 essential_ = [[UIActionSheet alloc]
3408 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3409 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3410 defaultButtonIndex:0
3415 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3418 changes_ = [[NSArray alloc] initWithObjects:
3426 issues_ = [database_ issues];
3428 issues_ = [issues_ retain];
3430 sizes_ = [[NSArray alloc] initWithObjects:
3431 SizeString([database_ fetcher].FetchNeeded()),
3432 SizeString([database_ fetcher].PartialPresent()),
3433 SizeString([database_ cache]->UsrSize()),
3436 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3440 - (NSString *) backButtonTitle {
3441 return CYLocalize("CONFIRM");
3444 - (NSString *) leftButtonTitle {
3445 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3448 - (id) rightButtonTitle {
3449 return issues_ != nil ? nil : [super rightButtonTitle];
3452 - (id) _rightButtonTitle {
3453 #if AlwaysReload || IgnoreInstall
3454 return [super _rightButtonTitle];
3456 return CYLocalize("CONFIRM");
3460 - (void) _leftButtonClicked {
3465 - (void) _rightButtonClicked {
3467 return [super _rightButtonClicked];
3469 if (essential_ != nil)
3470 [essential_ popupAlertAnimated:YES];
3474 [delegate_ confirm];
3482 /* Progress Data {{{ */
3483 @interface ProgressData : NSObject {
3489 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3496 @implementation ProgressData
3498 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3499 if ((self = [super init]) != nil) {
3500 selector_ = selector;
3520 /* Progress View {{{ */
3521 @interface ProgressView : UIView <
3522 ConfigurationDelegate,
3525 _transient Database *database_;
3527 UIView *background_;
3528 UITransitionView *transition_;
3530 UINavigationBar *navbar_;
3531 UIProgressBar *progress_;
3532 UITextView *output_;
3533 UITextLabel *status_;
3534 UIPushButton *close_;
3537 SHA1SumValue springlist_;
3538 SHA1SumValue notifyconf_;
3539 SHA1SumValue sandplate_;
3542 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3544 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3545 - (void) setContentView:(UIView *)view;
3548 - (void) _retachThread;
3549 - (void) _detachNewThreadData:(ProgressData *)data;
3550 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3556 @protocol ProgressViewDelegate
3557 - (void) progressViewIsComplete:(ProgressView *)sender;
3560 @implementation ProgressView
3563 [transition_ setDelegate:nil];
3564 [navbar_ setDelegate:nil];
3567 if (background_ != nil)
3568 [background_ release];
3569 [transition_ release];
3572 [progress_ release];
3579 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3580 if (bootstrap_ && from == overlay_ && to == view_)
3584 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3585 if ((self = [super initWithFrame:frame]) != nil) {
3586 database_ = database;
3587 delegate_ = delegate;
3589 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3590 [transition_ setDelegate:self];
3592 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3595 [overlay_ setBackgroundColor:[UIColor blackColor]];
3597 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3598 [background_ setBackgroundColor:[UIColor blackColor]];
3599 [self addSubview:background_];
3602 [self addSubview:transition_];
3604 CGSize navsize = [UINavigationBar defaultSize];
3605 CGRect navrect = {{0, 0}, navsize};
3607 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3608 [overlay_ addSubview:navbar_];
3610 [navbar_ setBarStyle:1];
3611 [navbar_ setDelegate:self];
3613 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3614 [navbar_ pushNavigationItem:navitem];
3616 CGRect bounds = [overlay_ bounds];
3617 CGSize prgsize = [UIProgressBar defaultSize];
3620 (bounds.size.width - prgsize.width) / 2,
3621 bounds.size.height - prgsize.height - 20
3624 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3625 [progress_ setStyle:0];
3627 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3629 bounds.size.height - prgsize.height - 50,
3630 bounds.size.width - 20,
3634 [status_ setColor:[UIColor whiteColor]];
3635 [status_ setBackgroundColor:[UIColor clearColor]];
3637 [status_ setCentersHorizontally:YES];
3638 //[status_ setFont:font];
3641 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3643 navrect.size.height + 20,
3644 bounds.size.width - 20,
3645 bounds.size.height - navsize.height - 62 - navrect.size.height
3649 //[output_ setTextFont:@"Courier New"];
3650 [output_ setTextSize:12];
3652 [output_ setTextColor:[UIColor whiteColor]];
3653 [output_ setBackgroundColor:[UIColor clearColor]];
3655 [output_ setMarginTop:0];
3656 [output_ setAllowsRubberBanding:YES];
3657 [output_ setEditable:NO];
3659 [overlay_ addSubview:output_];
3661 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3663 bounds.size.height - prgsize.height - 50,
3664 bounds.size.width - 20,
3668 [close_ setAutosizesToFit:NO];
3669 [close_ setDrawsShadow:YES];
3670 [close_ setStretchBackground:YES];
3671 [close_ setEnabled:YES];
3673 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3674 [close_ setTitleFont:bold];
3676 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3677 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3678 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3682 - (void) setContentView:(UIView *)view {
3683 view_ = [view retain];
3686 - (void) resetView {
3687 [transition_ transition:6 toView:view_];
3690 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3691 NSString *context([sheet context]);
3693 if ([context isEqualToString:@"error"])
3695 else if ([context isEqualToString:@"conffile"]) {
3696 FILE *input = [database_ input];
3700 fprintf(input, "N\n");
3704 fprintf(input, "Y\n");
3715 - (void) closeButtonPushed {
3724 [delegate_ suspendWithAnimation:YES];
3728 system("launchctl stop com.apple.SpringBoard");
3732 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
3741 - (void) _retachThread {
3742 UINavigationItem *item = [navbar_ topItem];
3743 [item setTitle:CYLocalize("COMPLETE")];
3745 [overlay_ addSubview:close_];
3746 [progress_ removeFromSuperview];
3747 [status_ removeFromSuperview];
3749 [delegate_ progressViewIsComplete:self];
3752 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
3753 MMap mmap(file, MMap::ReadOnly);
3755 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3756 if (!(sandplate_ == sha1.Result()))
3761 FileFd file(NotifyConfig_, FileFd::ReadOnly);
3762 MMap mmap(file, MMap::ReadOnly);
3764 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3765 if (!(notifyconf_ == sha1.Result()))
3770 FileFd file(SpringBoard_, FileFd::ReadOnly);
3771 MMap mmap(file, MMap::ReadOnly);
3773 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3774 if (!(springlist_ == sha1.Result()))
3779 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
3780 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
3781 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
3782 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
3783 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
3786 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
3788 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
3789 [cache autorelease];
3791 NSFileManager *manager = [NSFileManager defaultManager];
3792 NSError *error = nil;
3794 id system = [cache objectForKey:@"System"];
3799 if (stat(Cache_, &info) == -1)
3802 [system removeAllObjects];
3804 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
3805 for (NSString *app in apps)
3806 if ([app hasSuffix:@".app"]) {
3807 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
3808 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
3809 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
3811 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
3812 [info setObject:path forKey:@"Path"];
3813 [info setObject:@"System" forKey:@"ApplicationType"];
3814 [system addInfoDictionary:info];
3820 [cache writeToFile:@Cache_ atomically:YES];
3822 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
3824 if (chmod(Cache_, info.st_mode) == -1)
3828 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
3831 notify_post("com.apple.mobile.application_installed");
3833 [delegate_ setStatusBarShowsProgress:NO];
3836 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
3837 [[data target] performSelector:[data selector] withObject:[data object]];
3840 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
3843 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
3844 UINavigationItem *item = [navbar_ topItem];
3845 [item setTitle:title];
3847 [status_ setText:nil];
3848 [output_ setText:@""];
3849 [progress_ setProgress:0];
3851 [close_ removeFromSuperview];
3852 [overlay_ addSubview:progress_];
3853 [overlay_ addSubview:status_];
3855 [delegate_ setStatusBarShowsProgress:YES];
3859 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
3860 MMap mmap(file, MMap::ReadOnly);
3862 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3863 sandplate_ = sha1.Result();
3867 FileFd file(NotifyConfig_, FileFd::ReadOnly);
3868 MMap mmap(file, MMap::ReadOnly);
3870 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3871 notifyconf_ = sha1.Result();
3875 FileFd file(SpringBoard_, FileFd::ReadOnly);
3876 MMap mmap(file, MMap::ReadOnly);
3878 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3879 springlist_ = sha1.Result();
3882 [transition_ transition:6 toView:overlay_];
3885 detachNewThreadSelector:@selector(_detachNewThreadData:)
3887 withObject:[[ProgressData alloc]
3888 initWithSelector:selector
3895 - (void) repairWithSelector:(SEL)selector {
3897 detachNewThreadSelector:selector
3900 title:CYLocalize("REPAIRING")
3904 - (void) setConfigurationData:(NSString *)data {
3906 performSelectorOnMainThread:@selector(_setConfigurationData:)
3912 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
3913 Package *package = id == nil ? nil : [database_ packageWithName:id];
3915 UIActionSheet *sheet = [[[UIActionSheet alloc]
3916 initWithTitle:(package == nil ? id : [package name])
3917 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3918 defaultButtonIndex:0
3923 [sheet setBodyText:error];
3924 [sheet popupAlertAnimated:YES];
3927 - (void) setProgressTitle:(NSString *)title {
3929 performSelectorOnMainThread:@selector(_setProgressTitle:)
3935 - (void) setProgressPercent:(float)percent {
3937 performSelectorOnMainThread:@selector(_setProgressPercent:)
3938 withObject:[NSNumber numberWithFloat:percent]
3943 - (void) startProgress {
3946 - (void) addProgressOutput:(NSString *)output {
3948 performSelectorOnMainThread:@selector(_addProgressOutput:)
3954 - (bool) isCancelling:(size_t)received {
3958 - (void) _setConfigurationData:(NSString *)data {
3959 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
3961 _assert(conffile_r(data));
3963 NSString *ofile = conffile_r[1];
3964 //NSString *nfile = conffile_r[2];
3966 UIActionSheet *sheet = [[[UIActionSheet alloc]
3967 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
3968 buttons:[NSArray arrayWithObjects:
3969 CYLocalize("KEEP_OLD_COPY"),
3970 CYLocalize("ACCEPT_NEW_COPY"),
3971 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
3973 defaultButtonIndex:0
3978 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
3979 [sheet popupAlertAnimated:YES];
3982 - (void) _setProgressTitle:(NSString *)title {
3983 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
3984 for (size_t i(0), e([words count]); i != e; ++i) {
3985 NSString *word([words objectAtIndex:i]);
3986 if (Package *package = [database_ packageWithName:word])
3987 [words replaceObjectAtIndex:i withObject:[package name]];
3990 [status_ setText:[words componentsJoinedByString:@" "]];
3993 - (void) _setProgressPercent:(NSNumber *)percent {
3994 [progress_ setProgress:[percent floatValue]];
3997 - (void) _addProgressOutput:(NSString *)output {
3998 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
3999 CGSize size = [output_ contentSize];
4000 CGRect rect = {{0, size.height}, {size.width, 0}};
4001 [output_ scrollRectToVisible:rect animated:YES];
4004 - (BOOL) isRunning {
4011 /* Package Cell {{{ */
4012 @interface PackageCell : UITableCell {
4015 NSString *description_;
4022 UITextLabel *status_;
4026 - (PackageCell *) init;
4027 - (void) setPackage:(Package *)package;
4029 + (int) heightForPackage:(Package *)package;
4033 @implementation PackageCell
4035 - (void) clearPackage {
4046 if (description_ != nil) {
4047 [description_ release];
4051 if (source_ != nil) {
4056 if (badge_ != nil) {
4066 [self clearPackage];
4073 - (PackageCell *) init {
4074 if ((self = [super init]) != nil) {
4076 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4077 [status_ setBackgroundColor:[UIColor clearColor]];
4078 [status_ setFont:small];
4083 - (void) setPackage:(Package *)package {
4084 [self clearPackage];
4086 Source *source = [package source];
4088 icon_ = [[package icon] retain];
4089 name_ = [[package name] retain];
4090 description_ = [[package tagline] retain];
4091 commercial_ = [package isCommercial];
4093 package_ = [package retain];
4095 NSString *label = nil;
4096 bool trusted = false;
4098 if (source != nil) {
4099 label = [source label];
4100 trusted = [source trusted];
4101 } else if ([[package id] isEqualToString:@"firmware"])
4102 label = CYLocalize("APPLE");
4104 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4106 NSString *from(label);
4108 NSString *section = [package simpleSection];
4109 if (section != nil && ![section isEqualToString:label]) {
4110 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4111 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4114 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4115 source_ = [from retain];
4117 if (NSString *purpose = [package primaryPurpose])
4118 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4119 badge_ = [badge_ retain];
4122 if (NSString *mode = [package mode]) {
4123 [badge_ setImage:[UIImage applicationImageNamed:
4124 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4127 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4128 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4129 } else if ([package half]) {
4130 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4131 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4132 [status_ setColor:[UIColor redColor]];
4134 [badge_ setImage:nil];
4135 [status_ setText:nil];
4142 - (void) drawRect:(CGRect)rect {
4146 if (NSString *mode = [package_ mode]) {
4147 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4148 color = remove ? RemovingColor_ : InstallingColor_;
4150 color = [UIColor whiteColor];
4152 [self setBackgroundColor:color];
4156 [super drawRect:rect];
4159 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4161 CGContextRef context(UIGraphicsGetCurrentContext());
4162 [[self backgroundColor] set];
4164 back.size.height -= 1;
4165 CGContextFillRect(context, back);
4168 [super drawBackgroundInRect:rect withFade:fade];
4171 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4174 rect.size = [icon_ size];
4176 rect.size.width /= 2;
4177 rect.size.height /= 2;
4179 rect.origin.x = 25 - rect.size.width / 2;
4180 rect.origin.y = 25 - rect.size.height / 2;
4182 [icon_ drawInRect:rect];
4185 if (badge_ != nil) {
4186 CGSize size = [badge_ size];
4188 [badge_ drawAtPoint:CGPointMake(
4189 36 - size.width / 2,
4190 36 - size.height / 2
4198 UISetColor(commercial_ ? Purple_ : Black_);
4199 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4200 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4203 UISetColor(commercial_ ? Purplish_ : Gray_);
4204 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4206 [super drawContentInRect:rect selected:selected];
4209 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4211 [super setSelected:selected withFade:fade];
4214 + (int) heightForPackage:(Package *)package {
4215 NSString *tagline([package tagline]);
4216 int height = tagline == nil || [tagline length] == 0 ? -17 : 0;
4218 if ([package hasMode] || [package half])
4227 /* Section Cell {{{ */
4228 @interface SectionCell : UISimpleTableCell {
4233 _UISwitchSlider *switch_;
4238 - (void) setSection:(Section *)section editing:(BOOL)editing;
4242 @implementation SectionCell
4244 - (void) clearSection {
4245 if (section_ != nil) {
4255 if (count_ != nil) {
4262 [self clearSection];
4269 if ((self = [super init]) != nil) {
4270 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4272 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4273 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4277 - (void) onSwitch:(id)sender {
4278 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4279 if (metadata == nil) {
4280 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4281 [Sections_ setObject:metadata forKey:section_];
4285 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4288 - (void) setSection:(Section *)section editing:(BOOL)editing {
4289 if (editing != editing_) {
4291 [switch_ removeFromSuperview];
4293 [self addSubview:switch_];
4297 [self clearSection];
4299 if (section == nil) {
4300 name_ = [CYLocalize("ALL_PACKAGES") retain];
4303 section_ = [section name];
4304 if (section_ != nil)
4305 section_ = [section_ retain];
4306 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4307 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4310 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4314 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4315 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4322 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4324 CGSize size = [count_ sizeWithFont:Font14_];
4328 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4330 [super drawContentInRect:rect selected:selected];
4336 /* File Table {{{ */
4337 @interface FileTable : RVPage {
4338 _transient Database *database_;
4341 NSMutableArray *files_;
4345 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4346 - (void) setPackage:(Package *)package;
4350 @implementation FileTable
4353 if (package_ != nil)
4362 - (int) numberOfRowsInTable:(UITable *)table {
4363 return files_ == nil ? 0 : [files_ count];
4366 - (float) table:(UITable *)table heightForRow:(int)row {
4370 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4371 if (reusing == nil) {
4372 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4373 UIFont *font = [UIFont systemFontOfSize:16];
4374 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4376 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4380 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4384 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4385 if ((self = [super initWithBook:book]) != nil) {
4386 database_ = database;
4388 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4390 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4391 [self addSubview:list_];
4393 UITableColumn *column = [[[UITableColumn alloc]
4394 initWithTitle:CYLocalize("NAME")
4396 width:[self frame].size.width
4399 [list_ setDataSource:self];
4400 [list_ setSeparatorStyle:1];
4401 [list_ addTableColumn:column];
4402 [list_ setDelegate:self];
4403 [list_ setReusesTableCells:YES];
4407 - (void) setPackage:(Package *)package {
4408 if (package_ != nil) {
4409 [package_ autorelease];
4418 [files_ removeAllObjects];
4420 if (package != nil) {
4421 package_ = [package retain];
4422 name_ = [[package id] retain];
4424 if (NSArray *files = [package files])
4425 [files_ addObjectsFromArray:files];
4427 if ([files_ count] != 0) {
4428 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4429 [files_ removeObjectAtIndex:0];
4430 [files_ sortUsingSelector:@selector(compareByPath:)];
4432 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4433 [stack addObject:@"/"];
4435 for (int i(0), e([files_ count]); i != e; ++i) {
4436 NSString *file = [files_ objectAtIndex:i];
4437 while (![file hasPrefix:[stack lastObject]])
4438 [stack removeLastObject];
4439 NSString *directory = [stack lastObject];
4440 [stack addObject:[file stringByAppendingString:@"/"]];
4441 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4442 ([stack count] - 2) * 3, "",
4443 [file substringFromIndex:[directory length]]
4452 - (void) resetViewAnimated:(BOOL)animated {
4453 [list_ resetViewAnimated:animated];
4456 - (void) reloadData {
4457 [self setPackage:[database_ packageWithName:name_]];
4458 [self reloadButtons];
4461 - (NSString *) title {
4462 return CYLocalize("INSTALLED_FILES");
4465 - (NSString *) backButtonTitle {
4466 return CYLocalize("FILES");
4471 /* Package View {{{ */
4472 @interface PackageView : BrowserView {
4473 _transient Database *database_;
4477 NSMutableArray *buttons_;
4480 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4481 - (void) setPackage:(Package *)package;
4485 @implementation PackageView
4488 if (package_ != nil)
4497 if ([self retainCount] == 1)
4498 [delegate_ setPackageView:self];
4502 /* XXX: this is not safe at all... localization of /fail/ */
4503 - (void) _clickButtonWithName:(NSString *)name {
4504 if ([name isEqualToString:CYLocalize("CLEAR")])
4505 [delegate_ clearPackage:package_];
4506 else if ([name isEqualToString:CYLocalize("INSTALL")])
4507 [delegate_ installPackage:package_];
4508 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4509 [delegate_ installPackage:package_];
4510 else if ([name isEqualToString:CYLocalize("REMOVE")])
4511 [delegate_ removePackage:package_];
4512 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4513 [delegate_ installPackage:package_];
4514 else _assert(false);
4517 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4518 NSString *context([sheet context]);
4520 if ([context isEqualToString:@"modify"]) {
4521 int count = [buttons_ count];
4522 _assert(count != 0);
4523 _assert(button <= count + 1);
4525 if (count != button - 1)
4526 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4530 [super alertSheet:sheet buttonClicked:button];
4533 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4534 return [super webView:sender didFinishLoadForFrame:frame];
4537 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4538 [super webView:sender didClearWindowObject:window forFrame:frame];
4539 [window setValue:package_ forKey:@"package"];
4542 - (bool) _allowJavaScriptPanel {
4547 - (void) __rightButtonClicked {
4548 int count = [buttons_ count];
4549 _assert(count != 0);
4552 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4554 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4555 [buttons addObjectsFromArray:buttons_];
4556 [buttons addObject:CYLocalize("CANCEL")];
4558 [delegate_ slideUp:[[[UIActionSheet alloc]
4561 defaultButtonIndex:([buttons count] - 1)
4568 - (void) _rightButtonClicked {
4570 [super _rightButtonClicked];
4572 [self __rightButtonClicked];
4576 - (id) _rightButtonTitle {
4577 int count = [buttons_ count];
4578 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4581 - (NSString *) backButtonTitle {
4585 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4586 if ((self = [super initWithBook:book]) != nil) {
4587 database_ = database;
4588 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4589 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4593 - (void) setPackage:(Package *)package {
4594 if (package_ != nil) {
4595 [package_ autorelease];
4604 [buttons_ removeAllObjects];
4606 if (package != nil) {
4607 package_ = [package retain];
4608 name_ = [[package id] retain];
4609 commercial_ = [package isCommercial];
4611 if ([package_ mode] != nil)
4612 [buttons_ addObject:CYLocalize("CLEAR")];
4613 if ([package_ source] == nil);
4614 else if ([package_ upgradableAndEssential:NO])
4615 [buttons_ addObject:CYLocalize("UPGRADE")];
4616 else if ([package_ installed] == nil)
4617 [buttons_ addObject:CYLocalize("INSTALL")];
4619 [buttons_ addObject:CYLocalize("REINSTALL")];
4620 if ([package_ installed] != nil)
4621 [buttons_ addObject:CYLocalize("REMOVE")];
4623 if (special_ != NULL) {
4624 CGRect frame([webview_ frame]);
4625 frame.size.width = 320;
4626 frame.size.height = 0;
4627 [webview_ setFrame:frame];
4629 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4632 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4634 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4636 [self setFinishHook:nil];
4637 [self setPopupHook:nil];
4640 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
4641 [super callFunction:special_];
4645 [self reloadButtons];
4648 - (bool) isLoading {
4649 return commercial_ ? [super isLoading] : false;
4652 - (void) reloadData {
4653 [self setPackage:[database_ packageWithName:name_]];
4658 /* Package Table {{{ */
4659 @interface PackageTable : RVPage {
4660 _transient Database *database_;
4662 NSMutableArray *packages_;
4663 NSMutableArray *sections_;
4664 UISectionList *list_;
4667 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
4669 - (void) setDelegate:(id)delegate;
4671 - (void) reloadData;
4672 - (void) resetCursor;
4674 - (UISectionList *) list;
4676 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4680 @implementation PackageTable
4683 [list_ setDataSource:nil];
4686 [packages_ release];
4687 [sections_ release];
4692 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4693 return [sections_ count];
4696 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4697 return [[sections_ objectAtIndex:section] name];
4700 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4701 return [[sections_ objectAtIndex:section] row];
4704 - (int) numberOfRowsInTable:(UITable *)table {
4705 return [packages_ count];
4708 - (float) table:(UITable *)table heightForRow:(int)row {
4709 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
4712 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4714 reusing = [[[PackageCell alloc] init] autorelease];
4715 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
4719 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
4723 - (void) tableRowSelected:(NSNotification *)notification {
4724 int row = [[notification object] selectedRow];
4728 Package *package = [packages_ objectAtIndex:row];
4729 package = [database_ packageWithName:[package id]];
4730 PackageView *view([delegate_ packageView]);
4731 [view setPackage:package];
4732 [view setDelegate:delegate_];
4733 [book_ pushPage:view];
4736 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
4737 if ((self = [super initWithBook:book]) != nil) {
4738 database_ = database;
4739 title_ = [title retain];
4741 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
4742 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
4744 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
4745 [list_ setDataSource:self];
4747 UITableColumn *column = [[[UITableColumn alloc]
4748 initWithTitle:CYLocalize("NAME")
4750 width:[self frame].size.width
4753 UITable *table = [list_ table];
4754 [table setSeparatorStyle:1];
4755 [table addTableColumn:column];
4756 [table setDelegate:self];
4757 [table setReusesTableCells:YES];
4759 [self addSubview:list_];
4761 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4762 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4766 - (void) setDelegate:(id)delegate {
4767 delegate_ = delegate;
4770 - (bool) hasPackage:(Package *)package {
4774 - (void) reloadData {
4775 NSArray *packages = [database_ packages];
4777 [packages_ removeAllObjects];
4778 [sections_ removeAllObjects];
4780 _profile(PackageTable$reloadData$Filter)
4781 for (Package *package in packages)
4782 if ([self hasPackage:package])
4783 [packages_ addObject:package];
4786 Section *section = nil;
4788 _profile(PackageTable$reloadData$Section)
4789 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
4793 _profile(PackageTable$reloadData$Section$Package)
4794 package = [packages_ objectAtIndex:offset];
4795 index = [package index];
4798 if (section == nil || [section index] != index) {
4799 _profile(PackageTable$reloadData$Section$Allocate)
4800 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
4803 _profile(PackageTable$reloadData$Section$Add)
4804 [sections_ addObject:section];
4808 [section addToCount];
4812 _profile(PackageTable$reloadData$List)
4817 - (NSString *) title {
4821 - (void) resetViewAnimated:(BOOL)animated {
4822 [list_ resetViewAnimated:animated];
4825 - (void) resetCursor {
4826 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
4829 - (UISectionList *) list {
4833 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
4834 [list_ setShouldHideHeaderInShortLists:hide];
4839 /* Filtered Package Table {{{ */
4840 @interface FilteredPackageTable : PackageTable {
4846 - (void) setObject:(id)object;
4848 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
4852 @implementation FilteredPackageTable
4860 - (void) setObject:(id)object {
4866 object_ = [object retain];
4869 - (bool) hasPackage:(Package *)package {
4870 _profile(FilteredPackageTable$hasPackage)
4871 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
4875 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
4876 if ((self = [super initWithBook:book database:database title:title]) != nil) {
4878 object_ = object == nil ? nil : [object retain];
4880 /* XXX: this is an unsafe optimization of doomy hell */
4881 Method method = class_getInstanceMethod([Package class], filter);
4882 imp_ = method_getImplementation(method);
4883 _assert(imp_ != NULL);
4892 /* Add Source View {{{ */
4893 @interface AddSourceView : RVPage {
4894 _transient Database *database_;
4897 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4901 @implementation AddSourceView
4903 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4904 if ((self = [super initWithBook:book]) != nil) {
4905 database_ = database;
4911 /* Source Cell {{{ */
4912 @interface SourceCell : UITableCell {
4915 NSString *description_;
4921 - (SourceCell *) initWithSource:(Source *)source;
4925 @implementation SourceCell
4930 [description_ release];
4935 - (SourceCell *) initWithSource:(Source *)source {
4936 if ((self = [super init]) != nil) {
4938 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
4940 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
4941 icon_ = [icon_ retain];
4943 origin_ = [[source name] retain];
4944 label_ = [[source uri] retain];
4945 description_ = [[source description] retain];
4949 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4951 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
4958 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4962 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4966 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4968 [super drawContentInRect:rect selected:selected];
4973 /* Source Table {{{ */
4974 @interface SourceTable : RVPage {
4975 _transient Database *database_;
4976 UISectionList *list_;
4977 NSMutableArray *sources_;
4978 UIActionSheet *alert_;
4982 UIProgressHUD *hud_;
4985 //NSURLConnection *installer_;
4986 NSURLConnection *trivial_bz2_;
4987 NSURLConnection *trivial_gz_;
4988 //NSURLConnection *automatic_;
4993 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4997 @implementation SourceTable
4999 - (void) _deallocConnection:(NSURLConnection *)connection {
5000 if (connection != nil) {
5001 [connection cancel];
5002 //[connection setDelegate:nil];
5003 [connection release];
5008 [[list_ table] setDelegate:nil];
5009 [list_ setDataSource:nil];
5018 //[self _deallocConnection:installer_];
5019 [self _deallocConnection:trivial_gz_];
5020 [self _deallocConnection:trivial_bz2_];
5021 //[self _deallocConnection:automatic_];
5028 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5029 return offset_ == 0 ? 1 : 2;
5032 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5033 switch (section + (offset_ == 0 ? 1 : 0)) {
5034 case 0: return CYLocalize("ENTERED_BY_USER");
5035 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5043 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5044 switch (section + (offset_ == 0 ? 1 : 0)) {
5046 case 1: return offset_;
5054 - (int) numberOfRowsInTable:(UITable *)table {
5055 return [sources_ count];
5058 - (float) table:(UITable *)table heightForRow:(int)row {
5059 Source *source = [sources_ objectAtIndex:row];
5060 return [source description] == nil ? 56 : 73;
5063 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5064 Source *source = [sources_ objectAtIndex:row];
5065 // XXX: weird warning, stupid selectors ;P
5066 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5069 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5073 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5077 - (void) tableRowSelected:(NSNotification*)notification {
5078 UITable *table([list_ table]);
5079 int row([table selectedRow]);
5083 Source *source = [sources_ objectAtIndex:row];
5085 PackageTable *packages = [[[FilteredPackageTable alloc]
5088 title:[source label]
5089 filter:@selector(isVisibleInSource:)
5093 [packages setDelegate:delegate_];
5095 [book_ pushPage:packages];
5098 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5099 Source *source = [sources_ objectAtIndex:row];
5100 return [source record] != nil;
5103 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5104 [[list_ table] setDeleteConfirmationRow:row];
5107 - (void) table:(UITable *)table deleteRow:(int)row {
5108 Source *source = [sources_ objectAtIndex:row];
5109 [Sources_ removeObjectForKey:[source key]];
5110 [delegate_ syncData];
5114 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5117 @"./", @"Distribution",
5118 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5120 [delegate_ syncData];
5123 - (NSString *) getWarning {
5124 NSString *href(href_);
5125 NSRange colon([href rangeOfString:@"://"]);
5126 if (colon.location != NSNotFound)
5127 href = [href substringFromIndex:(colon.location + 3)];
5128 href = [href stringByAddingPercentEscapes];
5129 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5130 href = [href stringByCachingURLWithCurrentCDN];
5132 NSURL *url([NSURL URLWithString:href]);
5134 NSStringEncoding encoding;
5135 NSError *error(nil);
5137 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5138 return [warning length] == 0 ? nil : warning;
5142 - (void) _endConnection:(NSURLConnection *)connection {
5143 NSURLConnection **field = NULL;
5144 if (connection == trivial_bz2_)
5145 field = &trivial_bz2_;
5146 else if (connection == trivial_gz_)
5147 field = &trivial_gz_;
5148 _assert(field != NULL);
5149 [connection release];
5153 trivial_bz2_ == nil &&
5159 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5162 UIActionSheet *sheet = [[[UIActionSheet alloc]
5163 initWithTitle:CYLocalize("SOURCE_WARNING")
5164 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5165 defaultButtonIndex:0
5170 [sheet setNumberOfRows:1];
5172 [sheet setBodyText:warning];
5173 [sheet popupAlertAnimated:YES];
5176 } else if (error_ != nil) {
5177 UIActionSheet *sheet = [[[UIActionSheet alloc]
5178 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5179 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5180 defaultButtonIndex:0
5185 [sheet setBodyText:[error_ localizedDescription]];
5186 [sheet popupAlertAnimated:YES];
5188 UIActionSheet *sheet = [[[UIActionSheet alloc]
5189 initWithTitle:CYLocalize("NOT_REPOSITORY")
5190 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5191 defaultButtonIndex:0
5196 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5197 [sheet popupAlertAnimated:YES];
5200 [delegate_ setStatusBarShowsProgress:NO];
5201 [delegate_ removeProgressHUD:hud_];
5211 if (error_ != nil) {
5218 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5219 switch ([response statusCode]) {
5225 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5226 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5228 error_ = [error retain];
5229 [self _endConnection:connection];
5232 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5233 [self _endConnection:connection];
5236 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5237 NSMutableURLRequest *request = [NSMutableURLRequest
5238 requestWithURL:[NSURL URLWithString:href]
5239 cachePolicy:NSURLRequestUseProtocolCachePolicy
5240 timeoutInterval:20.0
5243 [request setHTTPMethod:method];
5245 if (Machine_ != NULL)
5246 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5247 if (UniqueID_ != nil)
5248 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5251 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5253 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5256 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5257 NSString *context([sheet context]);
5259 if ([context isEqualToString:@"source"]) {
5262 NSString *href = [[sheet textField] text];
5264 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5266 if (![href hasSuffix:@"/"])
5267 href_ = [href stringByAppendingString:@"/"];
5270 href_ = [href_ retain];
5272 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5273 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5274 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5278 hud_ = [[delegate_ addProgressHUD] retain];
5279 [hud_ setText:CYLocalize("VERIFYING_URL")];
5290 } else if ([context isEqualToString:@"trivial"])
5292 else if ([context isEqualToString:@"urlerror"])
5294 else if ([context isEqualToString:@"warning"]) {
5314 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5315 if ((self = [super initWithBook:book]) != nil) {
5316 database_ = database;
5317 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5319 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5320 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5321 [list_ setShouldHideHeaderInShortLists:NO];
5323 [self addSubview:list_];
5324 [list_ setDataSource:self];
5326 UITableColumn *column = [[UITableColumn alloc]
5327 initWithTitle:CYLocalize("NAME")
5329 width:[self frame].size.width
5332 UITable *table = [list_ table];
5333 [table setSeparatorStyle:1];
5334 [table addTableColumn:column];
5335 [table setDelegate:self];
5339 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5340 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5344 - (void) reloadData {
5346 _assert(list.ReadMainList());
5348 [sources_ removeAllObjects];
5349 [sources_ addObjectsFromArray:[database_ sources]];
5351 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5354 int count = [sources_ count];
5355 for (offset_ = 0; offset_ != count; ++offset_) {
5356 Source *source = [sources_ objectAtIndex:offset_];
5357 if ([source record] == nil)
5364 - (void) resetViewAnimated:(BOOL)animated {
5365 [list_ resetViewAnimated:animated];
5368 - (void) _leftButtonClicked {
5369 /*[book_ pushPage:[[[AddSourceView alloc]
5374 UIActionSheet *sheet = [[[UIActionSheet alloc]
5375 initWithTitle:CYLocalize("ENTER_APT_URL")
5376 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5377 defaultButtonIndex:0
5382 [sheet setNumberOfRows:1];
5384 [sheet addTextFieldWithValue:@"http://" label:@""];
5386 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5387 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5388 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5389 [traits setKeyboardType:UIKeyboardTypeURL];
5390 // XXX: UIReturnKeyDone
5391 [traits setReturnKeyType:UIReturnKeyNext];
5393 [sheet popupAlertAnimated:YES];
5396 - (void) _rightButtonClicked {
5397 UITable *table = [list_ table];
5398 BOOL editing = [table isRowDeletionEnabled];
5399 [table enableRowDeletion:!editing animated:YES];
5400 [book_ reloadButtonsForPage:self];
5403 - (NSString *) title {
5404 return CYLocalize("SOURCES");
5407 - (NSString *) leftButtonTitle {
5408 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5411 - (id) rightButtonTitle {
5412 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5415 - (UINavigationButtonStyle) rightButtonStyle {
5416 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5422 /* Installed View {{{ */
5423 @interface InstalledView : RVPage {
5424 _transient Database *database_;
5425 FilteredPackageTable *packages_;
5429 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5433 @implementation InstalledView
5436 [packages_ release];
5440 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5441 if ((self = [super initWithBook:book]) != nil) {
5442 database_ = database;
5444 packages_ = [[FilteredPackageTable alloc]
5448 filter:@selector(isInstalledAndVisible:)
5449 with:[NSNumber numberWithBool:YES]
5452 [self addSubview:packages_];
5454 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5455 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5459 - (void) resetViewAnimated:(BOOL)animated {
5460 [packages_ resetViewAnimated:animated];
5463 - (void) reloadData {
5464 [packages_ reloadData];
5467 - (void) _rightButtonClicked {
5468 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5469 [packages_ reloadData];
5471 [book_ reloadButtonsForPage:self];
5474 - (NSString *) title {
5475 return CYLocalize("INSTALLED");
5478 - (NSString *) backButtonTitle {
5479 return CYLocalize("PACKAGES");
5482 - (id) rightButtonTitle {
5483 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5486 - (UINavigationButtonStyle) rightButtonStyle {
5487 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5490 - (void) setDelegate:(id)delegate {
5491 [super setDelegate:delegate];
5492 [packages_ setDelegate:delegate];
5499 @interface HomeView : BrowserView {
5504 @implementation HomeView
5506 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5507 NSString *context([sheet context]);
5509 if ([context isEqualToString:@"about"])
5512 [super alertSheet:sheet buttonClicked:button];
5515 - (void) _leftButtonClicked {
5516 UIActionSheet *sheet = [[[UIActionSheet alloc]
5517 initWithTitle:CYLocalize("ABOUT_CYDIA")
5518 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5519 defaultButtonIndex:0
5525 @"Copyright (C) 2008-2009\n"
5526 "Jay Freeman (saurik)\n"
5527 "saurik@saurik.com\n"
5528 "http://www.saurik.com/\n"
5531 "http://www.theokorigroup.com/\n"
5533 "College of Creative Studies,\n"
5534 "University of California,\n"
5536 "http://www.ccs.ucsb.edu/"
5539 [sheet popupAlertAnimated:YES];
5542 - (NSString *) leftButtonTitle {
5543 return CYLocalize("ABOUT");
5548 /* Manage View {{{ */
5549 @interface ManageView : BrowserView {
5554 @implementation ManageView
5556 - (NSString *) title {
5557 return CYLocalize("MANAGE");
5560 - (void) _leftButtonClicked {
5561 [delegate_ askForSettings];
5564 - (NSString *) leftButtonTitle {
5565 return CYLocalize("SETTINGS");
5569 - (id) _rightButtonTitle {
5570 return Queuing_ ? CYLocalize("QUEUE") : nil;
5573 - (UINavigationButtonStyle) rightButtonStyle {
5574 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5577 - (void) _rightButtonClicked {
5582 - (bool) isLoading {
5589 #include <BrowserView.m>
5591 /* Cydia Book {{{ */
5592 @interface CYBook : RVBook <
5595 _transient Database *database_;
5596 UINavigationBar *overlay_;
5597 UINavigationBar *underlay_;
5598 UIProgressIndicator *indicator_;
5599 UITextLabel *prompt_;
5600 UIProgressBar *progress_;
5601 UINavigationButton *cancel_;
5605 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5611 @implementation CYBook
5615 [indicator_ release];
5617 [progress_ release];
5622 - (NSString *) getTitleForPage:(RVPage *)page {
5623 return [super getTitleForPage:page];
5631 [UIView beginAnimations:nil context:NULL];
5633 CGRect ovrframe = [overlay_ frame];
5634 ovrframe.origin.y = 0;
5635 [overlay_ setFrame:ovrframe];
5637 CGRect barframe = [navbar_ frame];
5638 barframe.origin.y += ovrframe.size.height;
5639 [navbar_ setFrame:barframe];
5641 CGRect trnframe = [transition_ frame];
5642 trnframe.origin.y += ovrframe.size.height;
5643 trnframe.size.height -= ovrframe.size.height;
5644 [transition_ setFrame:trnframe];
5646 [UIView endAnimations];
5648 [indicator_ startAnimation];
5649 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5650 [progress_ setProgress:0];
5653 [overlay_ addSubview:cancel_];
5656 detachNewThreadSelector:@selector(_update)
5665 [indicator_ stopAnimation];
5667 [UIView beginAnimations:nil context:NULL];
5669 CGRect ovrframe = [overlay_ frame];
5670 ovrframe.origin.y = -ovrframe.size.height;
5671 [overlay_ setFrame:ovrframe];
5673 CGRect barframe = [navbar_ frame];
5674 barframe.origin.y -= ovrframe.size.height;
5675 [navbar_ setFrame:barframe];
5677 CGRect trnframe = [transition_ frame];
5678 trnframe.origin.y -= ovrframe.size.height;
5679 trnframe.size.height += ovrframe.size.height;
5680 [transition_ setFrame:trnframe];
5682 [UIView commitAnimations];
5684 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5687 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
5688 if ((self = [super initWithFrame:frame]) != nil) {
5689 database_ = database;
5691 CGRect ovrrect = [navbar_ bounds];
5692 ovrrect.size.height = [UINavigationBar defaultSize].height;
5693 ovrrect.origin.y = -ovrrect.size.height;
5695 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5696 [self addSubview:overlay_];
5698 ovrrect.origin.y = frame.size.height;
5699 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5700 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
5701 [self addSubview:underlay_];
5703 [overlay_ setBarStyle:1];
5704 [underlay_ setBarStyle:1];
5706 int barstyle = [overlay_ _barStyle:NO];
5707 bool ugly = barstyle == 0;
5709 UIProgressIndicatorStyle style = ugly ?
5710 UIProgressIndicatorStyleMediumBrown :
5711 UIProgressIndicatorStyleMediumWhite;
5713 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
5714 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
5715 CGRect indrect = {{indoffset, indoffset}, indsize};
5717 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
5718 [indicator_ setStyle:style];
5719 [overlay_ addSubview:indicator_];
5721 CGSize prmsize = {215, indsize.height + 4};
5724 indoffset * 2 + indsize.width,
5728 unsigned(ovrrect.size.height - prmsize.height) / 2
5731 UIFont *font = [UIFont systemFontOfSize:15];
5733 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
5735 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
5736 [prompt_ setBackgroundColor:[UIColor clearColor]];
5737 [prompt_ setFont:font];
5739 [overlay_ addSubview:prompt_];
5741 CGSize prgsize = {75, 100};
5744 ovrrect.size.width - prgsize.width - 10,
5745 (ovrrect.size.height - prgsize.height) / 2
5748 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
5749 [progress_ setStyle:0];
5750 [overlay_ addSubview:progress_];
5752 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
5753 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
5755 CGRect frame = [cancel_ frame];
5756 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
5757 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
5758 [cancel_ setFrame:frame];
5760 [cancel_ setBarStyle:barstyle];
5764 - (void) _onCancel {
5766 [cancel_ removeFromSuperview];
5769 - (void) _update { _pooled
5771 status.setDelegate(self);
5773 [database_ updateWithStatus:status];
5776 performSelectorOnMainThread:@selector(_update_)
5782 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
5783 [prompt_ setText:[NSString stringWithFormat:CYLocalize("ERROR_MESSAGE"), error]];
5786 - (void) setProgressTitle:(NSString *)title {
5788 performSelectorOnMainThread:@selector(_setProgressTitle:)
5794 - (void) setProgressPercent:(float)percent {
5796 performSelectorOnMainThread:@selector(_setProgressPercent:)
5797 withObject:[NSNumber numberWithFloat:percent]
5802 - (void) startProgress {
5805 - (void) addProgressOutput:(NSString *)output {
5807 performSelectorOnMainThread:@selector(_addProgressOutput:)
5813 - (bool) isCancelling:(size_t)received {
5817 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5821 - (void) _setProgressTitle:(NSString *)title {
5822 [prompt_ setText:title];
5825 - (void) _setProgressPercent:(NSNumber *)percent {
5826 [progress_ setProgress:[percent floatValue]];
5829 - (void) _addProgressOutput:(NSString *)output {
5834 /* Cydia:// Protocol {{{ */
5835 @interface CydiaURLProtocol : NSURLProtocol {
5840 @implementation CydiaURLProtocol
5842 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
5843 NSURL *url([request URL]);
5846 NSString *scheme([[url scheme] lowercaseString]);
5847 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
5852 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
5856 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
5857 id<NSURLProtocolClient> client([self client]);
5859 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
5861 NSData *data(UIImagePNGRepresentation(icon));
5863 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
5864 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
5865 [client URLProtocol:self didLoadData:data];
5866 [client URLProtocolDidFinishLoading:self];
5870 - (void) startLoading {
5871 id<NSURLProtocolClient> client([self client]);
5872 NSURLRequest *request([self request]);
5874 NSURL *url([request URL]);
5875 NSString *href([url absoluteString]);
5877 NSString *path([href substringFromIndex:8]);
5878 NSRange slash([path rangeOfString:@"/"]);
5881 if (slash.location == NSNotFound) {
5885 command = [path substringToIndex:slash.location];
5886 path = [path substringFromIndex:(slash.location + 1)];
5889 Database *database([Database sharedInstance]);
5891 if ([command isEqualToString:@"package-icon"]) {
5894 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5895 Package *package([database packageWithName:path]);
5898 UIImage *icon([package icon]);
5899 [self _returnPNGWithImage:icon forRequest:request];
5900 } else if ([command isEqualToString:@"source-icon"]) {
5903 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5904 NSString *source(Simplify(path));
5905 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
5907 icon = [UIImage applicationImageNamed:@"unknown.png"];
5908 [self _returnPNGWithImage:icon forRequest:request];
5909 } else if ([command isEqualToString:@"uikit-image"]) {
5912 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5913 UIImage *icon(_UIImageWithName(path));
5914 [self _returnPNGWithImage:icon forRequest:request];
5915 } else if ([command isEqualToString:@"section-icon"]) {
5918 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5919 NSString *section(Simplify(path));
5920 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
5922 icon = [UIImage applicationImageNamed:@"unknown.png"];
5923 [self _returnPNGWithImage:icon forRequest:request];
5925 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
5929 - (void) stopLoading {
5935 /* Sections View {{{ */
5936 @interface SectionsView : RVPage {
5937 _transient Database *database_;
5938 NSMutableArray *sections_;
5939 NSMutableArray *filtered_;
5940 UITransitionView *transition_;
5946 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5947 - (void) reloadData;
5952 @implementation SectionsView
5955 [list_ setDataSource:nil];
5956 [list_ setDelegate:nil];
5958 [sections_ release];
5959 [filtered_ release];
5960 [transition_ release];
5962 [accessory_ release];
5966 - (int) numberOfRowsInTable:(UITable *)table {
5967 return editing_ ? [sections_ count] : [filtered_ count] + 1;
5970 - (float) table:(UITable *)table heightForRow:(int)row {
5974 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
5976 reusing = [[[SectionCell alloc] init] autorelease];
5977 [(SectionCell *)reusing setSection:(editing_ ?
5978 [sections_ objectAtIndex:row] :
5979 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
5980 ) editing:editing_];
5984 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5988 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5992 - (void) tableRowSelected:(NSNotification *)notification {
5993 int row = [[notification object] selectedRow];
6004 title = CYLocalize("ALL_PACKAGES");
6006 section = [filtered_ objectAtIndex:(row - 1)];
6007 name = [section name];
6010 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6013 title = CYLocalize("NO_SECTION");
6017 PackageTable *table = [[[FilteredPackageTable alloc]
6021 filter:@selector(isVisiblyUninstalledInSection:)
6025 [table setDelegate:delegate_];
6027 [book_ pushPage:table];
6030 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6031 if ((self = [super initWithBook:book]) != nil) {
6032 database_ = database;
6034 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6035 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6037 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6038 [self addSubview:transition_];
6040 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6041 [transition_ transition:0 toView:list_];
6043 UITableColumn *column = [[[UITableColumn alloc]
6044 initWithTitle:CYLocalize("NAME")
6046 width:[self frame].size.width
6049 [list_ setDataSource:self];
6050 [list_ setSeparatorStyle:1];
6051 [list_ addTableColumn:column];
6052 [list_ setDelegate:self];
6053 [list_ setReusesTableCells:YES];
6057 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6058 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6062 - (void) reloadData {
6063 NSArray *packages = [database_ packages];
6065 [sections_ removeAllObjects];
6066 [filtered_ removeAllObjects];
6069 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6070 SectionMap sections;
6071 sections.resize(64);
6073 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6077 for (Package *package in packages) {
6078 NSString *name([package section]);
6079 NSString *key(name == nil ? @"" : name);
6084 _profile(SectionsView$reloadData$Section)
6085 section = §ions[key];
6086 if (*section == nil) {
6087 _profile(SectionsView$reloadData$Section$Allocate)
6088 *section = [[[Section alloc] initWithName:name] autorelease];
6093 [*section addToCount];
6095 _profile(SectionsView$reloadData$Filter)
6096 if (![package valid] || [package installed] != nil || ![package visible])
6100 [*section addToRow];
6104 _profile(SectionsView$reloadData$Section)
6105 section = [sections objectForKey:key];
6106 if (section == nil) {
6107 _profile(SectionsView$reloadData$Section$Allocate)
6108 section = [[[Section alloc] initWithName:name] autorelease];
6109 [sections setObject:section forKey:key];
6114 [section addToCount];
6116 _profile(SectionsView$reloadData$Filter)
6117 if (![package valid] || [package installed] != nil || ![package visible])
6127 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6128 [sections_ addObject:i->second];
6130 [sections_ addObjectsFromArray:[sections allValues]];
6133 [sections_ sortUsingSelector:@selector(compareByName:)];
6135 for (Section *section in sections_) {
6136 size_t count([section row]);
6137 if ([section row] == 0)
6140 section = [[[Section alloc] initWithName:[section name]] autorelease];
6141 [section setCount:count];
6142 [filtered_ addObject:section];
6149 - (void) resetView {
6151 [self _rightButtonClicked];
6154 - (void) resetViewAnimated:(BOOL)animated {
6155 [list_ resetViewAnimated:animated];
6158 - (void) _rightButtonClicked {
6159 if ((editing_ = !editing_))
6162 [delegate_ updateData];
6163 [book_ reloadTitleForPage:self];
6164 [book_ reloadButtonsForPage:self];
6167 - (NSString *) title {
6168 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6171 - (NSString *) backButtonTitle {
6172 return CYLocalize("SECTIONS");
6175 - (id) rightButtonTitle {
6176 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6179 - (UINavigationButtonStyle) rightButtonStyle {
6180 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6183 - (UIView *) accessoryView {
6189 /* Changes View {{{ */
6190 @interface ChangesView : RVPage {
6191 _transient Database *database_;
6192 NSMutableArray *packages_;
6193 NSMutableArray *sections_;
6194 UISectionList *list_;
6198 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6199 - (void) reloadData;
6203 @implementation ChangesView
6206 [[list_ table] setDelegate:nil];
6207 [list_ setDataSource:nil];
6209 [packages_ release];
6210 [sections_ release];
6215 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6216 return [sections_ count];
6219 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6220 return [[sections_ objectAtIndex:section] name];
6223 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6224 return [[sections_ objectAtIndex:section] row];
6227 - (int) numberOfRowsInTable:(UITable *)table {
6228 return [packages_ count];
6231 - (float) table:(UITable *)table heightForRow:(int)row {
6232 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6235 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6237 reusing = [[[PackageCell alloc] init] autorelease];
6238 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6242 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6246 - (void) tableRowSelected:(NSNotification *)notification {
6247 int row = [[notification object] selectedRow];
6250 Package *package = [packages_ objectAtIndex:row];
6251 PackageView *view([delegate_ packageView]);
6252 [view setDelegate:delegate_];
6253 [view setPackage:package];
6254 [book_ pushPage:view];
6257 - (void) _leftButtonClicked {
6258 [(CYBook *)book_ update];
6259 [self reloadButtons];
6262 - (void) _rightButtonClicked {
6263 [delegate_ distUpgrade];
6266 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6267 if ((self = [super initWithBook:book]) != nil) {
6268 database_ = database;
6270 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6271 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6273 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6274 [self addSubview:list_];
6276 [list_ setShouldHideHeaderInShortLists:NO];
6277 [list_ setDataSource:self];
6278 //[list_ setSectionListStyle:1];
6280 UITableColumn *column = [[[UITableColumn alloc]
6281 initWithTitle:CYLocalize("NAME")
6283 width:[self frame].size.width
6286 UITable *table = [list_ table];
6287 [table setSeparatorStyle:1];
6288 [table addTableColumn:column];
6289 [table setDelegate:self];
6290 [table setReusesTableCells:YES];
6294 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6295 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6299 - (void) reloadData {
6300 NSArray *packages = [database_ packages];
6302 [packages_ removeAllObjects];
6303 [sections_ removeAllObjects];
6306 for (Package *package in packages)
6308 [package installed] == nil && [package valid] && [package visible] ||
6309 [package upgradableAndEssential:YES]
6311 [packages_ addObject:package];
6314 [packages_ radixSortUsingFunction:reinterpret_cast<uint32_t (*)(id, void *)>(&PackageChangesRadix) withArgument:NULL];
6317 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES")] autorelease];
6318 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES")] autorelease];
6319 Section *section = nil;
6323 bool unseens = false;
6325 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
6328 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6329 Package *package = [packages_ objectAtIndex:offset];
6332 _profile(ChangesView$reloadData$Upgrade)
6333 uae = [package upgradableAndEssential:YES];
6340 _profile(ChangesView$reloadData$Remember)
6341 seen = [package seen];
6345 _profile(ChangesView$reloadData$Compare)
6346 different = section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame);
6354 name = CYLocalize("UNKNOWN");
6356 _profile(ChangesView$reloadData$Format)
6357 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6363 _profile(ChangesView$reloadData$Allocate)
6364 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6365 section = [[[Section alloc] initWithName:name row:offset] autorelease];
6366 [sections_ addObject:section];
6370 [section addToCount];
6371 } else if ([package ignored])
6372 [ignored addToCount];
6375 [upgradable addToCount];
6380 CFRelease(formatter);
6383 Section *last = [sections_ lastObject];
6384 size_t count = [last count];
6385 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6386 [sections_ removeLastObject];
6389 if ([ignored count] != 0)
6390 [sections_ insertObject:ignored atIndex:0];
6392 [sections_ insertObject:upgradable atIndex:0];
6395 [self reloadButtons];
6398 - (void) resetViewAnimated:(BOOL)animated {
6399 [list_ resetViewAnimated:animated];
6402 - (NSString *) leftButtonTitle {
6403 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6406 - (id) rightButtonTitle {
6407 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6410 - (NSString *) title {
6411 return CYLocalize("CHANGES");
6416 /* Search View {{{ */
6417 @protocol SearchViewDelegate
6418 - (void) showKeyboard:(BOOL)show;
6421 @interface SearchView : RVPage {
6423 UISearchField *field_;
6424 UITransitionView *transition_;
6425 FilteredPackageTable *table_;
6426 UIPreferencesTable *advanced_;
6432 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6433 - (void) reloadData;
6437 @implementation SearchView
6440 [field_ setDelegate:nil];
6442 [accessory_ release];
6444 [transition_ release];
6446 [advanced_ release];
6451 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6455 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6457 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6459 default: _assert(false);
6463 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6467 default: _assert(false);
6471 - (void) _showKeyboard:(BOOL)show {
6472 CGSize keysize = [UIKeyboard defaultSize];
6473 CGRect keydown = [book_ pageBounds];
6474 CGRect keyup = keydown;
6475 keyup.size.height -= keysize.height - ButtonBarHeight_;
6477 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6479 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6480 [animation setSignificantRectFields:8];
6483 [animation setStartFrame:keydown];
6484 [animation setEndFrame:keyup];
6486 [animation setStartFrame:keyup];
6487 [animation setEndFrame:keydown];
6490 UIAnimator *animator = [UIAnimator sharedAnimator];
6493 addAnimations:[NSArray arrayWithObjects:animation, nil]
6494 withDuration:(KeyboardTime_ - delay)
6499 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6501 [delegate_ showKeyboard:show];
6504 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6505 [self _showKeyboard:YES];
6508 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6509 [self _showKeyboard:NO];
6512 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6514 NSString *text([field_ text]);
6515 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6521 - (void) textFieldClearButtonPressed:(UITextField *)field {
6525 - (void) keyboardInputShouldDelete:(id)input {
6529 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6530 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6534 [field_ resignFirstResponder];
6539 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6540 if ((self = [super initWithBook:book]) != nil) {
6541 CGRect pageBounds = [book_ pageBounds];
6543 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6544 [self addSubview:transition_];
6546 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6548 [advanced_ setReusesTableCells:YES];
6549 [advanced_ setDataSource:self];
6550 [advanced_ reloadData];
6552 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6553 CGColor dimmed(space_, 0, 0, 0, 0.5);
6554 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6556 table_ = [[FilteredPackageTable alloc]
6560 filter:@selector(isUnfilteredAndSearchedForBy:)
6564 [table_ setShouldHideHeaderInShortLists:NO];
6565 [transition_ transition:0 toView:table_];
6574 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6581 [self bounds].size.width - area.origin.x - 18;
6583 area.size.height = [UISearchField defaultHeight];
6585 field_ = [[UISearchField alloc] initWithFrame:area];
6587 UIFont *font = [UIFont systemFontOfSize:16];
6588 [field_ setFont:font];
6590 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6591 [field_ setDelegate:self];
6593 [field_ setPaddingTop:5];
6595 UITextInputTraits *traits([field_ textInputTraits]);
6596 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6597 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6598 [traits setReturnKeyType:UIReturnKeySearch];
6600 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6602 accessory_ = [[UIView alloc] initWithFrame:accrect];
6603 [accessory_ addSubview:field_];
6605 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6606 [configure setShowPressFeedback:YES];
6607 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6608 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6609 [accessory_ addSubview:configure];*/
6611 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6612 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6618 LKAnimation *animation = [LKTransition animation];
6619 [animation setType:@"oglFlip"];
6620 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6621 [animation setFillMode:@"extended"];
6622 [animation setTransitionFlags:3];
6623 [animation setDuration:10];
6624 [animation setSpeed:0.35];
6625 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6626 [[transition_ _layer] addAnimation:animation forKey:0];
6627 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6628 flipped_ = !flipped_;
6632 - (void) configurePushed {
6633 [field_ resignFirstResponder];
6637 - (void) resetViewAnimated:(BOOL)animated {
6640 [table_ resetViewAnimated:animated];
6643 - (void) _reloadData {
6646 - (void) reloadData {
6649 [table_ setObject:[field_ text]];
6650 _profile(SearchView$reloadData)
6651 [table_ reloadData];
6654 [table_ resetCursor];
6657 - (UIView *) accessoryView {
6661 - (NSString *) title {
6665 - (NSString *) backButtonTitle {
6666 return CYLocalize("SEARCH");
6669 - (void) setDelegate:(id)delegate {
6670 [table_ setDelegate:delegate];
6671 [super setDelegate:delegate];
6677 @interface SettingsView : RVPage {
6678 _transient Database *database_;
6681 UIPreferencesTable *table_;
6682 _UISwitchSlider *subscribedSwitch_;
6683 _UISwitchSlider *ignoredSwitch_;
6684 UIPreferencesControlTableCell *subscribedCell_;
6685 UIPreferencesControlTableCell *ignoredCell_;
6688 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6692 @implementation SettingsView
6695 [table_ setDataSource:nil];
6698 if (package_ != nil)
6701 [subscribedSwitch_ release];
6702 [ignoredSwitch_ release];
6703 [subscribedCell_ release];
6704 [ignoredCell_ release];
6708 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6709 if (package_ == nil)
6715 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6716 if (package_ == nil)
6723 default: _assert(false);
6729 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
6730 if (package_ == nil)
6737 default: _assert(false);
6743 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6744 if (package_ == nil)
6751 default: _assert(false);
6757 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
6758 if (package_ == nil)
6761 _UISwitchSlider *slider([cell control]);
6762 BOOL value([slider value] != 0);
6763 NSMutableDictionary *metadata([package_ metadata]);
6766 if (NSNumber *number = [metadata objectForKey:key])
6767 before = [number boolValue];
6771 if (value != before) {
6772 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
6774 [delegate_ updateData];
6778 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
6779 [self onSomething:cell withKey:@"IsSubscribed"];
6782 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
6783 [self onSomething:cell withKey:@"IsIgnored"];
6786 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
6787 if (package_ == nil)
6791 case 0: switch (row) {
6793 return subscribedCell_;
6795 return ignoredCell_;
6796 default: _assert(false);
6799 case 1: switch (row) {
6801 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
6802 [cell setShowSelection:NO];
6803 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
6807 default: _assert(false);
6810 default: _assert(false);
6816 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
6817 if ((self = [super initWithBook:book])) {
6818 database_ = database;
6819 name_ = [package retain];
6821 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
6822 [self addSubview:table_];
6824 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
6825 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
6827 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
6828 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
6830 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
6831 [subscribedCell_ setShowSelection:NO];
6832 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
6833 [subscribedCell_ setControl:subscribedSwitch_];
6835 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
6836 [ignoredCell_ setShowSelection:NO];
6837 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
6838 [ignoredCell_ setControl:ignoredSwitch_];
6840 [table_ setDataSource:self];
6845 - (void) resetViewAnimated:(BOOL)animated {
6846 [table_ resetViewAnimated:animated];
6849 - (void) reloadData {
6850 if (package_ != nil)
6851 [package_ autorelease];
6852 package_ = [database_ packageWithName:name_];
6853 if (package_ != nil) {
6855 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
6856 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
6859 [table_ reloadData];
6862 - (NSString *) title {
6863 return CYLocalize("SETTINGS");
6868 /* Signature View {{{ */
6869 @interface SignatureView : BrowserView {
6870 _transient Database *database_;
6874 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6878 @implementation SignatureView
6885 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
6887 [super webView:sender didClearWindowObject:window forFrame:frame];
6890 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
6891 if ((self = [super initWithBook:book]) != nil) {
6892 database_ = database;
6893 package_ = [package retain];
6898 - (void) resetViewAnimated:(BOOL)animated {
6901 - (void) reloadData {
6902 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
6908 @interface Cydia : UIApplication <
6909 ConfirmationViewDelegate,
6910 ProgressViewDelegate,
6919 UIToolbar *buttonbar_;
6923 NSMutableArray *essential_;
6924 NSMutableArray *broken_;
6926 Database *database_;
6927 ProgressView *progress_;
6931 UIKeyboard *keyboard_;
6932 UIProgressHUD *hud_;
6934 SectionsView *sections_;
6935 ChangesView *changes_;
6936 ManageView *manage_;
6937 SearchView *search_;
6939 PackageView *package_;
6944 @implementation Cydia
6947 if ([broken_ count] != 0) {
6948 int count = [broken_ count];
6950 UIActionSheet *sheet = [[[UIActionSheet alloc]
6951 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
6952 buttons:[NSArray arrayWithObjects:
6953 CYLocalize("FORCIBLY_CLEAR"),
6954 CYLocalize("TEMPORARY_IGNORE"),
6956 defaultButtonIndex:0
6961 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
6962 [sheet popupAlertAnimated:YES];
6963 } else if (!Ignored_ && [essential_ count] != 0) {
6964 int count = [essential_ count];
6966 UIActionSheet *sheet = [[[UIActionSheet alloc]
6967 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
6968 buttons:[NSArray arrayWithObjects:
6969 CYLocalize("UPGRADE_ESSENTIAL"),
6970 CYLocalize("COMPLETE_UPGRADE"),
6971 CYLocalize("TEMPORARY_IGNORE"),
6973 defaultButtonIndex:0
6978 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
6979 [sheet popupAlertAnimated:YES];
6983 - (void) _reloadData {
6986 static bool loaded(false);
6987 UIProgressHUD *hud([self addProgressHUD]);
6988 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
6991 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
6994 [self removeProgressHUD:hud];
6998 [essential_ removeAllObjects];
6999 [broken_ removeAllObjects];
7001 NSArray *packages = [database_ packages];
7002 for (Package *package in packages) {
7004 [broken_ addObject:package];
7005 if ([package upgradableAndEssential:NO]) {
7006 if ([package essential])
7007 [essential_ addObject:package];
7013 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7014 [buttonbar_ setBadgeValue:badge forButton:3];
7015 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7016 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7017 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7018 [self setApplicationBadge:badge];
7020 [self setApplicationBadgeString:badge];
7022 [buttonbar_ setBadgeValue:nil forButton:3];
7023 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7024 [buttonbar_ setBadgeAnimated:NO forButton:3];
7025 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7026 [self removeApplicationBadge];
7027 else // XXX: maybe use setApplicationBadgeString also?
7028 [self setApplicationIconBadgeNumber:0];
7032 [buttonbar_ setBadgeValue:nil forButton:4];
7036 // XXX: what is this line of code for?
7037 if ([packages count] == 0);
7038 else if (Loaded_ || ManualRefresh) loaded:
7043 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7044 NSTimeInterval interval([update timeIntervalSinceNow]);
7045 if (interval <= 0 && interval > -600)
7053 - (void) _saveConfig {
7056 NSString *error(nil);
7057 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7059 NSError *error(nil);
7060 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7061 NSLog(@"failure to save metadata data: %@", error);
7064 NSLog(@"failure to serialize metadata: %@", error);
7072 - (void) updateData {
7075 /* XXX: this is just stupid */
7076 if (tag_ != 2 && sections_ != nil)
7077 [sections_ reloadData];
7078 if (tag_ != 3 && changes_ != nil)
7079 [changes_ reloadData];
7080 if (tag_ != 5 && search_ != nil)
7081 [search_ reloadData];
7091 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7092 _assert(file != NULL);
7094 NSArray *keys = [Sources_ allKeys];
7096 for (NSString *key in keys) {
7097 NSDictionary *source = [Sources_ objectForKey:key];
7099 fprintf(file, "%s %s %s\n",
7100 [[source objectForKey:@"Type"] UTF8String],
7101 [[source objectForKey:@"URI"] UTF8String],
7102 [[source objectForKey:@"Distribution"] UTF8String]
7111 detachNewThreadSelector:@selector(update_)
7114 title:CYLocalize("UPDATING_SOURCES")
7118 - (void) reloadData {
7119 @synchronized (self) {
7120 if (confirm_ == nil)
7126 pkgProblemResolver *resolver = [database_ resolver];
7128 resolver->InstallProtect();
7129 if (!resolver->Resolve(true))
7133 - (void) popUpBook:(RVBook *)book {
7134 [underlay_ popSubview:book];
7137 - (CGRect) popUpBounds {
7138 return [underlay_ bounds];
7142 [database_ prepare];
7144 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7145 [confirm_ setDelegate:self];
7147 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7148 [page setDelegate:self];
7150 [confirm_ setPage:page];
7151 [self popUpBook:confirm_];
7155 @synchronized (self) {
7160 - (void) clearPackage:(Package *)package {
7161 @synchronized (self) {
7168 - (void) installPackage:(Package *)package {
7169 @synchronized (self) {
7176 - (void) removePackage:(Package *)package {
7177 @synchronized (self) {
7184 - (void) distUpgrade {
7185 @synchronized (self) {
7186 [database_ upgrade];
7192 [self slideUp:[[[UIActionSheet alloc]
7194 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7195 defaultButtonIndex:1
7202 @synchronized (self) {
7205 if (confirm_ != nil) {
7213 [overlay_ removeFromSuperview];
7217 detachNewThreadSelector:@selector(perform)
7220 title:CYLocalize("RUNNING")
7224 - (void) bootstrap_ {
7226 [database_ upgrade];
7227 [database_ prepare];
7228 [database_ perform];
7231 /* XXX: replace and localize */
7232 - (void) bootstrap {
7234 detachNewThreadSelector:@selector(bootstrap_)
7237 title:@"Bootstrap Install"
7241 - (void) progressViewIsComplete:(ProgressView *)progress {
7242 if (confirm_ != nil) {
7243 [underlay_ addSubview:overlay_];
7244 [confirm_ popFromSuperviewAnimated:NO];
7250 - (void) setPage:(RVPage *)page {
7251 [page resetViewAnimated:NO];
7252 [page setDelegate:self];
7253 [book_ setPage:page];
7256 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7257 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7258 [browser loadURL:url];
7262 - (void) _setHomePage {
7263 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7266 - (SectionsView *) sectionsView {
7267 if (sections_ == nil)
7268 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7272 - (void) buttonBarItemTapped:(id)sender {
7273 unsigned tag = [sender tag];
7275 [book_ resetViewAnimated:YES];
7277 } else if (tag_ == 2 && tag != 2)
7278 [[self sectionsView] resetView];
7281 case 1: [self _setHomePage]; break;
7283 case 2: [self setPage:[self sectionsView]]; break;
7284 case 3: [self setPage:changes_]; break;
7285 case 4: [self setPage:manage_]; break;
7286 case 5: [self setPage:search_]; break;
7288 default: _assert(false);
7294 - (void) applicationWillSuspend {
7296 [super applicationWillSuspend];
7299 - (void) askForSettings {
7300 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7302 UIActionSheet *role = [[[UIActionSheet alloc]
7303 initWithTitle:CYLocalize("WHO_ARE_YOU")
7304 buttons:[NSArray arrayWithObjects:
7305 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7306 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7307 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7309 defaultButtonIndex:-1
7314 [role setBodyText:CYLocalize("ROLE_EX")];
7315 [role popupAlertAnimated:YES];
7318 - (void) setPackageView:(PackageView *)view {
7319 if (package_ == nil)
7320 package_ = [view retain];
7323 - (PackageView *) packageView {
7326 if (package_ == nil)
7327 view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7330 view = [package_ autorelease];
7339 [self setStatusBarShowsProgress:NO];
7340 [self removeProgressHUD:hud_];
7345 pid_t pid = ExecFork();
7347 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7348 perror("launchctl stop");
7355 [self askForSettings];
7360 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7362 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7363 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7364 0, 0, screenrect.size.width, screenrect.size.height - 48
7365 ) database:database_];
7367 [book_ setDelegate:self];
7369 [overlay_ addSubview:book_];
7371 NSArray *buttonitems = [NSArray arrayWithObjects:
7372 [NSDictionary dictionaryWithObjectsAndKeys:
7373 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7374 @"home-up.png", kUIButtonBarButtonInfo,
7375 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7376 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7377 self, kUIButtonBarButtonTarget,
7378 @"Cydia", kUIButtonBarButtonTitle,
7379 @"0", kUIButtonBarButtonType,
7382 [NSDictionary dictionaryWithObjectsAndKeys:
7383 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7384 @"install-up.png", kUIButtonBarButtonInfo,
7385 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7386 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7387 self, kUIButtonBarButtonTarget,
7388 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7389 @"0", kUIButtonBarButtonType,
7392 [NSDictionary dictionaryWithObjectsAndKeys:
7393 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7394 @"changes-up.png", kUIButtonBarButtonInfo,
7395 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7396 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7397 self, kUIButtonBarButtonTarget,
7398 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7399 @"0", kUIButtonBarButtonType,
7402 [NSDictionary dictionaryWithObjectsAndKeys:
7403 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7404 @"manage-up.png", kUIButtonBarButtonInfo,
7405 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7406 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7407 self, kUIButtonBarButtonTarget,
7408 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7409 @"0", kUIButtonBarButtonType,
7412 [NSDictionary dictionaryWithObjectsAndKeys:
7413 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7414 @"search-up.png", kUIButtonBarButtonInfo,
7415 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7416 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7417 self, kUIButtonBarButtonTarget,
7418 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7419 @"0", kUIButtonBarButtonType,
7423 buttonbar_ = [[UIToolbar alloc]
7425 withFrame:CGRectMake(
7426 0, screenrect.size.height - ButtonBarHeight_,
7427 screenrect.size.width, ButtonBarHeight_
7429 withItemList:buttonitems
7432 [buttonbar_ setDelegate:self];
7433 [buttonbar_ setBarStyle:1];
7434 [buttonbar_ setButtonBarTrackingMode:2];
7436 int buttons[5] = {1, 2, 3, 4, 5};
7437 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7438 [buttonbar_ showButtonGroup:0 withDuration:0];
7440 for (int i = 0; i != 5; ++i)
7441 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7442 i * 64 + 2, 1, 60, ButtonBarHeight_
7445 [buttonbar_ showSelectionForButton:1];
7446 [overlay_ addSubview:buttonbar_];
7448 [UIKeyboard initImplementationNow];
7449 CGSize keysize = [UIKeyboard defaultSize];
7450 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7451 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7452 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7453 [overlay_ addSubview:keyboard_];
7456 [underlay_ addSubview:overlay_];
7460 [self sectionsView];
7461 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7462 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7464 manage_ = (ManageView *) [[self
7465 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7466 withClass:[ManageView class]
7469 [self setPackageView:[self packageView]];
7476 [self _setHomePage];
7479 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7480 NSString *context([sheet context]);
7482 if ([context isEqualToString:@"missing"])
7484 else if ([context isEqualToString:@"cancel"]) {
7502 @synchronized (self) {
7507 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7511 if (confirm_ != nil) {
7516 } else if ([context isEqualToString:@"fixhalf"]) {
7519 @synchronized (self) {
7520 for (Package *broken in broken_) {
7523 NSString *id = [broken id];
7524 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7525 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7526 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7527 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7536 [broken_ removeAllObjects];
7545 } else if ([context isEqualToString:@"role"]) {
7547 case 1: Role_ = @"User"; break;
7548 case 2: Role_ = @"Hacker"; break;
7549 case 3: Role_ = @"Developer"; break;
7556 bool reset = Settings_ != nil;
7558 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7562 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7572 } else if ([context isEqualToString:@"upgrade"]) {
7575 @synchronized (self) {
7576 for (Package *essential in essential_)
7577 [essential install];
7600 - (void) reorganize { _pooled
7601 system("/usr/libexec/cydia/free.sh");
7602 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7605 - (void) applicationSuspend:(__GSEvent *)event {
7606 if (hud_ == nil && ![progress_ isRunning])
7607 [super applicationSuspend:event];
7610 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7612 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7615 - (void) _setSuspended:(BOOL)value {
7617 [super _setSuspended:value];
7620 - (UIProgressHUD *) addProgressHUD {
7621 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7622 [window_ setUserInteractionEnabled:NO];
7624 [progress_ addSubview:hud];
7628 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7630 [hud removeFromSuperview];
7631 [window_ setUserInteractionEnabled:YES];
7634 - (void) openMailToURL:(NSURL *)url {
7635 // XXX: this makes me sad
7637 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7639 [UIApp openURL:url];// asPanel:YES];
7643 - (void) clearFirstResponder {
7644 if (id responder = [window_ firstResponder])
7645 [responder resignFirstResponder];
7648 - (RVPage *) pageForPackage:(NSString *)name {
7649 if (Package *package = [database_ packageWithName:name]) {
7650 PackageView *view([self packageView]);
7651 [view setPackage:package];
7654 UIActionSheet *sheet = [[[UIActionSheet alloc]
7655 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7656 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
7657 defaultButtonIndex:0
7662 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
7664 [sheet popupAlertAnimated:YES];
7669 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7673 NSString *scheme([[url scheme] lowercaseString]);
7674 if (![scheme isEqualToString:@"cydia"])
7676 NSString *path([url absoluteString]);
7677 if ([path length] < 8)
7679 path = [path substringFromIndex:8];
7680 if (![path hasPrefix:@"/"])
7681 path = [@"/" stringByAppendingString:path];
7683 if ([path isEqualToString:@"/add-source"])
7684 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
7685 else if ([path isEqualToString:@"/storage"])
7686 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
7687 else if ([path isEqualToString:@"/sources"])
7688 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
7689 else if ([path isEqualToString:@"/packages"])
7690 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
7691 else if ([path hasPrefix:@"/url/"])
7692 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
7693 else if ([path hasPrefix:@"/launch/"])
7694 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
7695 else if ([path hasPrefix:@"/package-settings/"])
7696 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
7697 else if ([path hasPrefix:@"/package-signature/"])
7698 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
7699 else if ([path hasPrefix:@"/package/"])
7700 return [self pageForPackage:[path substringFromIndex:9]];
7701 else if ([path hasPrefix:@"/files/"]) {
7702 NSString *name = [path substringFromIndex:7];
7704 if (Package *package = [database_ packageWithName:name]) {
7705 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
7706 [files setPackage:package];
7714 - (void) applicationOpenURL:(NSURL *)url {
7715 [super applicationOpenURL:url];
7717 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
7718 [self setPage:page];
7719 [buttonbar_ showSelectionForButton:tag];
7724 - (void) applicationDidFinishLaunching:(id)unused {
7726 Font12_ = [[UIFont systemFontOfSize:12] retain];
7727 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
7728 Font14_ = [[UIFont systemFontOfSize:14] retain];
7729 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
7730 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
7734 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
7735 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
7737 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
7739 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7740 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
7742 [window_ orderFront:self];
7743 [window_ makeKey:self];
7744 [window_ setHidden:NO];
7746 database_ = [Database sharedInstance];
7747 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
7748 [database_ setDelegate:progress_];
7749 [window_ setContentView:progress_];
7751 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
7752 [progress_ setContentView:underlay_];
7754 [progress_ resetView];
7757 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
7758 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
7759 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
7760 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
7761 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
7762 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
7763 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
7765 [self setIdleTimerDisabled:YES];
7767 hud_ = [[self addProgressHUD] retain];
7768 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
7770 [self setStatusBarShowsProgress:YES];
7773 detachNewThreadSelector:@selector(reorganize)
7781 - (void) showKeyboard:(BOOL)show {
7782 CGSize keysize = [UIKeyboard defaultSize];
7783 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
7784 CGRect keyup = keydown;
7785 keyup.origin.y -= keysize.height;
7787 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
7788 [animation setSignificantRectFields:2];
7791 [animation setStartFrame:keydown];
7792 [animation setEndFrame:keyup];
7793 [keyboard_ activate];
7795 [animation setStartFrame:keyup];
7796 [animation setEndFrame:keydown];
7797 [keyboard_ deactivate];
7800 [[UIAnimator sharedAnimator]
7801 addAnimations:[NSArray arrayWithObjects:animation, nil]
7802 withDuration:KeyboardTime_
7807 - (void) slideUp:(UIActionSheet *)alert {
7809 [alert presentSheetFromButtonBar:buttonbar_];
7811 [alert presentSheetInView:overlay_];
7816 void AddPreferences(NSString *plist) { _pooled
7817 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
7818 _assert(settings != NULL);
7819 NSMutableArray *items = [settings objectForKey:@"items"];
7823 for (NSMutableDictionary *item in items) {
7824 NSString *label = [item objectForKey:@"label"];
7825 if (label != nil && [label isEqualToString:@"Cydia"]) {
7832 for (size_t i(0); i != [items count]; ++i) {
7833 NSDictionary *item([items objectAtIndex:i]);
7834 NSString *label = [item objectForKey:@"label"];
7835 if (label != nil && [label isEqualToString:@"General"]) {
7836 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
7837 @"CydiaSettings", @"bundle",
7838 @"PSLinkCell", @"cell",
7839 [NSNumber numberWithBool:YES], @"hasIcon",
7840 [NSNumber numberWithBool:YES], @"isController",
7842 nil] atIndex:(i + 1)];
7848 _assert([settings writeToFile:plist atomically:YES] == YES);
7853 id Alloc_(id self, SEL selector) {
7854 id object = alloc_(self, selector);
7855 lprintf("[%s]A-%p\n", self->isa->name, object);
7860 id Dealloc_(id self, SEL selector) {
7861 id object = dealloc_(self, selector);
7862 lprintf("[%s]D-%p\n", self->isa->name, object);
7866 Class $WebDefaultUIKitDelegate;
7868 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
7870 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
7871 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
7872 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
7873 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
7876 int main(int argc, char *argv[]) { _pooled
7879 /* Library Hacks {{{ */
7880 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
7882 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
7883 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
7884 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
7885 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
7886 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
7889 /* Set Locale {{{ */
7890 Locale_ = CFLocaleCopyCurrent();
7891 Languages_ = [NSLocale preferredLanguages];
7892 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
7893 //NSLog(@"%@", [Languages_ description]);
7895 if (Languages_ == nil || [Languages_ count] == 0)
7898 lang = [[Languages_ objectAtIndex:0] UTF8String];
7899 setenv("LANG", lang, true);
7900 //std::setlocale(LC_ALL, lang);
7901 NSLog(@"Setting Language: %s", lang);
7904 // XXX: apr_app_initialize?
7907 /* Parse Arguments {{{ */
7908 bool substrate(false);
7914 for (int argi(1); argi != argc; ++argi)
7915 if (strcmp(argv[argi], "--") == 0) {
7917 argv[argi] = argv[0];
7923 for (int argi(1); argi != arge; ++argi)
7924 if (strcmp(args[argi], "--bootstrap") == 0)
7926 else if (strcmp(args[argi], "--substrate") == 0)
7929 fprintf(stderr, "unknown argument: %s\n", args[argi]);
7934 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
7935 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
7936 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
7937 Sounds_Keyboard_ = [keyboard boolValue];
7940 App_ = [[NSBundle mainBundle] bundlePath];
7941 Home_ = NSHomeDirectory();
7946 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
7947 alloc_ = alloc->method_imp;
7948 alloc->method_imp = (IMP) &Alloc_;*/
7950 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
7951 dealloc_ = dealloc->method_imp;
7952 dealloc->method_imp = (IMP) &Dealloc_;*/
7957 size = sizeof(maxproc);
7958 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
7959 perror("sysctlbyname(\"kern.maxproc\", ?)");
7960 else if (maxproc < 64) {
7962 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
7963 perror("sysctlbyname(\"kern.maxproc\", #)");
7966 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
7967 char *machine = new char[size];
7968 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
7969 perror("sysctlbyname(\"hw.machine\", ?)");
7973 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
7975 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
7976 Build_ = [system objectForKey:@"ProductBuildVersion"];
7977 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
7978 Product_ = [info objectForKey:@"SafariProductVersion"];
7979 Safari_ = [info objectForKey:@"CFBundleVersion"];
7982 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
7983 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
7985 /* Load Database {{{ */
7987 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
7989 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
7992 if (Metadata_ == NULL)
7993 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
7995 Settings_ = [Metadata_ objectForKey:@"Settings"];
7997 Packages_ = [Metadata_ objectForKey:@"Packages"];
7998 Sections_ = [Metadata_ objectForKey:@"Sections"];
7999 Sources_ = [Metadata_ objectForKey:@"Sources"];
8002 if (Settings_ != nil)
8003 Role_ = [Settings_ objectForKey:@"Role"];
8005 if (Packages_ == nil) {
8006 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8007 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8010 if (Sections_ == nil) {
8011 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8012 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8015 if (Sources_ == nil) {
8016 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8017 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8022 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8025 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8026 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8027 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8028 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8030 if (access("/User", F_OK) != 0) {
8032 system("/usr/libexec/cydia/firmware.sh");
8036 _assert([[NSFileManager defaultManager]
8037 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8038 withIntermediateDirectories:YES
8043 if (access("/tmp/cydia.chk", F_OK) == 0) {
8044 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8045 _assert(errno == ENOENT);
8046 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8047 _assert(errno == ENOENT);
8050 _assert(pkgInitConfig(*_config));
8051 _assert(pkgInitSystem(*_config, _system));
8054 _config->Set("APT::Acquire::Translation", lang);
8056 /* Color Choices {{{ */
8057 space_ = CGColorSpaceCreateDeviceRGB();
8059 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8060 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8061 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8062 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8063 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8064 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8065 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8066 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8067 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8068 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8069 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8070 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8071 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8072 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8073 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8076 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8077 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8080 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8082 /* UIKit Configuration {{{ */
8083 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8084 if ($GSFontSetUseLegacyFontMetrics != NULL)
8085 $GSFontSetUseLegacyFontMetrics(YES);
8087 UIKeyboardDisableAutomaticAppearance();
8091 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8093 CGColorSpaceRelease(space_);