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 #include <CoreFoundation/CFPriv.h>
53 #include <CoreFoundation/CFUniChar.h>
55 #import <QuartzCore/CALayer.h>
56 #import <UIKit/UIKit.h>
58 #include <WebCore/WebCoreThread.h>
59 #import <WebKit/WebDefaultUIKitDelegate.h>
66 #include <ext/stdio_filebuf.h>
68 #include <apt-pkg/acquire.h>
69 #include <apt-pkg/acquire-item.h>
70 #include <apt-pkg/algorithms.h>
71 #include <apt-pkg/cachefile.h>
72 #include <apt-pkg/clean.h>
73 #include <apt-pkg/configuration.h>
74 #include <apt-pkg/debindexfile.h>
75 #include <apt-pkg/debmetaindex.h>
76 #include <apt-pkg/error.h>
77 #include <apt-pkg/init.h>
78 #include <apt-pkg/mmap.h>
79 #include <apt-pkg/pkgrecords.h>
80 #include <apt-pkg/sha1.h>
81 #include <apt-pkg/sourcelist.h>
82 #include <apt-pkg/sptr.h>
83 #include <apt-pkg/strutl.h>
85 #include <apr-1/apr_pools.h>
87 #include <sys/types.h>
89 #include <sys/sysctl.h>
90 #include <sys/param.h>
91 #include <sys/mount.h>
97 #include <mach-o/nlist.h>
107 #include <ext/hash_map>
109 #import "BrowserView.h"
110 #import "ResetView.h"
112 #import "substrate.h"
115 //#define _finline __attribute__((force_inline))
116 #define _finline inline
121 #define _limit(count) do { \
122 static size_t _count(0); \
123 if (++_count == count) \
128 #define _timestamp ({ \
130 gettimeofday(&tv, NULL); \
131 tv.tv_sec * 1000000 + tv.tv_usec; \
134 typedef std::vector<class ProfileTime *> TimeList;
144 ProfileTime(const char *name) :
148 times_.push_back(this);
151 void AddTime(uint64_t time) {
158 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
170 ProfileTimer(ProfileTime &time) :
177 time_.AddTime(_timestamp - start_);
182 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
184 std::cerr << "========" << std::endl;
187 #define _profile(name) { \
188 static ProfileTime name(#name); \
189 ProfileTimer _ ## name(name);
193 /* Objective-C Handle<> {{{ */
194 template <typename Type_>
196 typedef _H<Type_> This_;
201 _finline void Retain_() {
206 _finline void Clear_() {
212 _finline _H(Type_ *value = NULL, bool mended = false) :
223 _finline This_ &operator =(Type_ *value) {
224 if (value_ != value) {
233 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
235 void NSLogPoint(const char *fix, const CGPoint &point) {
236 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
239 void NSLogRect(const char *fix, const CGRect &rect) {
240 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
243 @interface NSObject (Cydia)
244 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
245 - (id) yieldToSelector:(SEL)selector;
248 @implementation NSObject (Cydia)
253 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
254 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
255 id object([[context objectAtIndex:1] nonretainedObjectValue]);
256 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
258 /* XXX: deal with exceptions */
259 id value([self performSelector:selector withObject:object]);
261 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
262 [context removeAllObjects];
263 if ([signature methodReturnLength] != 0 && value != nil)
264 [context addObject:value];
269 performSelectorOnMainThread:@selector(doNothing)
275 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
276 /*return [self performSelector:selector withObject:object];*/
278 volatile bool stopped(false);
280 NSMutableArray *context([NSMutableArray arrayWithObjects:
281 [NSValue valueWithPointer:selector],
282 [NSValue valueWithNonretainedObject:object],
283 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
286 NSThread *thread([[[NSThread alloc]
288 selector:@selector(_yieldToContext:)
294 NSRunLoop *loop([NSRunLoop currentRunLoop]);
295 NSDate *future([NSDate distantFuture]);
297 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
299 return [context count] == 0 ? nil : [context objectAtIndex:0];
302 - (id) yieldToSelector:(SEL)selector {
303 return [self yieldToSelector:selector withObject:nil];
308 /* NSForcedOrderingSearch doesn't work on the iPhone */
309 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
310 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
311 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
313 /* iPhoneOS 2.0 Compatibility {{{ */
315 @interface UITextView (iPhoneOS)
316 - (void) setTextSize:(float)size;
319 @implementation UITextView (iPhoneOS)
321 - (void) setTextSize:(float)size {
322 [self setFont:[[self font] fontWithSize:size]];
329 extern NSString * const kCAFilterNearest;
331 /* Information Dictionaries {{{ */
332 @interface NSMutableArray (Cydia)
333 - (void) addInfoDictionary:(NSDictionary *)info;
336 @implementation NSMutableArray (Cydia)
338 - (void) addInfoDictionary:(NSDictionary *)info {
339 [self addObject:info];
344 @interface NSMutableDictionary (Cydia)
345 - (void) addInfoDictionary:(NSDictionary *)info;
348 @implementation NSMutableDictionary (Cydia)
350 - (void) addInfoDictionary:(NSDictionary *)info {
351 NSString *bundle = [info objectForKey:@"CFBundleIdentifier"];
352 [self setObject:info forKey:bundle];
357 /* Pop Transitions {{{ */
358 @interface PopTransitionView : UITransitionView {
363 @implementation PopTransitionView
365 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
366 if (from != nil && to == nil)
367 [self removeFromSuperview];
372 @implementation UIView (PopUpView)
374 - (void) popFromSuperviewAnimated:(BOOL)animated {
375 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
378 - (void) popSubview:(UIView *)view {
379 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
380 [transition setDelegate:transition];
381 [self addSubview:transition];
383 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
384 [transition transition:UITransitionNone toView:blank];
385 [transition transition:UITransitionPushFromBottom toView:view];
391 #define lprintf(args...) fprintf(stderr, args)
394 #define ForSaurik (0 && !ForRelease)
395 #define LogBrowser (0 && !ForRelease)
396 #define TrackResize (0 && !ForRelease)
397 #define ManualRefresh (1 && !ForRelease)
398 #define ShowInternals (0 && !ForRelease)
399 #define IgnoreInstall (0 && !ForRelease)
400 #define RecycleWebViews 0
401 #define AlwaysReload (1 && !ForRelease)
405 #define _trace(args...)
407 #define _profile(name) {
410 #define PrintTimes() do {} while (false)
414 @interface NSMutableArray (Radix)
415 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
416 - (void) radixSortUsingFunction:(uint32_t (*)(id, void *))function withArgument:(void *)argument;
424 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
425 struct RadixItem_ *lhs(swap), *rhs(swap + count);
427 static const size_t width = 32;
428 static const size_t bits = 11;
429 static const size_t slots = 1 << bits;
430 static const size_t passes = (width + (bits - 1)) / bits;
432 size_t *hist(new size_t[slots]);
434 for (size_t pass(0); pass != passes; ++pass) {
435 memset(hist, 0, sizeof(size_t) * slots);
437 for (size_t i(0); i != count; ++i) {
438 uint32_t key(lhs[i].key);
440 key &= _not(uint32_t) >> width - bits;
445 for (size_t i(0); i != slots; ++i) {
446 size_t local(offset);
451 for (size_t i(0); i != count; ++i) {
452 uint32_t key(lhs[i].key);
454 key &= _not(uint32_t) >> width - bits;
455 rhs[hist[key]++] = lhs[i];
458 RadixItem_ *tmp(lhs);
465 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
466 for (size_t i(0); i != count; ++i)
467 [values addObject:[self objectAtIndex:lhs[i].index]];
468 [self setArray:values];
473 @implementation NSMutableArray (Radix)
475 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
476 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
477 [invocation setSelector:selector];
478 [invocation setArgument:&object atIndex:2];
480 size_t count([self count]);
481 struct RadixItem_ *swap(new RadixItem_[count * 2]);
483 for (size_t i(0); i != count; ++i) {
484 RadixItem_ &item(swap[i]);
487 id object([self objectAtIndex:i]);
488 [invocation setTarget:object];
491 [invocation getReturnValue:&item.key];
494 RadixSort_(self, count, swap);
497 - (void) radixSortUsingFunction:(uint32_t (*)(id, void *))function withArgument:(void *)argument {
498 size_t count([self count]);
499 struct RadixItem_ *swap(new RadixItem_[count * 2]);
501 for (size_t i(0); i != count; ++i) {
502 RadixItem_ &item(swap[i]);
505 id object([self objectAtIndex:i]);
506 item.key = function(object, argument);
509 RadixSort_(self, count, swap);
515 /* Apple Bug Fixes {{{ */
516 @implementation UIWebDocumentView (Cydia)
518 - (void) _setScrollerOffset:(CGPoint)offset {
519 UIScroller *scroller([self _scroller]);
521 CGSize size([scroller contentSize]);
522 CGSize bounds([scroller bounds].size);
525 max.x = size.width - bounds.width;
526 max.y = size.height - bounds.height;
534 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
535 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
537 [scroller setOffset:offset];
544 kUIControlEventMouseDown = 1 << 0,
545 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
546 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
547 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
548 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
549 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
550 } UIControlEventMasks;
552 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
553 size_t length([self length] - state->state);
556 else if (length > count)
558 for (size_t i(0); i != length; ++i)
559 objects[i] = [self item:state->state++];
560 state->itemsPtr = objects;
561 state->mutationsPtr = (unsigned long *) self;
565 @interface NSString (UIKit)
566 - (NSString *) stringByAddingPercentEscapes;
567 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
570 @interface NSString (Cydia)
571 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
572 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
573 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
574 - (NSComparisonResult) compareByPath:(NSString *)other;
575 - (NSString *) stringByCachingURLWithCurrentCDN;
576 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
579 @implementation NSString (Cydia)
581 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
582 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
585 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
586 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
587 memcpy(data, bytes, length);
588 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
591 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
592 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
595 - (NSComparisonResult) compareByPath:(NSString *)other {
596 NSString *prefix = [self commonPrefixWithString:other options:0];
597 size_t length = [prefix length];
599 NSRange lrange = NSMakeRange(length, [self length] - length);
600 NSRange rrange = NSMakeRange(length, [other length] - length);
602 lrange = [self rangeOfString:@"/" options:0 range:lrange];
603 rrange = [other rangeOfString:@"/" options:0 range:rrange];
605 NSComparisonResult value;
607 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
608 value = NSOrderedSame;
609 else if (lrange.location == NSNotFound)
610 value = NSOrderedAscending;
611 else if (rrange.location == NSNotFound)
612 value = NSOrderedDescending;
614 value = NSOrderedSame;
616 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
617 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
618 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
619 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
621 NSComparisonResult result = [lpath compare:rpath];
622 return result == NSOrderedSame ? value : result;
625 - (NSString *) stringByCachingURLWithCurrentCDN {
627 stringByReplacingOccurrencesOfString:@"://"
628 withString:@"://ne.edgecastcdn.net/8003A4/"
630 /* XXX: this is somewhat inaccurate */
631 range:NSMakeRange(0, 10)
635 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
636 return [(id)CFURLCreateStringByAddingPercentEscapes(
641 kCFStringEncodingUTF8
647 static inline NSString *CYLocalizeEx(NSString *key, NSString *value = nil) {
648 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:nil];
651 #define CYLocalize(key) CYLocalizeEx(@ key)
659 _finline void clear_() {
665 _finline bool empty() const {
669 _finline size_t size() const {
673 _finline char *data() const {
677 _finline void clear() {
682 _finline CYString() :
689 _finline ~CYString() {
693 void operator =(const CYString &rhs) {
697 if (rhs.cache_ == nil)
700 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
703 void set(apr_pool_t *pool, const char *data, size_t size) {
709 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
710 memcpy(temp, data, size);
717 _finline void set(apr_pool_t *pool, const char *data) {
718 set(pool, data, data == NULL ? 0 : strlen(data));
721 _finline void set(apr_pool_t *pool, const std::string &rhs) {
722 set(pool, rhs.data(), rhs.size());
725 bool operator ==(const CYString &rhs) const {
726 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
730 if (cache_ == NULL) {
733 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
734 } return (id) cache_;
739 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
742 struct NSStringMapHash :
743 std::unary_function<NSString *, size_t>
745 _finline size_t operator ()(NSString *value) const {
746 return CFStringHashNSString((CFStringRef) value);
750 struct NSStringMapLess :
751 std::binary_function<NSString *, NSString *, bool>
753 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
754 return [lhs compare:rhs] == NSOrderedAscending;
758 struct NSStringMapEqual :
759 std::binary_function<NSString *, NSString *, bool>
761 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
762 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
763 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
764 //[lhs isEqualToString:rhs];
768 /* Perl-Compatible RegEx {{{ */
778 Pcre(const char *regex) :
783 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
786 lprintf("%d:%s\n", offset, error);
790 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
791 matches_ = new int[(capture_ + 1) * 3];
799 NSString *operator [](size_t match) {
800 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
803 bool operator ()(NSString *data) {
804 // XXX: length is for characters, not for bytes
805 return operator ()([data UTF8String], [data length]);
808 bool operator ()(const char *data, size_t size) {
810 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
814 /* Mime Addresses {{{ */
815 @interface Address : NSObject {
821 - (NSString *) address;
823 - (void) setAddress:(NSString *)address;
825 + (Address *) addressWithString:(NSString *)string;
826 - (Address *) initWithString:(NSString *)string;
829 @implementation Address
838 - (NSString *) name {
842 - (NSString *) address {
846 - (void) setAddress:(NSString *)address {
848 [address_ autorelease];
852 address_ = [address retain];
855 + (Address *) addressWithString:(NSString *)string {
856 return [[[Address alloc] initWithString:string] autorelease];
859 + (NSArray *) _attributeKeys {
860 return [NSArray arrayWithObjects:@"address", @"name", nil];
863 - (NSArray *) attributeKeys {
864 return [[self class] _attributeKeys];
867 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
868 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
871 - (Address *) initWithString:(NSString *)string {
872 if ((self = [super init]) != nil) {
873 const char *data = [string UTF8String];
874 size_t size = [string length];
876 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
878 if (address_r(data, size)) {
879 name_ = [address_r[1] retain];
880 address_ = [address_r[2] retain];
882 name_ = [string retain];
890 /* CoreGraphics Primitives {{{ */
901 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
904 Set(space, red, green, blue, alpha);
909 CGColorRelease(color_);
916 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
918 float color[] = {red, green, blue, alpha};
919 color_ = CGColorCreate(space, color);
922 operator CGColorRef() {
928 extern "C" void UISetColor(CGColorRef color);
930 /* Random Global Variables {{{ */
931 static const int PulseInterval_ = 50000;
932 static const int ButtonBarHeight_ = 48;
933 static const float KeyboardTime_ = 0.3f;
935 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
936 #define SandboxTemplate_ "/usr/share/sandbox/SandboxTemplate.sb"
937 #define NotifyConfig_ "/etc/notify.conf"
939 static bool Queuing_;
941 static CGColor Blue_;
942 static CGColor Blueish_;
943 static CGColor Black_;
945 static CGColor White_;
946 static CGColor Gray_;
947 static CGColor Green_;
948 static CGColor Purple_;
949 static CGColor Purplish_;
951 static UIColor *InstallingColor_;
952 static UIColor *RemovingColor_;
954 static NSString *App_;
955 static NSString *Home_;
956 static BOOL Sounds_Keyboard_;
958 static BOOL Advanced_;
960 static BOOL Ignored_;
962 static UIFont *Font12_;
963 static UIFont *Font12Bold_;
964 static UIFont *Font14_;
965 static UIFont *Font18Bold_;
966 static UIFont *Font22Bold_;
968 static const char *Machine_ = NULL;
969 static const NSString *UniqueID_ = nil;
970 static const NSString *Build_ = nil;
971 static const NSString *Product_ = nil;
972 static const NSString *Safari_ = nil;
976 CGColorSpaceRef space_;
981 static NSDictionary *SectionMap_;
982 static NSMutableDictionary *Metadata_;
983 static _transient NSMutableDictionary *Settings_;
984 static _transient NSString *Role_;
985 static _transient NSMutableDictionary *Packages_;
986 static _transient NSMutableDictionary *Sections_;
987 static _transient NSMutableDictionary *Sources_;
988 static bool Changed_;
992 static NSMutableArray *Documents_;
995 NSString *GetLastUpdate() {
996 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
999 return CYLocalize("NEVER_OR_UNKNOWN");
1001 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1002 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1004 CFRelease(formatter);
1006 return [(NSString *) formatted autorelease];
1009 /* Display Helpers {{{ */
1010 inline float Interpolate(float begin, float end, float fraction) {
1011 return (end - begin) * fraction + begin;
1014 /* XXX: localize this! */
1015 NSString *SizeString(double size) {
1016 bool negative = size < 0;
1021 while (size > 1024) {
1026 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1028 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1031 NSString *StripVersion(const char *version) {
1032 const char *colon(strchr(version, ':'));
1034 version = colon + 1;
1035 return [NSString stringWithUTF8String:version];
1038 NSString *StripVersion(NSString *version) {
1039 NSRange colon = [version rangeOfString:@":"];
1040 if (colon.location != NSNotFound)
1041 version = [version substringFromIndex:(colon.location + 1)];
1045 NSString *LocalizeSection(NSString *section) {
1046 static Pcre title_r("^(.*?) \\((.*)\\)$");
1047 if (title_r(section)) {
1048 NSString *parent(title_r[1]);
1049 NSString *child(title_r[2]);
1051 return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"),
1052 LocalizeSection(parent),
1053 LocalizeSection(child)
1057 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1060 NSString *Simplify(NSString *title) {
1061 const char *data = [title UTF8String];
1062 size_t size = [title length];
1064 static Pcre square_r("^\\[(.*)\\]$");
1065 if (square_r(data, size))
1066 return Simplify(square_r[1]);
1068 static Pcre paren_r("^\\((.*)\\)$");
1069 if (paren_r(data, size))
1070 return Simplify(paren_r[1]);
1072 static Pcre title_r("^(.*?) \\((.*)\\)$");
1073 if (title_r(data, size))
1074 return Simplify(title_r[1]);
1079 _finline static void Stifle(char &value) {
1080 value = (value & 0xdf) ^ 0x40;
1084 bool isSectionVisible(NSString *section) {
1085 NSDictionary *metadata([Sections_ objectForKey:section]);
1086 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1087 return hidden == nil || ![hidden boolValue];
1090 /* Delegate Prototypes {{{ */
1094 @interface NSObject (ProgressDelegate)
1097 @implementation NSObject(ProgressDelegate)
1099 - (void) _setProgressError:(NSArray *)args {
1100 [self performSelector:@selector(setProgressError:forPackage:)
1101 withObject:[args objectAtIndex:0]
1102 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1108 @protocol ProgressDelegate
1109 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1110 - (void) setProgressTitle:(NSString *)title;
1111 - (void) setProgressPercent:(float)percent;
1112 - (void) startProgress;
1113 - (void) addProgressOutput:(NSString *)output;
1114 - (bool) isCancelling:(size_t)received;
1117 @protocol ConfigurationDelegate
1118 - (void) repairWithSelector:(SEL)selector;
1119 - (void) setConfigurationData:(NSString *)data;
1124 @protocol CydiaDelegate
1125 - (void) setPackageView:(PackageView *)view;
1126 - (void) clearPackage:(Package *)package;
1127 - (void) installPackage:(Package *)package;
1128 - (void) removePackage:(Package *)package;
1129 - (void) slideUp:(UIActionSheet *)alert;
1130 - (void) distUpgrade;
1131 - (void) updateData;
1133 - (void) askForSettings;
1134 - (UIProgressHUD *) addProgressHUD;
1135 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1136 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1137 - (RVPage *) pageForPackage:(NSString *)name;
1138 - (void) openMailToURL:(NSURL *)url;
1139 - (void) clearFirstResponder;
1140 - (PackageView *) packageView;
1144 /* Status Delegation {{{ */
1146 public pkgAcquireStatus
1149 _transient NSObject<ProgressDelegate> *delegate_;
1157 void setDelegate(id delegate) {
1158 delegate_ = delegate;
1161 virtual bool MediaChange(std::string media, std::string drive) {
1165 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1168 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1169 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1170 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1173 virtual void Done(pkgAcquire::ItemDesc &item) {
1176 virtual void Fail(pkgAcquire::ItemDesc &item) {
1178 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1179 item.Owner->Status == pkgAcquire::Item::StatDone
1183 std::string &error(item.Owner->ErrorText);
1187 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1188 NSArray *fields([description componentsSeparatedByString:@" "]);
1189 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1191 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1192 withObject:[NSArray arrayWithObjects:
1193 [NSString stringWithUTF8String:error.c_str()],
1200 virtual bool Pulse(pkgAcquire *Owner) {
1201 bool value = pkgAcquireStatus::Pulse(Owner);
1204 double(CurrentBytes + CurrentItems) /
1205 double(TotalBytes + TotalItems)
1208 [delegate_ setProgressPercent:percent];
1209 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1212 virtual void Start() {
1213 [delegate_ startProgress];
1216 virtual void Stop() {
1220 /* Progress Delegation {{{ */
1225 _transient id<ProgressDelegate> delegate_;
1228 virtual void Update() {
1229 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1230 [delegate_ setProgressPercent:(Percent / 100)];*/
1239 void setDelegate(id delegate) {
1240 delegate_ = delegate;
1243 virtual void Done() {
1244 //[delegate_ setProgressPercent:1];
1249 /* Database Interface {{{ */
1250 @interface Database : NSObject {
1256 pkgCacheFile cache_;
1257 pkgDepCache::Policy *policy_;
1258 pkgRecords *records_;
1259 pkgProblemResolver *resolver_;
1260 pkgAcquire *fetcher_;
1262 SPtr<pkgPackageManager> manager_;
1263 pkgSourceList *list_;
1265 NSMutableDictionary *sources_;
1266 NSMutableArray *packages_;
1268 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1277 + (Database *) sharedInstance;
1280 - (void) _readCydia:(NSNumber *)fd;
1281 - (void) _readStatus:(NSNumber *)fd;
1282 - (void) _readOutput:(NSNumber *)fd;
1286 - (Package *) packageWithName:(NSString *)name;
1288 - (pkgCacheFile &) cache;
1289 - (pkgDepCache::Policy *) policy;
1290 - (pkgRecords *) records;
1291 - (pkgProblemResolver *) resolver;
1292 - (pkgAcquire &) fetcher;
1293 - (pkgSourceList &) list;
1294 - (NSArray *) packages;
1295 - (NSArray *) sources;
1296 - (void) reloadData;
1304 - (void) updateWithStatus:(Status &)status;
1306 - (void) setDelegate:(id)delegate;
1307 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1311 /* Source Class {{{ */
1312 @interface Source : NSObject {
1313 NSString *description_;
1319 NSString *distribution_;
1323 NSString *defaultIcon_;
1325 NSDictionary *record_;
1329 - (Source *) initWithMetaIndex:(metaIndex *)index;
1331 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1333 - (NSString *) supportForPackage:(NSString *)package;
1335 - (NSDictionary *) record;
1339 - (NSString *) distribution;
1340 - (NSString *) type;
1342 - (NSString *) host;
1344 - (NSString *) name;
1345 - (NSString *) description;
1346 - (NSString *) label;
1347 - (NSString *) origin;
1348 - (NSString *) version;
1350 - (NSString *) defaultIcon;
1354 @implementation Source
1356 #define _clear(field) \
1363 _clear(distribution_)
1366 _clear(description_)
1371 _clear(defaultIcon_)
1380 + (NSArray *) _attributeKeys {
1381 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1384 - (NSArray *) attributeKeys {
1385 return [[self class] _attributeKeys];
1388 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1389 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1392 - (void) setMetaIndex:(metaIndex *)index {
1395 trusted_ = index->IsTrusted();
1397 uri_ = [[NSString stringWithUTF8String:index->GetURI().c_str()] retain];
1398 distribution_ = [[NSString stringWithUTF8String:index->GetDist().c_str()] retain];
1399 type_ = [[NSString stringWithUTF8String:index->GetType()] retain];
1401 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1402 if (dindex != NULL) {
1403 std::ifstream release(dindex->MetaIndexFile("Release").c_str());
1405 while (std::getline(release, line)) {
1406 std::string::size_type colon(line.find(':'));
1407 if (colon == std::string::npos)
1410 std::string name(line.substr(0, colon));
1411 std::string value(line.substr(colon + 1));
1412 while (!value.empty() && value[0] == ' ')
1413 value = value.substr(1);
1415 if (name == "Default-Icon")
1416 defaultIcon_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1417 else if (name == "Description")
1418 description_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1419 else if (name == "Label")
1420 label_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1421 else if (name == "Origin")
1422 origin_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1423 else if (name == "Support")
1424 support_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1425 else if (name == "Version")
1426 version_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1430 record_ = [Sources_ objectForKey:[self key]];
1432 record_ = [record_ retain];
1435 - (Source *) initWithMetaIndex:(metaIndex *)index {
1436 if ((self = [super init]) != nil) {
1437 [self setMetaIndex:index];
1441 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1442 NSDictionary *lhr = [self record];
1443 NSDictionary *rhr = [source record];
1446 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1448 NSString *lhs = [self name];
1449 NSString *rhs = [source name];
1451 if ([lhs length] != 0 && [rhs length] != 0) {
1452 unichar lhc = [lhs characterAtIndex:0];
1453 unichar rhc = [rhs characterAtIndex:0];
1455 if (isalpha(lhc) && !isalpha(rhc))
1456 return NSOrderedAscending;
1457 else if (!isalpha(lhc) && isalpha(rhc))
1458 return NSOrderedDescending;
1461 return [lhs compare:rhs options:LaxCompareOptions_];
1464 - (NSString *) supportForPackage:(NSString *)package {
1465 return support_ == nil ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1468 - (NSDictionary *) record {
1476 - (NSString *) uri {
1480 - (NSString *) distribution {
1481 return distribution_;
1484 - (NSString *) type {
1488 - (NSString *) key {
1489 return [NSString stringWithFormat:@"%@:%@:%@", type_, uri_, distribution_];
1492 - (NSString *) host {
1493 return [[[NSURL URLWithString:[self uri]] host] lowercaseString];
1496 - (NSString *) name {
1497 return origin_ == nil ? [self host] : origin_;
1500 - (NSString *) description {
1501 return description_;
1504 - (NSString *) label {
1505 return label_ == nil ? [self host] : label_;
1508 - (NSString *) origin {
1512 - (NSString *) version {
1516 - (NSString *) defaultIcon {
1517 return defaultIcon_;
1522 /* Relationship Class {{{ */
1523 @interface Relationship : NSObject {
1528 - (NSString *) type;
1530 - (NSString *) name;
1534 @implementation Relationship
1542 - (NSString *) type {
1550 - (NSString *) name {
1557 /* Package Class {{{ */
1558 @interface Package : NSObject {
1561 pkgCache::VerIterator version_;
1562 pkgCache::PkgIterator iterator_;
1563 _transient Database *database_;
1564 pkgCache::VerFileIterator file_;
1570 NSString *section$_;
1575 NSString *installed_;
1581 CYString depiction_;
1594 NSArray *relationships_;
1596 NSMutableDictionary *metadata_;
1597 _transient NSDate *firstSeen_;
1598 _transient NSDate *lastSeen_;
1602 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1603 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1605 - (pkgCache::PkgIterator) iterator;
1607 - (NSString *) section;
1608 - (NSString *) simpleSection;
1610 - (NSString *) longSection;
1611 - (NSString *) shortSection;
1615 - (Address *) maintainer;
1617 - (NSString *) description;
1620 - (NSMutableDictionary *) metadata;
1622 - (BOOL) subscribed;
1625 - (NSString *) latest;
1626 - (NSString *) installed;
1629 - (BOOL) upgradableAndEssential:(BOOL)essential;
1632 - (BOOL) unfiltered;
1636 - (BOOL) halfConfigured;
1637 - (BOOL) halfInstalled;
1639 - (NSString *) mode;
1642 - (NSString *) name;
1643 - (NSString *) tagline;
1645 - (NSString *) homepage;
1646 - (NSString *) depiction;
1647 - (Address *) author;
1649 - (NSString *) support;
1651 - (NSArray *) files;
1652 - (NSArray *) relationships;
1653 - (NSArray *) warnings;
1654 - (NSArray *) applications;
1656 - (Source *) source;
1657 - (NSString *) role;
1659 - (BOOL) matches:(NSString *)text;
1661 - (bool) hasSupportingRole;
1662 - (BOOL) hasTag:(NSString *)tag;
1663 - (NSString *) primaryPurpose;
1664 - (NSArray *) purposes;
1665 - (bool) isCommercial;
1667 - (uint32_t) compareByPrefix;
1668 - (uint32_t) compareBySection:(NSArray *)sections;
1670 - (uint32_t) compareForChanges;
1675 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1676 - (bool) isInstalledAndVisible:(NSNumber *)number;
1677 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1678 - (bool) isVisibleInSource:(Source *)source;
1682 uint32_t PackageChangesRadix(Package *self, void *) {
1687 uint32_t timestamp : 30;
1688 uint32_t ignored : 1;
1689 uint32_t upgradable : 1;
1693 bool upgradable([self upgradableAndEssential:YES]);
1694 value.bits.upgradable = upgradable ? 1 : 0;
1697 value.bits.timestamp = 0;
1698 value.bits.ignored = [self ignored] ? 0 : 1;
1699 value.bits.upgradable = 1;
1701 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1702 value.bits.ignored = 0;
1703 value.bits.upgradable = 0;
1706 return _not(uint32_t) - value.key;
1709 CFStringRef (*PackageName)(Package *self, SEL sel);
1711 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1712 _profile(PackageNameCompare)
1713 CFStringRef lhn, rhn;
1716 _profile(PackageNameCompare$Setup)
1717 lhn = PackageName(lhs, @selector(name));
1718 rhn = PackageName(rhs, @selector(name));
1721 _profile(PackageNameCompare$Nothing)
1724 _profile(PackageNameCompare$Length)
1725 length = CFStringGetLength(lhn);
1728 _profile(PackageNameCompare$NumbersLast)
1729 if (length != 0 && CFStringGetLength(rhn) != 0) {
1730 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1731 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1732 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1733 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1734 return lha ? NSOrderedAscending : NSOrderedDescending;
1738 _profile(PackageNameCompare$Compare)
1739 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1744 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
1745 return PackageNameCompare(*lhs, *rhs, arg);
1748 struct PackageNameOrdering :
1749 std::binary_function<Package *, Package *, bool>
1751 _finline bool operator ()(Package *lhs, Package *rhs) const {
1752 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1756 @implementation Package
1761 if (section$_ != nil)
1762 [section$_ release];
1766 if (installed_ != nil)
1767 [installed_ release];
1769 if (sponsor$_ != nil)
1770 [sponsor$_ release];
1771 if (author$_ != nil)
1778 if (relationships_ != nil)
1779 [relationships_ release];
1780 if (metadata_ != nil)
1781 [metadata_ release];
1786 + (NSString *) webScriptNameForSelector:(SEL)selector {
1787 if (selector == @selector(hasTag:))
1793 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1794 return [self webScriptNameForSelector:selector] == nil;
1797 + (NSArray *) _attributeKeys {
1798 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];
1801 - (NSArray *) attributeKeys {
1802 return [[self class] _attributeKeys];
1805 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1806 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1809 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
1810 if ((self = [super init]) != nil) {
1811 _profile(Package$initWithVersion)
1812 @synchronized (database) {
1813 era_ = [database era];
1816 iterator_ = version.ParentPkg();
1817 database_ = database;
1819 _profile(Package$initWithVersion$Latest)
1820 latest_ = [StripVersion(version_.VerStr()) retain];
1823 pkgCache::VerIterator current(iterator_.CurrentVer());
1825 installed_ = [StripVersion(current.VerStr()) retain];
1827 if (!version_.end())
1828 file_ = version_.FileList();
1830 pkgCache &cache([database_ cache]);
1831 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
1834 _profile(Package$initWithVersion$Name)
1835 id_.set(pool, iterator_.Name());
1839 source_ = [database_ getSource:file_.File()];
1844 _profile(Package$initWithVersion$Parse)
1845 pkgRecords::Parser *parser;
1847 _profile(Package$initWithVersion$Parse$Lookup)
1848 parser = &[database_ records]->Lookup(file_);
1854 _profile(Package$initWithVersion$Parse$Find)
1861 {"depiction", &depiction_},
1862 {"homepage", &homepage_},
1863 {"website", &website},
1864 {"support", &support_},
1865 {"sponsor", &sponsor_},
1866 {"author", &author_},
1870 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1871 const char *start, *end;
1873 if (parser->Find(names[i].name_, start, end)) {
1874 CYString &value(*names[i].value_);
1875 _profile(Package$initWithVersion$Parse$Value)
1876 value.set(pool, start, end - start);
1882 _profile(Package$initWithVersion$Parse$Tagline)
1883 tagline_.set(pool, parser->ShortDesc());
1886 _profile(Package$initWithVersion$Parse$Retain)
1887 if (!homepage_.empty())
1888 homepage_ = website;
1889 if (homepage_ == depiction_)
1892 tags_ = [[tag componentsSeparatedByString:@", "] retain];
1896 _profile(Package$initWithVersion$Tags)
1898 for (NSString *tag in tags_)
1899 if ([tag hasPrefix:@"role::"]) {
1900 role_ = [[tag substringFromIndex:6] retain];
1905 bool changed(false);
1906 NSString *key([id_ lowercaseString]);
1908 _profile(Package$initWithVersion$Metadata)
1909 metadata_ = [Packages_ objectForKey:key];
1911 if (metadata_ == nil) {
1912 firstSeen_ = [now_ retain];
1914 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
1915 firstSeen_, @"FirstSeen",
1916 latest_, @"LastVersion",
1921 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
1922 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
1924 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
1925 subscribed_ = [subscribed boolValue];
1927 NSString *version([metadata_ objectForKey:@"LastVersion"]);
1929 if (firstSeen_ == nil) {
1930 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
1931 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
1935 if (version == nil) {
1936 [metadata_ setObject:latest_ forKey:@"LastVersion"];
1938 } else if (![version isEqualToString:latest_]) {
1939 [metadata_ setObject:latest_ forKey:@"LastVersion"];
1941 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
1946 metadata_ = [metadata_ retain];
1949 [Packages_ setObject:metadata_ forKey:key];
1954 _profile(Package$initWithVersion$Section)
1955 section_.set(pool, iterator_.Section());
1958 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
1959 visible_ = [self hasSupportingRole] && [self unfiltered];
1960 } _end } return self;
1963 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
1964 pkgCache::VerIterator version;
1966 _profile(Package$packageWithIterator$GetCandidateVer)
1967 version = [database policy]->GetCandidateVer(iterator);
1973 return [[[Package alloc]
1974 initWithVersion:version
1981 - (pkgCache::PkgIterator) iterator {
1985 - (NSString *) section {
1986 if (section$_ == nil) {
1987 if (section_.empty())
1990 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
1991 NSString *name(section_);
1994 if (NSDictionary *value = [SectionMap_ objectForKey:name])
1995 if (NSString *rename = [value objectForKey:@"Rename"]) {
2000 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2004 - (NSString *) simpleSection {
2005 if (NSString *section = [self section])
2006 return Simplify(section);
2011 - (NSString *) longSection {
2012 return LocalizeSection(section_);
2015 - (NSString *) shortSection {
2016 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2019 - (NSString *) uri {
2022 pkgIndexFile *index;
2023 pkgCache::PkgFileIterator file(file_.File());
2024 if (![database_ list].FindIndex(file, index))
2026 return [NSString stringWithUTF8String:iterator_->Path];
2027 //return [NSString stringWithUTF8String:file.Site()];
2028 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2032 - (Address *) maintainer {
2035 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2036 const std::string &maintainer(parser->Maintainer());
2037 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2041 return version_.end() ? 0 : version_->InstalledSize;
2044 - (NSString *) description {
2047 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2048 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2050 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2051 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2052 if ([lines count] < 2)
2055 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2056 for (size_t i(1), e([lines count]); i != e; ++i) {
2057 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2058 [trimmed addObject:trim];
2061 return [trimmed componentsJoinedByString:@"\n"];
2065 _profile(Package$index)
2066 CFStringRef name((CFStringRef) [self name]);
2067 if (CFStringGetLength(name) == 0)
2069 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2070 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2072 return toupper(character);
2076 - (NSMutableDictionary *) metadata {
2081 if (subscribed_ && lastSeen_ != nil)
2086 - (BOOL) subscribed {
2091 NSDictionary *metadata([self metadata]);
2092 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2093 return [ignored boolValue];
2098 - (NSString *) latest {
2102 - (NSString *) installed {
2107 return !version_.end();
2110 - (BOOL) upgradableAndEssential:(BOOL)essential {
2111 _profile(Package$upgradableAndEssential)
2112 pkgCache::VerIterator current(iterator_.CurrentVer());
2114 return essential && essential_ && visible_;
2116 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2120 - (BOOL) essential {
2125 return [database_ cache][iterator_].InstBroken();
2128 - (BOOL) unfiltered {
2129 NSString *section([self section]);
2130 return section == nil || isSectionVisible(section);
2138 unsigned char current(iterator_->CurrentState);
2139 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2142 - (BOOL) halfConfigured {
2143 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2146 - (BOOL) halfInstalled {
2147 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2151 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2152 return state.Mode != pkgDepCache::ModeKeep;
2155 - (NSString *) mode {
2156 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2158 switch (state.Mode) {
2159 case pkgDepCache::ModeDelete:
2160 if ((state.iFlags & pkgDepCache::Purge) != 0)
2164 case pkgDepCache::ModeKeep:
2165 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2166 return @"REINSTALL";
2167 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2171 case pkgDepCache::ModeInstall:
2172 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2173 return @"REINSTALL";
2174 else*/ switch (state.Status) {
2176 return @"DOWNGRADE";
2182 return @"NEW_INSTALL";
2195 - (NSString *) name {
2196 return name_.empty() ? id_ : name_;
2199 - (NSString *) tagline {
2203 - (UIImage *) icon {
2204 NSString *section = [self simpleSection];
2208 if ([icon_ hasPrefix:@"file:///"])
2209 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2210 if (icon == nil) if (section != nil)
2211 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2212 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2213 if ([dicon hasPrefix:@"file:///"])
2214 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2216 icon = [UIImage applicationImageNamed:@"unknown.png"];
2220 - (NSString *) homepage {
2224 - (NSString *) depiction {
2228 - (Address *) sponsor {
2229 if (sponsor$_ == nil) {
2230 if (sponsor_.empty())
2232 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2236 - (Address *) author {
2237 if (author$_ == nil) {
2238 if (author_.empty())
2240 author$_ = [[Address addressWithString:author_] retain];
2244 - (NSString *) support {
2245 return support_ != nil ? support_ : [[self source] supportForPackage:id_];
2248 - (NSArray *) files {
2249 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2250 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2253 fin.open([path UTF8String]);
2258 while (std::getline(fin, line))
2259 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2264 - (NSArray *) relationships {
2265 return relationships_;
2268 - (NSArray *) warnings {
2269 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2270 const char *name(iterator_.Name());
2272 size_t length(strlen(name));
2273 if (length < 2) invalid:
2274 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2275 else for (size_t i(0); i != length; ++i)
2277 /* XXX: technically this is not allowed */
2278 (name[i] < 'A' || name[i] > 'Z') &&
2279 (name[i] < 'a' || name[i] > 'z') &&
2280 (name[i] < '0' || name[i] > '9') &&
2281 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2284 if (strcmp(name, "cydia") != 0) {
2286 bool _private = false;
2289 bool repository = [[self section] isEqualToString:@"Repositories"];
2291 if (NSArray *files = [self files])
2292 for (NSString *file in files)
2293 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2295 else if (!_private && [file isEqualToString:@"/private"])
2297 else if (!stash && [file isEqualToString:@"/var/stash"])
2300 /* XXX: this is not sensitive enough. only some folders are valid. */
2301 if (cydia && !repository)
2302 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2304 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2306 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2309 return [warnings count] == 0 ? nil : warnings;
2312 - (NSArray *) applications {
2313 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2315 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2317 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2318 if (NSArray *files = [self files])
2319 for (NSString *file in files)
2320 if (application_r(file)) {
2321 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2322 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2323 if ([id isEqualToString:me])
2326 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2328 display = application_r[1];
2330 NSString *bundle([file stringByDeletingLastPathComponent]);
2331 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2332 if (icon == nil || [icon length] == 0)
2334 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2336 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2337 [applications addObject:application];
2339 [application addObject:id];
2340 [application addObject:display];
2341 [application addObject:url];
2344 return [applications count] == 0 ? nil : applications;
2347 - (Source *) source {
2349 @synchronized (database_) {
2350 if ([database_ era] != era_ || file_.end())
2353 source_ = [database_ getSource:file_.File()];
2365 - (NSString *) role {
2369 - (BOOL) matches:(NSString *)text {
2375 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2376 if (range.location != NSNotFound)
2379 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2380 if (range.location != NSNotFound)
2383 range = [[self tagline] rangeOfString:text options:MatchCompareOptions_];
2384 if (range.location != NSNotFound)
2390 - (bool) hasSupportingRole {
2393 if ([role_ isEqualToString:@"enduser"])
2395 if ([Role_ isEqualToString:@"User"])
2397 if ([role_ isEqualToString:@"hacker"])
2399 if ([Role_ isEqualToString:@"Hacker"])
2401 if ([role_ isEqualToString:@"developer"])
2403 if ([Role_ isEqualToString:@"Developer"])
2408 - (BOOL) hasTag:(NSString *)tag {
2409 return tags_ == nil ? NO : [tags_ containsObject:tag];
2412 - (NSString *) primaryPurpose {
2413 for (NSString *tag in tags_)
2414 if ([tag hasPrefix:@"purpose::"])
2415 return [tag substringFromIndex:9];
2419 - (NSArray *) purposes {
2420 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2421 for (NSString *tag in tags_)
2422 if ([tag hasPrefix:@"purpose::"])
2423 [purposes addObject:[tag substringFromIndex:9]];
2424 return [purposes count] == 0 ? nil : purposes;
2427 - (bool) isCommercial {
2428 return [self hasTag:@"cydia::commercial"];
2431 - (uint32_t) compareByPrefix {
2434 CYString &name(name_.empty() ? id_ : name_);
2435 if (name.size() <= offset)
2437 size_t size(name.size() - offset);
2441 memcpy(data, name.data() + offset, 4);
2443 memcpy(data, name.data() + offset, size);
2444 memset(data + size, 0, 4 - size);
2452 /* XXX: ntohl may be more honest */
2453 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2456 - (uint32_t) compareBySection:(NSArray *)sections {
2457 NSString *section([self section]);
2458 for (size_t i(0), e([sections count]); i != e; ++i) {
2459 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2463 return _not(uint32_t);
2466 - (uint32_t) compareForChanges {
2471 uint32_t timestamp : 30;
2472 uint32_t ignored : 1;
2473 uint32_t upgradable : 1;
2477 bool upgradable([self upgradableAndEssential:YES]);
2478 value.bits.upgradable = upgradable ? 1 : 0;
2481 value.bits.timestamp = 0;
2482 value.bits.ignored = [self ignored] ? 0 : 1;
2483 value.bits.upgradable = 1;
2485 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2486 value.bits.ignored = 0;
2487 value.bits.upgradable = 0;
2490 return _not(uint32_t) - value.key;
2494 pkgProblemResolver *resolver = [database_ resolver];
2495 resolver->Clear(iterator_);
2496 resolver->Protect(iterator_);
2500 pkgProblemResolver *resolver = [database_ resolver];
2501 resolver->Clear(iterator_);
2502 resolver->Protect(iterator_);
2503 pkgCacheFile &cache([database_ cache]);
2504 cache->MarkInstall(iterator_, false);
2505 pkgDepCache::StateCache &state((*cache)[iterator_]);
2506 if (!state.Install())
2507 cache->SetReInstall(iterator_, true);
2511 pkgProblemResolver *resolver = [database_ resolver];
2512 resolver->Clear(iterator_);
2513 resolver->Protect(iterator_);
2514 resolver->Remove(iterator_);
2515 [database_ cache]->MarkDelete(iterator_, true);
2518 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2519 _profile(Package$isUnfilteredAndSearchedForBy)
2522 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2523 value &= [self unfiltered];
2526 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2527 value &= [self matches:search];
2534 - (bool) isInstalledAndVisible:(NSNumber *)number {
2535 return (![number boolValue] || [self visible]) && [self installed] != nil;
2538 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2539 NSString *section = [self section];
2543 [self installed] == nil && (
2545 section == nil && [name length] == 0 ||
2546 [name isEqualToString:section]
2550 - (bool) isVisibleInSource:(Source *)source {
2551 return [self source] == source && [self visible];
2556 /* Section Class {{{ */
2557 @interface Section : NSObject {
2562 NSString *localized_;
2565 - (NSComparisonResult) compareByLocalized:(Section *)section;
2566 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2567 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2568 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2569 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2570 - (NSString *) name;
2577 - (void) addToCount;
2579 - (void) setCount:(size_t)count;
2580 - (NSString *) localized;
2584 @implementation Section
2588 if (localized_ != nil)
2589 [localized_ release];
2593 - (NSComparisonResult) compareByLocalized:(Section *)section {
2594 NSString *lhs(localized_);
2595 NSString *rhs([section localized]);
2597 /*if ([lhs length] != 0 && [rhs length] != 0) {
2598 unichar lhc = [lhs characterAtIndex:0];
2599 unichar rhc = [rhs characterAtIndex:0];
2601 if (isalpha(lhc) && !isalpha(rhc))
2602 return NSOrderedAscending;
2603 else if (!isalpha(lhc) && isalpha(rhc))
2604 return NSOrderedDescending;
2607 return [lhs compare:rhs options:LaxCompareOptions_];
2610 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2611 if ((self = [self initWithName:name localize:NO]) != nil) {
2612 if (localized != nil)
2613 localized_ = [localized retain];
2617 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2618 return [self initWithName:name row:0 localize:localize];
2621 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2622 if ((self = [super init]) != nil) {
2623 name_ = [name retain];
2627 localized_ = [LocalizeSection(name_) retain];
2631 /* XXX: localize the index thingees */
2632 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2633 if ((self = [super init]) != nil) {
2634 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2640 - (NSString *) name {
2660 - (void) addToCount {
2664 - (void) setCount:(size_t)count {
2668 - (NSString *) localized {
2676 static NSArray *Finishes_;
2678 /* Database Implementation {{{ */
2679 @implementation Database
2681 + (Database *) sharedInstance {
2682 static Database *instance;
2683 if (instance == nil)
2684 instance = [[Database alloc] init];
2694 NSRecycleZone(zone_);
2695 // XXX: malloc_destroy_zone(zone_);
2696 apr_pool_destroy(pool_);
2700 - (void) _readCydia:(NSNumber *)fd { _pooled
2701 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2702 std::istream is(&ib);
2705 static Pcre finish_r("^finish:([^:]*)$");
2707 while (std::getline(is, line)) {
2708 const char *data(line.c_str());
2709 size_t size = line.size();
2710 lprintf("C:%s\n", data);
2712 if (finish_r(data, size)) {
2713 NSString *finish = finish_r[1];
2714 int index = [Finishes_ indexOfObject:finish];
2715 if (index != INT_MAX && index > Finish_)
2723 - (void) _readStatus:(NSNumber *)fd { _pooled
2724 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2725 std::istream is(&ib);
2728 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2729 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2731 while (std::getline(is, line)) {
2732 const char *data(line.c_str());
2733 size_t size = line.size();
2734 lprintf("S:%s\n", data);
2736 if (conffile_r(data, size)) {
2737 [delegate_ setConfigurationData:conffile_r[1]];
2738 } else if (strncmp(data, "status: ", 8) == 0) {
2739 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2740 [delegate_ setProgressTitle:string];
2741 } else if (pmstatus_r(data, size)) {
2742 std::string type([pmstatus_r[1] UTF8String]);
2743 NSString *id = pmstatus_r[2];
2745 float percent([pmstatus_r[3] floatValue]);
2746 [delegate_ setProgressPercent:(percent / 100)];
2748 NSString *string = pmstatus_r[4];
2750 if (type == "pmerror")
2751 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2752 withObject:[NSArray arrayWithObjects:string, id, nil]
2755 else if (type == "pmstatus") {
2756 [delegate_ setProgressTitle:string];
2757 } else if (type == "pmconffile")
2758 [delegate_ setConfigurationData:string];
2759 else _assert(false);
2760 } else _assert(false);
2766 - (void) _readOutput:(NSNumber *)fd { _pooled
2767 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2768 std::istream is(&ib);
2771 while (std::getline(is, line)) {
2772 lprintf("O:%s\n", line.c_str());
2773 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2783 - (Package *) packageWithName:(NSString *)name {
2784 if (static_cast<pkgDepCache *>(cache_) == NULL)
2786 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2787 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2790 - (Database *) init {
2791 if ((self = [super init]) != nil) {
2798 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2799 apr_pool_create(&pool_, NULL);
2801 sources_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];
2802 packages_ = [[NSMutableArray alloc] init];
2806 _assert(pipe(fds) != -1);
2809 _config->Set("APT::Keep-Fds::", cydiafd_);
2810 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
2813 detachNewThreadSelector:@selector(_readCydia:)
2815 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2818 _assert(pipe(fds) != -1);
2822 detachNewThreadSelector:@selector(_readStatus:)
2824 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2827 _assert(pipe(fds) != -1);
2828 _assert(dup2(fds[0], 0) != -1);
2829 _assert(close(fds[0]) != -1);
2831 input_ = fdopen(fds[1], "a");
2833 _assert(pipe(fds) != -1);
2834 _assert(dup2(fds[1], 1) != -1);
2835 _assert(close(fds[1]) != -1);
2838 detachNewThreadSelector:@selector(_readOutput:)
2840 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2845 - (pkgCacheFile &) cache {
2849 - (pkgDepCache::Policy *) policy {
2853 - (pkgRecords *) records {
2857 - (pkgProblemResolver *) resolver {
2861 - (pkgAcquire &) fetcher {
2865 - (pkgSourceList &) list {
2869 - (NSArray *) packages {
2873 - (NSArray *) sources {
2874 return [sources_ allValues];
2877 - (NSArray *) issues {
2878 if (cache_->BrokenCount() == 0)
2881 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
2883 for (Package *package in packages_) {
2884 if (![package broken])
2886 pkgCache::PkgIterator pkg([package iterator]);
2888 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
2889 [entry addObject:[package name]];
2890 [issues addObject:entry];
2892 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
2896 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
2897 pkgCache::DepIterator start;
2898 pkgCache::DepIterator end;
2899 dep.GlobOr(start, end); // ++dep
2901 if (!cache_->IsImportantDep(end))
2903 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
2906 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
2907 [entry addObject:failure];
2908 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
2910 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
2911 [failure addObject:[package name]];
2913 pkgCache::PkgIterator target(start.TargetPkg());
2914 if (target->ProvidesList != 0)
2915 [failure addObject:@"?"];
2917 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
2919 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
2920 else if (!cache_[target].CandidateVerIter(cache_).end())
2921 [failure addObject:@"-"];
2922 else if (target->ProvidesList == 0)
2923 [failure addObject:@"!"];
2925 [failure addObject:@"%"];
2929 if (start.TargetVer() != 0)
2930 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
2941 - (void) reloadData { _pooled
2942 @synchronized (self) {
2964 apr_pool_clear(pool_);
2965 NSRecycleZone(zone_);
2967 int chk(creat("/tmp/cydia.chk", 0644));
2972 if (!cache_.Open(progress_, true)) {
2974 if (!_error->PopMessage(error))
2977 lprintf("cache_.Open():[%s]\n", error.c_str());
2979 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
2980 [delegate_ repairWithSelector:@selector(configure)];
2981 else if (error == "The package lists or status file could not be parsed or opened.")
2982 [delegate_ repairWithSelector:@selector(update)];
2983 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
2984 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
2985 // else if (error == "The list of sources could not be read.")
2986 else _assert(false);
2992 unlink("/tmp/cydia.chk");
2994 now_ = [[NSDate date] retain];
2996 policy_ = new pkgDepCache::Policy();
2997 records_ = new pkgRecords(cache_);
2998 resolver_ = new pkgProblemResolver(cache_);
2999 fetcher_ = new pkgAcquire(&status_);
3002 list_ = new pkgSourceList();
3003 _assert(list_->ReadMainList());
3005 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3006 _assert(pkgApplyStatus(cache_));
3008 if (cache_->BrokenCount() != 0) {
3009 _assert(pkgFixBroken(cache_));
3010 _assert(cache_->BrokenCount() == 0);
3011 _assert(pkgMinimizeUpgrade(cache_));
3016 std::string lists(_config->FindDir("Dir::State::lists"));
3018 [sources_ removeAllObjects];
3019 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3020 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3021 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3022 if (debPackagesIndex *packages = dynamic_cast<debPackagesIndex *>(*index))
3024 setObject:[[[Source alloc] initWithMetaIndex:*source] autorelease]
3025 forKey:[NSString stringWithFormat:@"%s%s",
3027 URItoFileName(packages->IndexURI("Packages")).c_str()
3035 /*std::vector<Package *> packages;
3036 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3037 [packages_ release];
3040 [packages_ removeAllObjects];
3044 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3045 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3046 //packages.push_back(package);
3047 [packages_ addObject:package];
3051 /*if (packages.empty())
3052 packages_ = [[NSArray alloc] init];
3054 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3057 [packages_ radixSortUsingSelector:@selector(compareByPrefix) withObject:NULL];
3065 /*if (!packages.empty())
3066 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3067 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3069 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3071 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3077 - (void) configure {
3078 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3079 system([dpkg UTF8String]);
3087 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3088 _assert(!_error->PendingError());
3091 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3094 public pkgArchiveCleaner
3097 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3102 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3104 while (_error->PopMessage(error))
3105 lprintf("ArchiveCleaner: %s\n", error.c_str());
3110 pkgRecords records(cache_);
3112 lock_ = new FileFd();
3113 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3114 _assert(!_error->PendingError());
3117 // XXX: explain this with an error message
3118 _assert(list.ReadMainList());
3120 manager_ = (_system->CreatePM(cache_));
3121 _assert(manager_->GetArchives(fetcher_, &list, &records));
3122 _assert(!_error->PendingError());
3126 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3128 _assert(list.ReadMainList());
3129 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3130 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3133 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3138 bool failed = false;
3139 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3140 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3143 std::string uri = (*item)->DescURI();
3144 std::string error = (*item)->ErrorText;
3146 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3149 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3150 withObject:[NSArray arrayWithObjects:
3151 [NSString stringWithUTF8String:error.c_str()],
3163 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3165 if (_error->PendingError()) {
3170 if (result == pkgPackageManager::Failed) {
3175 if (result != pkgPackageManager::Completed) {
3180 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3182 _assert(list.ReadMainList());
3183 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3184 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3187 if (![before isEqualToArray:after])
3192 _assert(pkgDistUpgrade(cache_));
3196 [self updateWithStatus:status_];
3199 - (void) updateWithStatus:(Status &)status {
3201 _assert(list.ReadMainList());
3204 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3205 _assert(!_error->PendingError());
3207 pkgAcquire fetcher(&status);
3208 _assert(list.GetIndexes(&fetcher));
3210 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3211 bool failed = false;
3212 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3213 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3214 (*item)->Finished();
3218 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3219 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3220 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3223 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3228 - (void) setDelegate:(id)delegate {
3229 delegate_ = delegate;
3230 status_.setDelegate(delegate);
3231 progress_.setDelegate(delegate);
3234 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3235 if (const char *name = file.FileName())
3236 if (Source *source = [sources_ objectForKey:[NSString stringWithUTF8String:name]])
3244 /* PopUp Windows {{{ */
3245 @interface PopUpView : UIView {
3246 _transient id delegate_;
3247 UITransitionView *transition_;
3252 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3256 @implementation PopUpView
3259 [transition_ setDelegate:nil];
3260 [transition_ release];
3266 [transition_ transition:UITransitionPushFromTop toView:nil];
3269 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3270 if (from != nil && to == nil)
3271 [self removeFromSuperview];
3274 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3275 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3276 delegate_ = delegate;
3278 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3279 [self addSubview:transition_];
3281 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3283 [view addSubview:self];
3285 [transition_ setDelegate:self];
3287 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3288 [transition_ transition:UITransitionNone toView:blank];
3289 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3297 /* Mail Composition {{{ */
3298 @interface MailToView : PopUpView {
3299 MailComposeController *controller_;
3302 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3306 @implementation MailToView
3309 [controller_ release];
3313 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3317 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3318 NSLog(@"did:%@", delivery);
3319 // [UIApp setStatusBarShowsProgress:NO];
3320 if ([controller error]){
3321 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3322 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3323 [mailAlertSheet setBodyText:[controller error]];
3324 [mailAlertSheet popupAlertAnimated:YES];
3328 - (void) showError {
3329 NSLog(@"%@", [controller_ error]);
3330 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3331 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3332 [mailAlertSheet setBodyText:[controller_ error]];
3333 [mailAlertSheet popupAlertAnimated:YES];
3336 - (void) deliverMessage { _pooled
3340 if (![controller_ deliverMessage])
3341 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3344 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3345 if ([controller_ needsDelivery])
3346 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3351 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3352 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3353 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3354 [controller_ setDelegate:self];
3355 [controller_ initializeUI];
3356 [controller_ setupForURL:url];
3358 UIView *view([controller_ view]);
3359 [overlay_ addSubview:view];
3367 /* Confirmation View {{{ */
3368 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3369 if (!iterator.end())
3370 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3371 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3373 pkgCache::PkgIterator package(dep.TargetPkg());
3376 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3383 @protocol ConfirmationViewDelegate
3389 @interface ConfirmationView : BrowserView {
3390 _transient Database *database_;
3391 UIActionSheet *essential_;
3398 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3402 @implementation ConfirmationView
3409 if (essential_ != nil)
3410 [essential_ release];
3416 [book_ popFromSuperviewAnimated:YES];
3419 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3420 NSString *context([sheet context]);
3422 if ([context isEqualToString:@"remove"]) {
3430 [delegate_ confirm];
3437 } else if ([context isEqualToString:@"unable"]) {
3441 [super alertSheet:sheet buttonClicked:button];
3444 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3445 [super webView:sender didClearWindowObject:window forFrame:frame];
3446 [window setValue:changes_ forKey:@"changes"];
3447 [window setValue:issues_ forKey:@"issues"];
3448 [window setValue:sizes_ forKey:@"sizes"];
3451 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3452 if ((self = [super initWithBook:book]) != nil) {
3453 database_ = database;
3455 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3456 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3457 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3458 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3459 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3463 pkgDepCache::Policy *policy([database_ policy]);
3465 pkgCacheFile &cache([database_ cache]);
3466 NSArray *packages = [database_ packages];
3467 for (Package *package in packages) {
3468 pkgCache::PkgIterator iterator = [package iterator];
3469 pkgDepCache::StateCache &state(cache[iterator]);
3471 NSString *name([package name]);
3473 if (state.NewInstall())
3474 [installing addObject:name];
3475 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3476 [reinstalling addObject:name];
3477 else if (state.Upgrade())
3478 [upgrading addObject:name];
3479 else if (state.Downgrade())
3480 [downgrading addObject:name];
3481 else if (state.Delete()) {
3482 if ([package essential])
3484 [removing addObject:name];
3487 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3488 substrate_ |= DepSubstrate(iterator.CurrentVer());
3493 else if (Advanced_ || true) {
3494 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3496 essential_ = [[UIActionSheet alloc]
3497 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3498 buttons:[NSArray arrayWithObjects:
3499 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3500 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3502 defaultButtonIndex:0
3508 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3510 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3512 essential_ = [[UIActionSheet alloc]
3513 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3514 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3515 defaultButtonIndex:0
3520 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3523 changes_ = [[NSArray alloc] initWithObjects:
3531 issues_ = [database_ issues];
3533 issues_ = [issues_ retain];
3535 sizes_ = [[NSArray alloc] initWithObjects:
3536 SizeString([database_ fetcher].FetchNeeded()),
3537 SizeString([database_ fetcher].PartialPresent()),
3538 SizeString([database_ cache]->UsrSize()),
3541 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3545 - (NSString *) backButtonTitle {
3546 return CYLocalize("CONFIRM");
3549 - (NSString *) leftButtonTitle {
3550 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3553 - (id) rightButtonTitle {
3554 return issues_ != nil ? nil : [super rightButtonTitle];
3557 - (id) _rightButtonTitle {
3558 #if AlwaysReload || IgnoreInstall
3559 return [super _rightButtonTitle];
3561 return CYLocalize("CONFIRM");
3565 - (void) _leftButtonClicked {
3570 - (void) _rightButtonClicked {
3572 return [super _rightButtonClicked];
3574 if (essential_ != nil)
3575 [essential_ popupAlertAnimated:YES];
3579 [delegate_ confirm];
3587 /* Progress Data {{{ */
3588 @interface ProgressData : NSObject {
3594 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3601 @implementation ProgressData
3603 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3604 if ((self = [super init]) != nil) {
3605 selector_ = selector;
3625 /* Progress View {{{ */
3626 @interface ProgressView : UIView <
3627 ConfigurationDelegate,
3630 _transient Database *database_;
3632 UIView *background_;
3633 UITransitionView *transition_;
3635 UINavigationBar *navbar_;
3636 UIProgressBar *progress_;
3637 UITextView *output_;
3638 UITextLabel *status_;
3639 UIPushButton *close_;
3642 SHA1SumValue springlist_;
3643 SHA1SumValue notifyconf_;
3644 SHA1SumValue sandplate_;
3647 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3649 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3650 - (void) setContentView:(UIView *)view;
3653 - (void) _retachThread;
3654 - (void) _detachNewThreadData:(ProgressData *)data;
3655 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3661 @protocol ProgressViewDelegate
3662 - (void) progressViewIsComplete:(ProgressView *)sender;
3665 @implementation ProgressView
3668 [transition_ setDelegate:nil];
3669 [navbar_ setDelegate:nil];
3672 if (background_ != nil)
3673 [background_ release];
3674 [transition_ release];
3677 [progress_ release];
3684 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3685 if (bootstrap_ && from == overlay_ && to == view_)
3689 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3690 if ((self = [super initWithFrame:frame]) != nil) {
3691 database_ = database;
3692 delegate_ = delegate;
3694 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3695 [transition_ setDelegate:self];
3697 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3700 [overlay_ setBackgroundColor:[UIColor blackColor]];
3702 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3703 [background_ setBackgroundColor:[UIColor blackColor]];
3704 [self addSubview:background_];
3707 [self addSubview:transition_];
3709 CGSize navsize = [UINavigationBar defaultSize];
3710 CGRect navrect = {{0, 0}, navsize};
3712 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3713 [overlay_ addSubview:navbar_];
3715 [navbar_ setBarStyle:1];
3716 [navbar_ setDelegate:self];
3718 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3719 [navbar_ pushNavigationItem:navitem];
3721 CGRect bounds = [overlay_ bounds];
3722 CGSize prgsize = [UIProgressBar defaultSize];
3725 (bounds.size.width - prgsize.width) / 2,
3726 bounds.size.height - prgsize.height - 20
3729 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3730 [progress_ setStyle:0];
3732 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3734 bounds.size.height - prgsize.height - 50,
3735 bounds.size.width - 20,
3739 [status_ setColor:[UIColor whiteColor]];
3740 [status_ setBackgroundColor:[UIColor clearColor]];
3742 [status_ setCentersHorizontally:YES];
3743 //[status_ setFont:font];
3746 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3748 navrect.size.height + 20,
3749 bounds.size.width - 20,
3750 bounds.size.height - navsize.height - 62 - navrect.size.height
3754 //[output_ setTextFont:@"Courier New"];
3755 [output_ setTextSize:12];
3757 [output_ setTextColor:[UIColor whiteColor]];
3758 [output_ setBackgroundColor:[UIColor clearColor]];
3760 [output_ setMarginTop:0];
3761 [output_ setAllowsRubberBanding:YES];
3762 [output_ setEditable:NO];
3764 [overlay_ addSubview:output_];
3766 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3768 bounds.size.height - prgsize.height - 50,
3769 bounds.size.width - 20,
3773 [close_ setAutosizesToFit:NO];
3774 [close_ setDrawsShadow:YES];
3775 [close_ setStretchBackground:YES];
3776 [close_ setEnabled:YES];
3778 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3779 [close_ setTitleFont:bold];
3781 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3782 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3783 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3787 - (void) setContentView:(UIView *)view {
3788 view_ = [view retain];
3791 - (void) resetView {
3792 [transition_ transition:6 toView:view_];
3795 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3796 NSString *context([sheet context]);
3798 if ([context isEqualToString:@"error"])
3800 else if ([context isEqualToString:@"conffile"]) {
3801 FILE *input = [database_ input];
3805 fprintf(input, "N\n");
3809 fprintf(input, "Y\n");
3820 - (void) closeButtonPushed {
3829 [delegate_ suspendWithAnimation:YES];
3833 system("launchctl stop com.apple.SpringBoard");
3837 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
3846 - (void) _retachThread {
3847 UINavigationItem *item = [navbar_ topItem];
3848 [item setTitle:CYLocalize("COMPLETE")];
3850 [overlay_ addSubview:close_];
3851 [progress_ removeFromSuperview];
3852 [status_ removeFromSuperview];
3854 [delegate_ progressViewIsComplete:self];
3857 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
3858 MMap mmap(file, MMap::ReadOnly);
3860 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3861 if (!(sandplate_ == sha1.Result()))
3866 FileFd file(NotifyConfig_, FileFd::ReadOnly);
3867 MMap mmap(file, MMap::ReadOnly);
3869 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3870 if (!(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 if (!(springlist_ == sha1.Result()))
3884 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
3885 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
3886 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
3887 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
3888 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
3891 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
3893 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
3894 [cache autorelease];
3896 NSFileManager *manager = [NSFileManager defaultManager];
3897 NSError *error = nil;
3899 id system = [cache objectForKey:@"System"];
3904 if (stat(Cache_, &info) == -1)
3907 [system removeAllObjects];
3909 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
3910 for (NSString *app in apps)
3911 if ([app hasSuffix:@".app"]) {
3912 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
3913 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
3914 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
3916 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
3917 [info setObject:path forKey:@"Path"];
3918 [info setObject:@"System" forKey:@"ApplicationType"];
3919 [system addInfoDictionary:info];
3925 [cache writeToFile:@Cache_ atomically:YES];
3927 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
3929 if (chmod(Cache_, info.st_mode) == -1)
3933 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
3936 notify_post("com.apple.mobile.application_installed");
3938 [delegate_ setStatusBarShowsProgress:NO];
3941 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
3942 [[data target] performSelector:[data selector] withObject:[data object]];
3945 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
3948 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
3949 UINavigationItem *item = [navbar_ topItem];
3950 [item setTitle:title];
3952 [status_ setText:nil];
3953 [output_ setText:@""];
3954 [progress_ setProgress:0];
3956 [close_ removeFromSuperview];
3957 [overlay_ addSubview:progress_];
3958 [overlay_ addSubview:status_];
3960 [delegate_ setStatusBarShowsProgress:YES];
3964 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
3965 MMap mmap(file, MMap::ReadOnly);
3967 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3968 sandplate_ = sha1.Result();
3972 FileFd file(NotifyConfig_, FileFd::ReadOnly);
3973 MMap mmap(file, MMap::ReadOnly);
3975 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3976 notifyconf_ = sha1.Result();
3980 FileFd file(SpringBoard_, FileFd::ReadOnly);
3981 MMap mmap(file, MMap::ReadOnly);
3983 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3984 springlist_ = sha1.Result();
3987 [transition_ transition:6 toView:overlay_];
3990 detachNewThreadSelector:@selector(_detachNewThreadData:)
3992 withObject:[[ProgressData alloc]
3993 initWithSelector:selector
4000 - (void) repairWithSelector:(SEL)selector {
4002 detachNewThreadSelector:selector
4005 title:CYLocalize("REPAIRING")
4009 - (void) setConfigurationData:(NSString *)data {
4011 performSelectorOnMainThread:@selector(_setConfigurationData:)
4017 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4018 Package *package = id == nil ? nil : [database_ packageWithName:id];
4020 UIActionSheet *sheet = [[[UIActionSheet alloc]
4021 initWithTitle:(package == nil ? id : [package name])
4022 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4023 defaultButtonIndex:0
4028 [sheet setBodyText:error];
4029 [sheet popupAlertAnimated:YES];
4032 - (void) setProgressTitle:(NSString *)title {
4034 performSelectorOnMainThread:@selector(_setProgressTitle:)
4040 - (void) setProgressPercent:(float)percent {
4042 performSelectorOnMainThread:@selector(_setProgressPercent:)
4043 withObject:[NSNumber numberWithFloat:percent]
4048 - (void) startProgress {
4051 - (void) addProgressOutput:(NSString *)output {
4053 performSelectorOnMainThread:@selector(_addProgressOutput:)
4059 - (bool) isCancelling:(size_t)received {
4063 - (void) _setConfigurationData:(NSString *)data {
4064 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4066 _assert(conffile_r(data));
4068 NSString *ofile = conffile_r[1];
4069 //NSString *nfile = conffile_r[2];
4071 UIActionSheet *sheet = [[[UIActionSheet alloc]
4072 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
4073 buttons:[NSArray arrayWithObjects:
4074 CYLocalize("KEEP_OLD_COPY"),
4075 CYLocalize("ACCEPT_NEW_COPY"),
4076 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
4078 defaultButtonIndex:0
4083 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4084 [sheet popupAlertAnimated:YES];
4087 - (void) _setProgressTitle:(NSString *)title {
4088 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4089 for (size_t i(0), e([words count]); i != e; ++i) {
4090 NSString *word([words objectAtIndex:i]);
4091 if (Package *package = [database_ packageWithName:word])
4092 [words replaceObjectAtIndex:i withObject:[package name]];
4095 [status_ setText:[words componentsJoinedByString:@" "]];
4098 - (void) _setProgressPercent:(NSNumber *)percent {
4099 [progress_ setProgress:[percent floatValue]];
4102 - (void) _addProgressOutput:(NSString *)output {
4103 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4104 CGSize size = [output_ contentSize];
4105 CGRect rect = {{0, size.height}, {size.width, 0}};
4106 [output_ scrollRectToVisible:rect animated:YES];
4109 - (BOOL) isRunning {
4116 /* Package Cell {{{ */
4117 @interface PackageCell : UITableCell {
4120 NSString *description_;
4127 UITextLabel *status_;
4131 - (PackageCell *) init;
4132 - (void) setPackage:(Package *)package;
4134 + (int) heightForPackage:(Package *)package;
4138 @implementation PackageCell
4140 - (void) clearPackage {
4151 if (description_ != nil) {
4152 [description_ release];
4156 if (source_ != nil) {
4161 if (badge_ != nil) {
4171 [self clearPackage];
4178 - (PackageCell *) init {
4179 if ((self = [super init]) != nil) {
4181 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4182 [status_ setBackgroundColor:[UIColor clearColor]];
4183 [status_ setFont:small];
4188 - (void) setPackage:(Package *)package {
4189 [self clearPackage];
4191 Source *source = [package source];
4193 icon_ = [[package icon] retain];
4194 name_ = [[package name] retain];
4195 description_ = [[package tagline] retain];
4196 commercial_ = [package isCommercial];
4198 package_ = [package retain];
4200 NSString *label = nil;
4201 bool trusted = false;
4203 if (source != nil) {
4204 label = [source label];
4205 trusted = [source trusted];
4206 } else if ([[package id] isEqualToString:@"firmware"])
4207 label = CYLocalize("APPLE");
4209 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4211 NSString *from(label);
4213 NSString *section = [package simpleSection];
4214 if (section != nil && ![section isEqualToString:label]) {
4215 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4216 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4219 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4220 source_ = [from retain];
4222 if (NSString *purpose = [package primaryPurpose])
4223 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4224 badge_ = [badge_ retain];
4227 if (NSString *mode = [package mode]) {
4228 [badge_ setImage:[UIImage applicationImageNamed:
4229 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4232 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4233 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4234 } else if ([package half]) {
4235 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4236 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4237 [status_ setColor:[UIColor redColor]];
4239 [badge_ setImage:nil];
4240 [status_ setText:nil];
4247 - (void) drawRect:(CGRect)rect {
4251 if (NSString *mode = [package_ mode]) {
4252 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4253 color = remove ? RemovingColor_ : InstallingColor_;
4255 color = [UIColor whiteColor];
4257 [self setBackgroundColor:color];
4261 [super drawRect:rect];
4264 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4266 CGContextRef context(UIGraphicsGetCurrentContext());
4267 [[self backgroundColor] set];
4269 back.size.height -= 1;
4270 CGContextFillRect(context, back);
4273 [super drawBackgroundInRect:rect withFade:fade];
4276 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4279 rect.size = [icon_ size];
4281 rect.size.width /= 2;
4282 rect.size.height /= 2;
4284 rect.origin.x = 25 - rect.size.width / 2;
4285 rect.origin.y = 25 - rect.size.height / 2;
4287 [icon_ drawInRect:rect];
4290 if (badge_ != nil) {
4291 CGSize size = [badge_ size];
4293 [badge_ drawAtPoint:CGPointMake(
4294 36 - size.width / 2,
4295 36 - size.height / 2
4303 UISetColor(commercial_ ? Purple_ : Black_);
4304 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4305 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4308 UISetColor(commercial_ ? Purplish_ : Gray_);
4309 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4311 [super drawContentInRect:rect selected:selected];
4314 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4316 [super setSelected:selected withFade:fade];
4319 + (int) heightForPackage:(Package *)package {
4320 NSString *tagline([package tagline]);
4321 int height = tagline == nil || [tagline length] == 0 ? -17 : 0;
4323 if ([package hasMode] || [package half])
4332 /* Section Cell {{{ */
4333 @interface SectionCell : UISimpleTableCell {
4338 _UISwitchSlider *switch_;
4343 - (void) setSection:(Section *)section editing:(BOOL)editing;
4347 @implementation SectionCell
4349 - (void) clearSection {
4350 if (section_ != nil) {
4360 if (count_ != nil) {
4367 [self clearSection];
4374 if ((self = [super init]) != nil) {
4375 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4377 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4378 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4382 - (void) onSwitch:(id)sender {
4383 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4384 if (metadata == nil) {
4385 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4386 [Sections_ setObject:metadata forKey:section_];
4390 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4393 - (void) setSection:(Section *)section editing:(BOOL)editing {
4394 if (editing != editing_) {
4396 [switch_ removeFromSuperview];
4398 [self addSubview:switch_];
4402 [self clearSection];
4404 if (section == nil) {
4405 name_ = [CYLocalize("ALL_PACKAGES") retain];
4408 section_ = [section localized];
4409 if (section_ != nil)
4410 section_ = [section_ retain];
4411 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4412 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4415 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4419 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4420 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4427 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4429 CGSize size = [count_ sizeWithFont:Font14_];
4433 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4435 [super drawContentInRect:rect selected:selected];
4441 /* File Table {{{ */
4442 @interface FileTable : RVPage {
4443 _transient Database *database_;
4446 NSMutableArray *files_;
4450 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4451 - (void) setPackage:(Package *)package;
4455 @implementation FileTable
4458 if (package_ != nil)
4467 - (int) numberOfRowsInTable:(UITable *)table {
4468 return files_ == nil ? 0 : [files_ count];
4471 - (float) table:(UITable *)table heightForRow:(int)row {
4475 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4476 if (reusing == nil) {
4477 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4478 UIFont *font = [UIFont systemFontOfSize:16];
4479 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4481 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4485 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4489 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4490 if ((self = [super initWithBook:book]) != nil) {
4491 database_ = database;
4493 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4495 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4496 [self addSubview:list_];
4498 UITableColumn *column = [[[UITableColumn alloc]
4499 initWithTitle:CYLocalize("NAME")
4501 width:[self frame].size.width
4504 [list_ setDataSource:self];
4505 [list_ setSeparatorStyle:1];
4506 [list_ addTableColumn:column];
4507 [list_ setDelegate:self];
4508 [list_ setReusesTableCells:YES];
4512 - (void) setPackage:(Package *)package {
4513 if (package_ != nil) {
4514 [package_ autorelease];
4523 [files_ removeAllObjects];
4525 if (package != nil) {
4526 package_ = [package retain];
4527 name_ = [[package id] retain];
4529 if (NSArray *files = [package files])
4530 [files_ addObjectsFromArray:files];
4532 if ([files_ count] != 0) {
4533 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4534 [files_ removeObjectAtIndex:0];
4535 [files_ sortUsingSelector:@selector(compareByPath:)];
4537 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4538 [stack addObject:@"/"];
4540 for (int i(0), e([files_ count]); i != e; ++i) {
4541 NSString *file = [files_ objectAtIndex:i];
4542 while (![file hasPrefix:[stack lastObject]])
4543 [stack removeLastObject];
4544 NSString *directory = [stack lastObject];
4545 [stack addObject:[file stringByAppendingString:@"/"]];
4546 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4547 ([stack count] - 2) * 3, "",
4548 [file substringFromIndex:[directory length]]
4557 - (void) resetViewAnimated:(BOOL)animated {
4558 [list_ resetViewAnimated:animated];
4561 - (void) reloadData {
4562 [self setPackage:[database_ packageWithName:name_]];
4563 [self reloadButtons];
4566 - (NSString *) title {
4567 return CYLocalize("INSTALLED_FILES");
4570 - (NSString *) backButtonTitle {
4571 return CYLocalize("FILES");
4576 /* Package View {{{ */
4577 @interface PackageView : BrowserView {
4578 _transient Database *database_;
4582 NSMutableArray *buttons_;
4585 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4586 - (void) setPackage:(Package *)package;
4590 @implementation PackageView
4593 if (package_ != nil)
4602 if ([self retainCount] == 1)
4603 [delegate_ setPackageView:self];
4607 /* XXX: this is not safe at all... localization of /fail/ */
4608 - (void) _clickButtonWithName:(NSString *)name {
4609 if ([name isEqualToString:CYLocalize("CLEAR")])
4610 [delegate_ clearPackage:package_];
4611 else if ([name isEqualToString:CYLocalize("INSTALL")])
4612 [delegate_ installPackage:package_];
4613 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4614 [delegate_ installPackage:package_];
4615 else if ([name isEqualToString:CYLocalize("REMOVE")])
4616 [delegate_ removePackage:package_];
4617 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4618 [delegate_ installPackage:package_];
4619 else _assert(false);
4622 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4623 NSString *context([sheet context]);
4625 if ([context isEqualToString:@"modify"]) {
4626 int count = [buttons_ count];
4627 _assert(count != 0);
4628 _assert(button <= count + 1);
4630 if (count != button - 1)
4631 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4635 [super alertSheet:sheet buttonClicked:button];
4638 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4639 return [super webView:sender didFinishLoadForFrame:frame];
4642 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4643 [super webView:sender didClearWindowObject:window forFrame:frame];
4644 [window setValue:package_ forKey:@"package"];
4647 - (bool) _allowJavaScriptPanel {
4652 - (void) __rightButtonClicked {
4653 int count = [buttons_ count];
4654 _assert(count != 0);
4657 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4659 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4660 [buttons addObjectsFromArray:buttons_];
4661 [buttons addObject:CYLocalize("CANCEL")];
4663 [delegate_ slideUp:[[[UIActionSheet alloc]
4666 defaultButtonIndex:([buttons count] - 1)
4673 - (void) _rightButtonClicked {
4675 [super _rightButtonClicked];
4677 [self __rightButtonClicked];
4681 - (id) _rightButtonTitle {
4682 int count = [buttons_ count];
4683 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4686 - (NSString *) backButtonTitle {
4690 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4691 if ((self = [super initWithBook:book]) != nil) {
4692 database_ = database;
4693 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4694 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4698 - (void) setPackage:(Package *)package {
4699 if (package_ != nil) {
4700 [package_ autorelease];
4709 [buttons_ removeAllObjects];
4711 if (package != nil) {
4712 package_ = [package retain];
4713 name_ = [[package id] retain];
4714 commercial_ = [package isCommercial];
4716 if ([package_ mode] != nil)
4717 [buttons_ addObject:CYLocalize("CLEAR")];
4718 if ([package_ source] == nil);
4719 else if ([package_ upgradableAndEssential:NO])
4720 [buttons_ addObject:CYLocalize("UPGRADE")];
4721 else if ([package_ installed] == nil)
4722 [buttons_ addObject:CYLocalize("INSTALL")];
4724 [buttons_ addObject:CYLocalize("REINSTALL")];
4725 if ([package_ installed] != nil)
4726 [buttons_ addObject:CYLocalize("REMOVE")];
4728 if (special_ != NULL) {
4729 CGRect frame([webview_ frame]);
4730 frame.size.width = 320;
4731 frame.size.height = 0;
4732 [webview_ setFrame:frame];
4734 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4737 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4739 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4741 [self setFinishHook:nil];
4742 [self setPopupHook:nil];
4745 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
4746 [super callFunction:special_];
4750 [self reloadButtons];
4753 - (bool) isLoading {
4754 return commercial_ ? [super isLoading] : false;
4757 - (void) reloadData {
4758 [self setPackage:[database_ packageWithName:name_]];
4763 /* Package Table {{{ */
4764 @interface PackageTable : RVPage {
4765 _transient Database *database_;
4767 NSMutableArray *packages_;
4768 NSMutableArray *sections_;
4769 UISectionList *list_;
4772 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
4774 - (void) setDelegate:(id)delegate;
4776 - (void) reloadData;
4777 - (void) resetCursor;
4779 - (UISectionList *) list;
4781 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4785 @implementation PackageTable
4788 [list_ setDataSource:nil];
4791 [packages_ release];
4792 [sections_ release];
4797 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4798 return [sections_ count];
4801 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4802 return [[sections_ objectAtIndex:section] name];
4805 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4806 return [[sections_ objectAtIndex:section] row];
4809 - (int) numberOfRowsInTable:(UITable *)table {
4810 return [packages_ count];
4813 - (float) table:(UITable *)table heightForRow:(int)row {
4814 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
4817 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4819 reusing = [[[PackageCell alloc] init] autorelease];
4820 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
4824 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
4828 - (void) tableRowSelected:(NSNotification *)notification {
4829 int row = [[notification object] selectedRow];
4833 Package *package = [packages_ objectAtIndex:row];
4834 package = [database_ packageWithName:[package id]];
4835 PackageView *view([delegate_ packageView]);
4836 [view setPackage:package];
4837 [view setDelegate:delegate_];
4838 [book_ pushPage:view];
4841 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
4842 if ((self = [super initWithBook:book]) != nil) {
4843 database_ = database;
4844 title_ = [title retain];
4846 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
4847 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
4849 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
4850 [list_ setDataSource:self];
4852 UITableColumn *column = [[[UITableColumn alloc]
4853 initWithTitle:CYLocalize("NAME")
4855 width:[self frame].size.width
4858 UITable *table = [list_ table];
4859 [table setSeparatorStyle:1];
4860 [table addTableColumn:column];
4861 [table setDelegate:self];
4862 [table setReusesTableCells:YES];
4864 [self addSubview:list_];
4866 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4867 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4871 - (void) setDelegate:(id)delegate {
4872 delegate_ = delegate;
4875 - (bool) hasPackage:(Package *)package {
4879 - (void) reloadData {
4880 NSArray *packages = [database_ packages];
4882 [packages_ removeAllObjects];
4883 [sections_ removeAllObjects];
4885 _profile(PackageTable$reloadData$Filter)
4886 for (Package *package in packages)
4887 if ([self hasPackage:package])
4888 [packages_ addObject:package];
4891 Section *section = nil;
4893 _profile(PackageTable$reloadData$Section)
4894 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
4898 _profile(PackageTable$reloadData$Section$Package)
4899 package = [packages_ objectAtIndex:offset];
4900 index = [package index];
4903 if (section == nil || [section index] != index) {
4904 _profile(PackageTable$reloadData$Section$Allocate)
4905 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
4908 _profile(PackageTable$reloadData$Section$Add)
4909 [sections_ addObject:section];
4913 [section addToCount];
4917 _profile(PackageTable$reloadData$List)
4922 - (NSString *) title {
4926 - (void) resetViewAnimated:(BOOL)animated {
4927 [list_ resetViewAnimated:animated];
4930 - (void) resetCursor {
4931 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
4934 - (UISectionList *) list {
4938 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
4939 [list_ setShouldHideHeaderInShortLists:hide];
4944 /* Filtered Package Table {{{ */
4945 @interface FilteredPackageTable : PackageTable {
4951 - (void) setObject:(id)object;
4953 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
4957 @implementation FilteredPackageTable
4965 - (void) setObject:(id)object {
4971 object_ = [object retain];
4974 - (bool) hasPackage:(Package *)package {
4975 _profile(FilteredPackageTable$hasPackage)
4976 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
4980 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
4981 if ((self = [super initWithBook:book database:database title:title]) != nil) {
4983 object_ = object == nil ? nil : [object retain];
4985 /* XXX: this is an unsafe optimization of doomy hell */
4986 Method method = class_getInstanceMethod([Package class], filter);
4987 imp_ = method_getImplementation(method);
4988 _assert(imp_ != NULL);
4997 /* Add Source View {{{ */
4998 @interface AddSourceView : RVPage {
4999 _transient Database *database_;
5002 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5006 @implementation AddSourceView
5008 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5009 if ((self = [super initWithBook:book]) != nil) {
5010 database_ = database;
5016 /* Source Cell {{{ */
5017 @interface SourceCell : UITableCell {
5020 NSString *description_;
5026 - (SourceCell *) initWithSource:(Source *)source;
5030 @implementation SourceCell
5035 [description_ release];
5040 - (SourceCell *) initWithSource:(Source *)source {
5041 if ((self = [super init]) != nil) {
5043 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5045 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5046 icon_ = [icon_ retain];
5048 origin_ = [[source name] retain];
5049 label_ = [[source uri] retain];
5050 description_ = [[source description] retain];
5054 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5056 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5063 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5067 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5071 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5073 [super drawContentInRect:rect selected:selected];
5078 /* Source Table {{{ */
5079 @interface SourceTable : RVPage {
5080 _transient Database *database_;
5081 UISectionList *list_;
5082 NSMutableArray *sources_;
5083 UIActionSheet *alert_;
5087 UIProgressHUD *hud_;
5090 //NSURLConnection *installer_;
5091 NSURLConnection *trivial_bz2_;
5092 NSURLConnection *trivial_gz_;
5093 //NSURLConnection *automatic_;
5098 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5102 @implementation SourceTable
5104 - (void) _deallocConnection:(NSURLConnection *)connection {
5105 if (connection != nil) {
5106 [connection cancel];
5107 //[connection setDelegate:nil];
5108 [connection release];
5113 [[list_ table] setDelegate:nil];
5114 [list_ setDataSource:nil];
5123 //[self _deallocConnection:installer_];
5124 [self _deallocConnection:trivial_gz_];
5125 [self _deallocConnection:trivial_bz2_];
5126 //[self _deallocConnection:automatic_];
5133 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5134 return offset_ == 0 ? 1 : 2;
5137 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5138 switch (section + (offset_ == 0 ? 1 : 0)) {
5139 case 0: return CYLocalize("ENTERED_BY_USER");
5140 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5148 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5149 switch (section + (offset_ == 0 ? 1 : 0)) {
5151 case 1: return offset_;
5159 - (int) numberOfRowsInTable:(UITable *)table {
5160 return [sources_ count];
5163 - (float) table:(UITable *)table heightForRow:(int)row {
5164 Source *source = [sources_ objectAtIndex:row];
5165 return [source description] == nil ? 56 : 73;
5168 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5169 Source *source = [sources_ objectAtIndex:row];
5170 // XXX: weird warning, stupid selectors ;P
5171 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5174 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5178 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5182 - (void) tableRowSelected:(NSNotification*)notification {
5183 UITable *table([list_ table]);
5184 int row([table selectedRow]);
5188 Source *source = [sources_ objectAtIndex:row];
5190 PackageTable *packages = [[[FilteredPackageTable alloc]
5193 title:[source label]
5194 filter:@selector(isVisibleInSource:)
5198 [packages setDelegate:delegate_];
5200 [book_ pushPage:packages];
5203 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5204 Source *source = [sources_ objectAtIndex:row];
5205 return [source record] != nil;
5208 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5209 [[list_ table] setDeleteConfirmationRow:row];
5212 - (void) table:(UITable *)table deleteRow:(int)row {
5213 Source *source = [sources_ objectAtIndex:row];
5214 [Sources_ removeObjectForKey:[source key]];
5215 [delegate_ syncData];
5219 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5222 @"./", @"Distribution",
5223 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5225 [delegate_ syncData];
5228 - (NSString *) getWarning {
5229 NSString *href(href_);
5230 NSRange colon([href rangeOfString:@"://"]);
5231 if (colon.location != NSNotFound)
5232 href = [href substringFromIndex:(colon.location + 3)];
5233 href = [href stringByAddingPercentEscapes];
5234 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5235 href = [href stringByCachingURLWithCurrentCDN];
5237 NSURL *url([NSURL URLWithString:href]);
5239 NSStringEncoding encoding;
5240 NSError *error(nil);
5242 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5243 return [warning length] == 0 ? nil : warning;
5247 - (void) _endConnection:(NSURLConnection *)connection {
5248 NSURLConnection **field = NULL;
5249 if (connection == trivial_bz2_)
5250 field = &trivial_bz2_;
5251 else if (connection == trivial_gz_)
5252 field = &trivial_gz_;
5253 _assert(field != NULL);
5254 [connection release];
5258 trivial_bz2_ == nil &&
5264 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5267 UIActionSheet *sheet = [[[UIActionSheet alloc]
5268 initWithTitle:CYLocalize("SOURCE_WARNING")
5269 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5270 defaultButtonIndex:0
5275 [sheet setNumberOfRows:1];
5277 [sheet setBodyText:warning];
5278 [sheet popupAlertAnimated:YES];
5281 } else if (error_ != nil) {
5282 UIActionSheet *sheet = [[[UIActionSheet alloc]
5283 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5284 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5285 defaultButtonIndex:0
5290 [sheet setBodyText:[error_ localizedDescription]];
5291 [sheet popupAlertAnimated:YES];
5293 UIActionSheet *sheet = [[[UIActionSheet alloc]
5294 initWithTitle:CYLocalize("NOT_REPOSITORY")
5295 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5296 defaultButtonIndex:0
5301 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5302 [sheet popupAlertAnimated:YES];
5305 [delegate_ setStatusBarShowsProgress:NO];
5306 [delegate_ removeProgressHUD:hud_];
5316 if (error_ != nil) {
5323 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5324 switch ([response statusCode]) {
5330 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5331 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5333 error_ = [error retain];
5334 [self _endConnection:connection];
5337 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5338 [self _endConnection:connection];
5341 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5342 NSMutableURLRequest *request = [NSMutableURLRequest
5343 requestWithURL:[NSURL URLWithString:href]
5344 cachePolicy:NSURLRequestUseProtocolCachePolicy
5345 timeoutInterval:20.0
5348 [request setHTTPMethod:method];
5350 if (Machine_ != NULL)
5351 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5352 if (UniqueID_ != nil)
5353 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5356 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5358 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5361 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5362 NSString *context([sheet context]);
5364 if ([context isEqualToString:@"source"]) {
5367 NSString *href = [[sheet textField] text];
5369 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5371 if (![href hasSuffix:@"/"])
5372 href_ = [href stringByAppendingString:@"/"];
5375 href_ = [href_ retain];
5377 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5378 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5379 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5383 hud_ = [[delegate_ addProgressHUD] retain];
5384 [hud_ setText:CYLocalize("VERIFYING_URL")];
5395 } else if ([context isEqualToString:@"trivial"])
5397 else if ([context isEqualToString:@"urlerror"])
5399 else if ([context isEqualToString:@"warning"]) {
5419 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5420 if ((self = [super initWithBook:book]) != nil) {
5421 database_ = database;
5422 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5424 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5425 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5426 [list_ setShouldHideHeaderInShortLists:NO];
5428 [self addSubview:list_];
5429 [list_ setDataSource:self];
5431 UITableColumn *column = [[UITableColumn alloc]
5432 initWithTitle:CYLocalize("NAME")
5434 width:[self frame].size.width
5437 UITable *table = [list_ table];
5438 [table setSeparatorStyle:1];
5439 [table addTableColumn:column];
5440 [table setDelegate:self];
5444 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5445 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5449 - (void) reloadData {
5451 _assert(list.ReadMainList());
5453 [sources_ removeAllObjects];
5454 [sources_ addObjectsFromArray:[database_ sources]];
5456 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5459 int count = [sources_ count];
5460 for (offset_ = 0; offset_ != count; ++offset_) {
5461 Source *source = [sources_ objectAtIndex:offset_];
5462 if ([source record] == nil)
5469 - (void) resetViewAnimated:(BOOL)animated {
5470 [list_ resetViewAnimated:animated];
5473 - (void) _leftButtonClicked {
5474 /*[book_ pushPage:[[[AddSourceView alloc]
5479 UIActionSheet *sheet = [[[UIActionSheet alloc]
5480 initWithTitle:CYLocalize("ENTER_APT_URL")
5481 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5482 defaultButtonIndex:0
5487 [sheet setNumberOfRows:1];
5489 [sheet addTextFieldWithValue:@"http://" label:@""];
5491 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5492 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5493 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5494 [traits setKeyboardType:UIKeyboardTypeURL];
5495 // XXX: UIReturnKeyDone
5496 [traits setReturnKeyType:UIReturnKeyNext];
5498 [sheet popupAlertAnimated:YES];
5501 - (void) _rightButtonClicked {
5502 UITable *table = [list_ table];
5503 BOOL editing = [table isRowDeletionEnabled];
5504 [table enableRowDeletion:!editing animated:YES];
5505 [book_ reloadButtonsForPage:self];
5508 - (NSString *) title {
5509 return CYLocalize("SOURCES");
5512 - (NSString *) leftButtonTitle {
5513 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5516 - (id) rightButtonTitle {
5517 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5520 - (UINavigationButtonStyle) rightButtonStyle {
5521 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5527 /* Installed View {{{ */
5528 @interface InstalledView : RVPage {
5529 _transient Database *database_;
5530 FilteredPackageTable *packages_;
5534 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5538 @implementation InstalledView
5541 [packages_ release];
5545 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5546 if ((self = [super initWithBook:book]) != nil) {
5547 database_ = database;
5549 packages_ = [[FilteredPackageTable alloc]
5553 filter:@selector(isInstalledAndVisible:)
5554 with:[NSNumber numberWithBool:YES]
5557 [self addSubview:packages_];
5559 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5560 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5564 - (void) resetViewAnimated:(BOOL)animated {
5565 [packages_ resetViewAnimated:animated];
5568 - (void) reloadData {
5569 [packages_ reloadData];
5572 - (void) _rightButtonClicked {
5573 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5574 [packages_ reloadData];
5576 [book_ reloadButtonsForPage:self];
5579 - (NSString *) title {
5580 return CYLocalize("INSTALLED");
5583 - (NSString *) backButtonTitle {
5584 return CYLocalize("PACKAGES");
5587 - (id) rightButtonTitle {
5588 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5591 - (UINavigationButtonStyle) rightButtonStyle {
5592 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5595 - (void) setDelegate:(id)delegate {
5596 [super setDelegate:delegate];
5597 [packages_ setDelegate:delegate];
5604 @interface HomeView : BrowserView {
5609 @implementation HomeView
5611 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5612 NSString *context([sheet context]);
5614 if ([context isEqualToString:@"about"])
5617 [super alertSheet:sheet buttonClicked:button];
5620 - (void) _leftButtonClicked {
5621 UIActionSheet *sheet = [[[UIActionSheet alloc]
5622 initWithTitle:CYLocalize("ABOUT_CYDIA")
5623 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5624 defaultButtonIndex:0
5630 @"Copyright (C) 2008-2009\n"
5631 "Jay Freeman (saurik)\n"
5632 "saurik@saurik.com\n"
5633 "http://www.saurik.com/\n"
5636 "http://www.theokorigroup.com/\n"
5638 "College of Creative Studies,\n"
5639 "University of California,\n"
5641 "http://www.ccs.ucsb.edu/"
5644 [sheet popupAlertAnimated:YES];
5647 - (NSString *) leftButtonTitle {
5648 return CYLocalize("ABOUT");
5653 /* Manage View {{{ */
5654 @interface ManageView : BrowserView {
5659 @implementation ManageView
5661 - (NSString *) title {
5662 return CYLocalize("MANAGE");
5665 - (void) _leftButtonClicked {
5666 [delegate_ askForSettings];
5669 - (NSString *) leftButtonTitle {
5670 return CYLocalize("SETTINGS");
5674 - (id) _rightButtonTitle {
5675 return Queuing_ ? CYLocalize("QUEUE") : nil;
5678 - (UINavigationButtonStyle) rightButtonStyle {
5679 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5682 - (void) _rightButtonClicked {
5687 - (bool) isLoading {
5694 #include <BrowserView.m>
5696 /* Cydia Book {{{ */
5697 @interface CYBook : RVBook <
5700 _transient Database *database_;
5701 UINavigationBar *overlay_;
5702 UINavigationBar *underlay_;
5703 UIProgressIndicator *indicator_;
5704 UITextLabel *prompt_;
5705 UIProgressBar *progress_;
5706 UINavigationButton *cancel_;
5710 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5716 @implementation CYBook
5720 [indicator_ release];
5722 [progress_ release];
5727 - (NSString *) getTitleForPage:(RVPage *)page {
5728 return [super getTitleForPage:page];
5736 [UIView beginAnimations:nil context:NULL];
5738 CGRect ovrframe = [overlay_ frame];
5739 ovrframe.origin.y = 0;
5740 [overlay_ setFrame:ovrframe];
5742 CGRect barframe = [navbar_ frame];
5743 barframe.origin.y += ovrframe.size.height;
5744 [navbar_ setFrame:barframe];
5746 CGRect trnframe = [transition_ frame];
5747 trnframe.origin.y += ovrframe.size.height;
5748 trnframe.size.height -= ovrframe.size.height;
5749 [transition_ setFrame:trnframe];
5751 [UIView endAnimations];
5753 [indicator_ startAnimation];
5754 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5755 [progress_ setProgress:0];
5758 [overlay_ addSubview:cancel_];
5761 detachNewThreadSelector:@selector(_update)
5770 [indicator_ stopAnimation];
5772 [UIView beginAnimations:nil context:NULL];
5774 CGRect ovrframe = [overlay_ frame];
5775 ovrframe.origin.y = -ovrframe.size.height;
5776 [overlay_ setFrame:ovrframe];
5778 CGRect barframe = [navbar_ frame];
5779 barframe.origin.y -= ovrframe.size.height;
5780 [navbar_ setFrame:barframe];
5782 CGRect trnframe = [transition_ frame];
5783 trnframe.origin.y -= ovrframe.size.height;
5784 trnframe.size.height += ovrframe.size.height;
5785 [transition_ setFrame:trnframe];
5787 [UIView commitAnimations];
5789 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5792 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
5793 if ((self = [super initWithFrame:frame]) != nil) {
5794 database_ = database;
5796 CGRect ovrrect = [navbar_ bounds];
5797 ovrrect.size.height = [UINavigationBar defaultSize].height;
5798 ovrrect.origin.y = -ovrrect.size.height;
5800 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5801 [self addSubview:overlay_];
5803 ovrrect.origin.y = frame.size.height;
5804 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5805 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
5806 [self addSubview:underlay_];
5808 [overlay_ setBarStyle:1];
5809 [underlay_ setBarStyle:1];
5811 int barstyle = [overlay_ _barStyle:NO];
5812 bool ugly = barstyle == 0;
5814 UIProgressIndicatorStyle style = ugly ?
5815 UIProgressIndicatorStyleMediumBrown :
5816 UIProgressIndicatorStyleMediumWhite;
5818 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
5819 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
5820 CGRect indrect = {{indoffset, indoffset}, indsize};
5822 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
5823 [indicator_ setStyle:style];
5824 [overlay_ addSubview:indicator_];
5826 CGSize prmsize = {215, indsize.height + 4};
5829 indoffset * 2 + indsize.width,
5833 unsigned(ovrrect.size.height - prmsize.height) / 2
5836 UIFont *font = [UIFont systemFontOfSize:15];
5838 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
5840 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
5841 [prompt_ setBackgroundColor:[UIColor clearColor]];
5842 [prompt_ setFont:font];
5844 [overlay_ addSubview:prompt_];
5846 CGSize prgsize = {75, 100};
5849 ovrrect.size.width - prgsize.width - 10,
5850 (ovrrect.size.height - prgsize.height) / 2
5853 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
5854 [progress_ setStyle:0];
5855 [overlay_ addSubview:progress_];
5857 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
5858 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
5860 CGRect frame = [cancel_ frame];
5861 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
5862 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
5863 [cancel_ setFrame:frame];
5865 [cancel_ setBarStyle:barstyle];
5869 - (void) _onCancel {
5871 [cancel_ removeFromSuperview];
5874 - (void) _update { _pooled
5876 status.setDelegate(self);
5878 [database_ updateWithStatus:status];
5881 performSelectorOnMainThread:@selector(_update_)
5887 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
5888 [prompt_ setText:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), error]];
5891 - (void) setProgressTitle:(NSString *)title {
5893 performSelectorOnMainThread:@selector(_setProgressTitle:)
5899 - (void) setProgressPercent:(float)percent {
5901 performSelectorOnMainThread:@selector(_setProgressPercent:)
5902 withObject:[NSNumber numberWithFloat:percent]
5907 - (void) startProgress {
5910 - (void) addProgressOutput:(NSString *)output {
5912 performSelectorOnMainThread:@selector(_addProgressOutput:)
5918 - (bool) isCancelling:(size_t)received {
5922 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5926 - (void) _setProgressTitle:(NSString *)title {
5927 [prompt_ setText:title];
5930 - (void) _setProgressPercent:(NSNumber *)percent {
5931 [progress_ setProgress:[percent floatValue]];
5934 - (void) _addProgressOutput:(NSString *)output {
5939 /* Cydia:// Protocol {{{ */
5940 @interface CydiaURLProtocol : NSURLProtocol {
5945 @implementation CydiaURLProtocol
5947 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
5948 NSURL *url([request URL]);
5951 NSString *scheme([[url scheme] lowercaseString]);
5952 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
5957 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
5961 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
5962 id<NSURLProtocolClient> client([self client]);
5964 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
5966 NSData *data(UIImagePNGRepresentation(icon));
5968 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
5969 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
5970 [client URLProtocol:self didLoadData:data];
5971 [client URLProtocolDidFinishLoading:self];
5975 - (void) startLoading {
5976 id<NSURLProtocolClient> client([self client]);
5977 NSURLRequest *request([self request]);
5979 NSURL *url([request URL]);
5980 NSString *href([url absoluteString]);
5982 NSString *path([href substringFromIndex:8]);
5983 NSRange slash([path rangeOfString:@"/"]);
5986 if (slash.location == NSNotFound) {
5990 command = [path substringToIndex:slash.location];
5991 path = [path substringFromIndex:(slash.location + 1)];
5994 Database *database([Database sharedInstance]);
5996 if ([command isEqualToString:@"package-icon"]) {
5999 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6000 Package *package([database packageWithName:path]);
6003 UIImage *icon([package icon]);
6004 [self _returnPNGWithImage:icon forRequest:request];
6005 } else if ([command isEqualToString:@"source-icon"]) {
6008 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6009 NSString *source(Simplify(path));
6010 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6012 icon = [UIImage applicationImageNamed:@"unknown.png"];
6013 [self _returnPNGWithImage:icon forRequest:request];
6014 } else if ([command isEqualToString:@"uikit-image"]) {
6017 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6018 UIImage *icon(_UIImageWithName(path));
6019 [self _returnPNGWithImage:icon forRequest:request];
6020 } else if ([command isEqualToString:@"section-icon"]) {
6023 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6024 NSString *section(Simplify(path));
6025 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6027 icon = [UIImage applicationImageNamed:@"unknown.png"];
6028 [self _returnPNGWithImage:icon forRequest:request];
6030 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6034 - (void) stopLoading {
6040 /* Sections View {{{ */
6041 @interface SectionsView : RVPage {
6042 _transient Database *database_;
6043 NSMutableArray *sections_;
6044 NSMutableArray *filtered_;
6045 UITransitionView *transition_;
6051 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6052 - (void) reloadData;
6057 @implementation SectionsView
6060 [list_ setDataSource:nil];
6061 [list_ setDelegate:nil];
6063 [sections_ release];
6064 [filtered_ release];
6065 [transition_ release];
6067 [accessory_ release];
6071 - (int) numberOfRowsInTable:(UITable *)table {
6072 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6075 - (float) table:(UITable *)table heightForRow:(int)row {
6079 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6081 reusing = [[[SectionCell alloc] init] autorelease];
6082 [(SectionCell *)reusing setSection:(editing_ ?
6083 [sections_ objectAtIndex:row] :
6084 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6085 ) editing:editing_];
6089 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6093 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6097 - (void) tableRowSelected:(NSNotification *)notification {
6098 int row = [[notification object] selectedRow];
6109 title = CYLocalize("ALL_PACKAGES");
6111 section = [filtered_ objectAtIndex:(row - 1)];
6112 name = [section name];
6115 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6118 title = CYLocalize("NO_SECTION");
6122 PackageTable *table = [[[FilteredPackageTable alloc]
6126 filter:@selector(isVisiblyUninstalledInSection:)
6130 [table setDelegate:delegate_];
6132 [book_ pushPage:table];
6135 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6136 if ((self = [super initWithBook:book]) != nil) {
6137 database_ = database;
6139 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6140 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6142 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6143 [self addSubview:transition_];
6145 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6146 [transition_ transition:0 toView:list_];
6148 UITableColumn *column = [[[UITableColumn alloc]
6149 initWithTitle:CYLocalize("NAME")
6151 width:[self frame].size.width
6154 [list_ setDataSource:self];
6155 [list_ setSeparatorStyle:1];
6156 [list_ addTableColumn:column];
6157 [list_ setDelegate:self];
6158 [list_ setReusesTableCells:YES];
6162 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6163 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6167 - (void) reloadData {
6168 NSArray *packages = [database_ packages];
6170 [sections_ removeAllObjects];
6171 [filtered_ removeAllObjects];
6174 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6175 SectionMap sections;
6176 sections.resize(64);
6178 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6182 for (Package *package in packages) {
6183 NSString *name([package section]);
6184 NSString *key(name == nil ? @"" : name);
6189 _profile(SectionsView$reloadData$Section)
6190 section = §ions[key];
6191 if (*section == nil) {
6192 _profile(SectionsView$reloadData$Section$Allocate)
6193 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6198 [*section addToCount];
6200 _profile(SectionsView$reloadData$Filter)
6201 if (![package valid] || [package installed] != nil || ![package visible])
6205 [*section addToRow];
6209 _profile(SectionsView$reloadData$Section)
6210 section = [sections objectForKey:key];
6211 if (section == nil) {
6212 _profile(SectionsView$reloadData$Section$Allocate)
6213 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6214 [sections setObject:section forKey:key];
6219 [section addToCount];
6221 _profile(SectionsView$reloadData$Filter)
6222 if (![package valid] || [package installed] != nil || ![package visible])
6232 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6233 [sections_ addObject:i->second];
6235 [sections_ addObjectsFromArray:[sections allValues]];
6238 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6240 for (Section *section in sections_) {
6241 size_t count([section row]);
6245 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6246 [section setCount:count];
6247 [filtered_ addObject:section];
6254 - (void) resetView {
6256 [self _rightButtonClicked];
6259 - (void) resetViewAnimated:(BOOL)animated {
6260 [list_ resetViewAnimated:animated];
6263 - (void) _rightButtonClicked {
6264 if ((editing_ = !editing_))
6267 [delegate_ updateData];
6268 [book_ reloadTitleForPage:self];
6269 [book_ reloadButtonsForPage:self];
6272 - (NSString *) title {
6273 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6276 - (NSString *) backButtonTitle {
6277 return CYLocalize("SECTIONS");
6280 - (id) rightButtonTitle {
6281 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6284 - (UINavigationButtonStyle) rightButtonStyle {
6285 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6288 - (UIView *) accessoryView {
6294 /* Changes View {{{ */
6295 @interface ChangesView : RVPage {
6296 _transient Database *database_;
6297 NSMutableArray *packages_;
6298 NSMutableArray *sections_;
6299 UISectionList *list_;
6303 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6304 - (void) reloadData;
6308 @implementation ChangesView
6311 [[list_ table] setDelegate:nil];
6312 [list_ setDataSource:nil];
6314 [packages_ release];
6315 [sections_ release];
6320 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6321 return [sections_ count];
6324 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6325 return [[sections_ objectAtIndex:section] name];
6328 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6329 return [[sections_ objectAtIndex:section] row];
6332 - (int) numberOfRowsInTable:(UITable *)table {
6333 return [packages_ count];
6336 - (float) table:(UITable *)table heightForRow:(int)row {
6337 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6340 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6342 reusing = [[[PackageCell alloc] init] autorelease];
6343 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6347 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6351 - (void) tableRowSelected:(NSNotification *)notification {
6352 int row = [[notification object] selectedRow];
6355 Package *package = [packages_ objectAtIndex:row];
6356 PackageView *view([delegate_ packageView]);
6357 [view setDelegate:delegate_];
6358 [view setPackage:package];
6359 [book_ pushPage:view];
6362 - (void) _leftButtonClicked {
6363 [(CYBook *)book_ update];
6364 [self reloadButtons];
6367 - (void) _rightButtonClicked {
6368 [delegate_ distUpgrade];
6371 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6372 if ((self = [super initWithBook:book]) != nil) {
6373 database_ = database;
6375 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6376 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6378 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6379 [self addSubview:list_];
6381 [list_ setShouldHideHeaderInShortLists:NO];
6382 [list_ setDataSource:self];
6383 //[list_ setSectionListStyle:1];
6385 UITableColumn *column = [[[UITableColumn alloc]
6386 initWithTitle:CYLocalize("NAME")
6388 width:[self frame].size.width
6391 UITable *table = [list_ table];
6392 [table setSeparatorStyle:1];
6393 [table addTableColumn:column];
6394 [table setDelegate:self];
6395 [table setReusesTableCells:YES];
6399 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6400 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6404 - (void) reloadData {
6405 NSArray *packages = [database_ packages];
6407 [packages_ removeAllObjects];
6408 [sections_ removeAllObjects];
6411 for (Package *package in packages)
6413 [package installed] == nil && [package valid] && [package visible] ||
6414 [package upgradableAndEssential:YES]
6416 [packages_ addObject:package];
6419 [packages_ radixSortUsingFunction:reinterpret_cast<uint32_t (*)(id, void *)>(&PackageChangesRadix) withArgument:NULL];
6422 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6423 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6424 Section *section = nil;
6428 bool unseens = false;
6430 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6432 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6433 Package *package = [packages_ objectAtIndex:offset];
6435 BOOL uae = [package upgradableAndEssential:YES];
6441 _profile(ChangesView$reloadData$Remember)
6442 seen = [package seen];
6445 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6450 name = CYLocalize("UNKNOWN");
6452 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6456 _profile(ChangesView$reloadData$Allocate)
6457 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6458 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6459 [sections_ addObject:section];
6463 [section addToCount];
6464 } else if ([package ignored])
6465 [ignored addToCount];
6468 [upgradable addToCount];
6473 CFRelease(formatter);
6476 Section *last = [sections_ lastObject];
6477 size_t count = [last count];
6478 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6479 [sections_ removeLastObject];
6482 if ([ignored count] != 0)
6483 [sections_ insertObject:ignored atIndex:0];
6485 [sections_ insertObject:upgradable atIndex:0];
6488 [self reloadButtons];
6491 - (void) resetViewAnimated:(BOOL)animated {
6492 [list_ resetViewAnimated:animated];
6495 - (NSString *) leftButtonTitle {
6496 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6499 - (id) rightButtonTitle {
6500 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6503 - (NSString *) title {
6504 return CYLocalize("CHANGES");
6509 /* Search View {{{ */
6510 @protocol SearchViewDelegate
6511 - (void) showKeyboard:(BOOL)show;
6514 @interface SearchView : RVPage {
6516 UISearchField *field_;
6517 UITransitionView *transition_;
6518 FilteredPackageTable *table_;
6519 UIPreferencesTable *advanced_;
6525 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6526 - (void) reloadData;
6530 @implementation SearchView
6533 [field_ setDelegate:nil];
6535 [accessory_ release];
6537 [transition_ release];
6539 [advanced_ release];
6544 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6548 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6550 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6552 default: _assert(false);
6556 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6560 default: _assert(false);
6564 - (void) _showKeyboard:(BOOL)show {
6565 CGSize keysize = [UIKeyboard defaultSize];
6566 CGRect keydown = [book_ pageBounds];
6567 CGRect keyup = keydown;
6568 keyup.size.height -= keysize.height - ButtonBarHeight_;
6570 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6572 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6573 [animation setSignificantRectFields:8];
6576 [animation setStartFrame:keydown];
6577 [animation setEndFrame:keyup];
6579 [animation setStartFrame:keyup];
6580 [animation setEndFrame:keydown];
6583 UIAnimator *animator = [UIAnimator sharedAnimator];
6586 addAnimations:[NSArray arrayWithObjects:animation, nil]
6587 withDuration:(KeyboardTime_ - delay)
6592 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6594 [delegate_ showKeyboard:show];
6597 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6598 [self _showKeyboard:YES];
6601 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6602 [self _showKeyboard:NO];
6605 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6607 NSString *text([field_ text]);
6608 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6614 - (void) textFieldClearButtonPressed:(UITextField *)field {
6618 - (void) keyboardInputShouldDelete:(id)input {
6622 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6623 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6627 [field_ resignFirstResponder];
6632 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6633 if ((self = [super initWithBook:book]) != nil) {
6634 CGRect pageBounds = [book_ pageBounds];
6636 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6637 [self addSubview:transition_];
6639 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6641 [advanced_ setReusesTableCells:YES];
6642 [advanced_ setDataSource:self];
6643 [advanced_ reloadData];
6645 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6646 CGColor dimmed(space_, 0, 0, 0, 0.5);
6647 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6649 table_ = [[FilteredPackageTable alloc]
6653 filter:@selector(isUnfilteredAndSearchedForBy:)
6657 [table_ setShouldHideHeaderInShortLists:NO];
6658 [transition_ transition:0 toView:table_];
6667 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6674 [self bounds].size.width - area.origin.x - 18;
6676 area.size.height = [UISearchField defaultHeight];
6678 field_ = [[UISearchField alloc] initWithFrame:area];
6680 UIFont *font = [UIFont systemFontOfSize:16];
6681 [field_ setFont:font];
6683 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6684 [field_ setDelegate:self];
6686 [field_ setPaddingTop:5];
6688 UITextInputTraits *traits([field_ textInputTraits]);
6689 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6690 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6691 [traits setReturnKeyType:UIReturnKeySearch];
6693 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6695 accessory_ = [[UIView alloc] initWithFrame:accrect];
6696 [accessory_ addSubview:field_];
6698 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6699 [configure setShowPressFeedback:YES];
6700 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6701 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6702 [accessory_ addSubview:configure];*/
6704 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6705 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6711 LKAnimation *animation = [LKTransition animation];
6712 [animation setType:@"oglFlip"];
6713 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6714 [animation setFillMode:@"extended"];
6715 [animation setTransitionFlags:3];
6716 [animation setDuration:10];
6717 [animation setSpeed:0.35];
6718 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6719 [[transition_ _layer] addAnimation:animation forKey:0];
6720 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6721 flipped_ = !flipped_;
6725 - (void) configurePushed {
6726 [field_ resignFirstResponder];
6730 - (void) resetViewAnimated:(BOOL)animated {
6733 [table_ resetViewAnimated:animated];
6736 - (void) _reloadData {
6739 - (void) reloadData {
6742 [table_ setObject:[field_ text]];
6743 _profile(SearchView$reloadData)
6744 [table_ reloadData];
6747 [table_ resetCursor];
6750 - (UIView *) accessoryView {
6754 - (NSString *) title {
6758 - (NSString *) backButtonTitle {
6759 return CYLocalize("SEARCH");
6762 - (void) setDelegate:(id)delegate {
6763 [table_ setDelegate:delegate];
6764 [super setDelegate:delegate];
6770 @interface SettingsView : RVPage {
6771 _transient Database *database_;
6774 UIPreferencesTable *table_;
6775 _UISwitchSlider *subscribedSwitch_;
6776 _UISwitchSlider *ignoredSwitch_;
6777 UIPreferencesControlTableCell *subscribedCell_;
6778 UIPreferencesControlTableCell *ignoredCell_;
6781 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6785 @implementation SettingsView
6788 [table_ setDataSource:nil];
6791 if (package_ != nil)
6794 [subscribedSwitch_ release];
6795 [ignoredSwitch_ release];
6796 [subscribedCell_ release];
6797 [ignoredCell_ release];
6801 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6802 if (package_ == nil)
6808 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6809 if (package_ == nil)
6816 default: _assert(false);
6822 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
6823 if (package_ == nil)
6830 default: _assert(false);
6836 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6837 if (package_ == nil)
6844 default: _assert(false);
6850 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
6851 if (package_ == nil)
6854 _UISwitchSlider *slider([cell control]);
6855 BOOL value([slider value] != 0);
6856 NSMutableDictionary *metadata([package_ metadata]);
6859 if (NSNumber *number = [metadata objectForKey:key])
6860 before = [number boolValue];
6864 if (value != before) {
6865 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
6867 [delegate_ updateData];
6871 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
6872 [self onSomething:cell withKey:@"IsSubscribed"];
6875 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
6876 [self onSomething:cell withKey:@"IsIgnored"];
6879 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
6880 if (package_ == nil)
6884 case 0: switch (row) {
6886 return subscribedCell_;
6888 return ignoredCell_;
6889 default: _assert(false);
6892 case 1: switch (row) {
6894 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
6895 [cell setShowSelection:NO];
6896 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
6900 default: _assert(false);
6903 default: _assert(false);
6909 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
6910 if ((self = [super initWithBook:book])) {
6911 database_ = database;
6912 name_ = [package retain];
6914 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
6915 [self addSubview:table_];
6917 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
6918 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
6920 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
6921 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
6923 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
6924 [subscribedCell_ setShowSelection:NO];
6925 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
6926 [subscribedCell_ setControl:subscribedSwitch_];
6928 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
6929 [ignoredCell_ setShowSelection:NO];
6930 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
6931 [ignoredCell_ setControl:ignoredSwitch_];
6933 [table_ setDataSource:self];
6938 - (void) resetViewAnimated:(BOOL)animated {
6939 [table_ resetViewAnimated:animated];
6942 - (void) reloadData {
6943 if (package_ != nil)
6944 [package_ autorelease];
6945 package_ = [database_ packageWithName:name_];
6946 if (package_ != nil) {
6948 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
6949 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
6952 [table_ reloadData];
6955 - (NSString *) title {
6956 return CYLocalize("SETTINGS");
6961 /* Signature View {{{ */
6962 @interface SignatureView : BrowserView {
6963 _transient Database *database_;
6967 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6971 @implementation SignatureView
6978 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
6980 [super webView:sender didClearWindowObject:window forFrame:frame];
6983 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
6984 if ((self = [super initWithBook:book]) != nil) {
6985 database_ = database;
6986 package_ = [package retain];
6991 - (void) resetViewAnimated:(BOOL)animated {
6994 - (void) reloadData {
6995 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7001 @interface Cydia : UIApplication <
7002 ConfirmationViewDelegate,
7003 ProgressViewDelegate,
7012 UIToolbar *buttonbar_;
7016 NSMutableArray *essential_;
7017 NSMutableArray *broken_;
7019 Database *database_;
7020 ProgressView *progress_;
7024 UIKeyboard *keyboard_;
7025 UIProgressHUD *hud_;
7027 SectionsView *sections_;
7028 ChangesView *changes_;
7029 ManageView *manage_;
7030 SearchView *search_;
7032 PackageView *package_;
7037 @implementation Cydia
7040 if ([broken_ count] != 0) {
7041 int count = [broken_ count];
7043 UIActionSheet *sheet = [[[UIActionSheet alloc]
7044 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
7045 buttons:[NSArray arrayWithObjects:
7046 CYLocalize("FORCIBLY_CLEAR"),
7047 CYLocalize("TEMPORARY_IGNORE"),
7049 defaultButtonIndex:0
7054 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
7055 [sheet popupAlertAnimated:YES];
7056 } else if (!Ignored_ && [essential_ count] != 0) {
7057 int count = [essential_ count];
7059 UIActionSheet *sheet = [[[UIActionSheet alloc]
7060 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
7061 buttons:[NSArray arrayWithObjects:
7062 CYLocalize("UPGRADE_ESSENTIAL"),
7063 CYLocalize("COMPLETE_UPGRADE"),
7064 CYLocalize("TEMPORARY_IGNORE"),
7066 defaultButtonIndex:0
7071 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
7072 [sheet popupAlertAnimated:YES];
7076 - (void) _reloadData {
7079 static bool loaded(false);
7080 UIProgressHUD *hud([self addProgressHUD]);
7081 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7084 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7087 [self removeProgressHUD:hud];
7091 [essential_ removeAllObjects];
7092 [broken_ removeAllObjects];
7094 NSArray *packages = [database_ packages];
7095 for (Package *package in packages) {
7097 [broken_ addObject:package];
7098 if ([package upgradableAndEssential:NO]) {
7099 if ([package essential])
7100 [essential_ addObject:package];
7106 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7107 [buttonbar_ setBadgeValue:badge forButton:3];
7108 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7109 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7110 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7111 [self setApplicationBadge:badge];
7113 [self setApplicationBadgeString:badge];
7115 [buttonbar_ setBadgeValue:nil forButton:3];
7116 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7117 [buttonbar_ setBadgeAnimated:NO forButton:3];
7118 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7119 [self removeApplicationBadge];
7120 else // XXX: maybe use setApplicationBadgeString also?
7121 [self setApplicationIconBadgeNumber:0];
7125 [buttonbar_ setBadgeValue:nil forButton:4];
7129 // XXX: what is this line of code for?
7130 if ([packages count] == 0);
7131 else if (Loaded_ || ManualRefresh) loaded:
7136 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7137 NSTimeInterval interval([update timeIntervalSinceNow]);
7138 if (interval <= 0 && interval > -600)
7146 - (void) _saveConfig {
7149 NSString *error(nil);
7150 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7152 NSError *error(nil);
7153 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7154 NSLog(@"failure to save metadata data: %@", error);
7157 NSLog(@"failure to serialize metadata: %@", error);
7165 - (void) updateData {
7168 /* XXX: this is just stupid */
7169 if (tag_ != 2 && sections_ != nil)
7170 [sections_ reloadData];
7171 if (tag_ != 3 && changes_ != nil)
7172 [changes_ reloadData];
7173 if (tag_ != 5 && search_ != nil)
7174 [search_ reloadData];
7184 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7185 _assert(file != NULL);
7187 NSArray *keys = [Sources_ allKeys];
7189 for (NSString *key in keys) {
7190 NSDictionary *source = [Sources_ objectForKey:key];
7192 fprintf(file, "%s %s %s\n",
7193 [[source objectForKey:@"Type"] UTF8String],
7194 [[source objectForKey:@"URI"] UTF8String],
7195 [[source objectForKey:@"Distribution"] UTF8String]
7204 detachNewThreadSelector:@selector(update_)
7207 title:CYLocalize("UPDATING_SOURCES")
7211 - (void) reloadData {
7212 @synchronized (self) {
7213 if (confirm_ == nil)
7219 pkgProblemResolver *resolver = [database_ resolver];
7221 resolver->InstallProtect();
7222 if (!resolver->Resolve(true))
7226 - (void) popUpBook:(RVBook *)book {
7227 [underlay_ popSubview:book];
7230 - (CGRect) popUpBounds {
7231 return [underlay_ bounds];
7235 [database_ prepare];
7237 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7238 [confirm_ setDelegate:self];
7240 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7241 [page setDelegate:self];
7243 [confirm_ setPage:page];
7244 [self popUpBook:confirm_];
7248 @synchronized (self) {
7253 - (void) clearPackage:(Package *)package {
7254 @synchronized (self) {
7261 - (void) installPackage:(Package *)package {
7262 @synchronized (self) {
7269 - (void) removePackage:(Package *)package {
7270 @synchronized (self) {
7277 - (void) distUpgrade {
7278 @synchronized (self) {
7279 [database_ upgrade];
7285 [self slideUp:[[[UIActionSheet alloc]
7287 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7288 defaultButtonIndex:1
7295 @synchronized (self) {
7298 if (confirm_ != nil) {
7306 [overlay_ removeFromSuperview];
7310 detachNewThreadSelector:@selector(perform)
7313 title:CYLocalize("RUNNING")
7317 - (void) bootstrap_ {
7319 [database_ upgrade];
7320 [database_ prepare];
7321 [database_ perform];
7324 /* XXX: replace and localize */
7325 - (void) bootstrap {
7327 detachNewThreadSelector:@selector(bootstrap_)
7330 title:@"Bootstrap Install"
7334 - (void) progressViewIsComplete:(ProgressView *)progress {
7335 if (confirm_ != nil) {
7336 [underlay_ addSubview:overlay_];
7337 [confirm_ popFromSuperviewAnimated:NO];
7343 - (void) setPage:(RVPage *)page {
7344 [page resetViewAnimated:NO];
7345 [page setDelegate:self];
7346 [book_ setPage:page];
7349 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7350 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7351 [browser loadURL:url];
7355 - (void) _setHomePage {
7356 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7359 - (SectionsView *) sectionsView {
7360 if (sections_ == nil)
7361 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7365 - (void) buttonBarItemTapped:(id)sender {
7366 unsigned tag = [sender tag];
7368 [book_ resetViewAnimated:YES];
7370 } else if (tag_ == 2 && tag != 2)
7371 [[self sectionsView] resetView];
7374 case 1: [self _setHomePage]; break;
7376 case 2: [self setPage:[self sectionsView]]; break;
7377 case 3: [self setPage:changes_]; break;
7378 case 4: [self setPage:manage_]; break;
7379 case 5: [self setPage:search_]; break;
7381 default: _assert(false);
7387 - (void) applicationWillSuspend {
7389 [super applicationWillSuspend];
7392 - (void) askForSettings {
7393 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7395 UIActionSheet *role = [[[UIActionSheet alloc]
7396 initWithTitle:CYLocalize("WHO_ARE_YOU")
7397 buttons:[NSArray arrayWithObjects:
7398 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7399 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7400 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7402 defaultButtonIndex:-1
7407 [role setBodyText:CYLocalize("ROLE_EX")];
7408 [role popupAlertAnimated:YES];
7411 - (void) setPackageView:(PackageView *)view {
7412 if (package_ == nil)
7413 package_ = [view retain];
7416 - (PackageView *) packageView {
7419 if (package_ == nil)
7420 view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7423 view = [package_ autorelease];
7432 [self setStatusBarShowsProgress:NO];
7433 [self removeProgressHUD:hud_];
7438 pid_t pid = ExecFork();
7440 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7441 perror("launchctl stop");
7448 [self askForSettings];
7453 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7455 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7456 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7457 0, 0, screenrect.size.width, screenrect.size.height - 48
7458 ) database:database_];
7460 [book_ setDelegate:self];
7462 [overlay_ addSubview:book_];
7464 NSArray *buttonitems = [NSArray arrayWithObjects:
7465 [NSDictionary dictionaryWithObjectsAndKeys:
7466 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7467 @"home-up.png", kUIButtonBarButtonInfo,
7468 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7469 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7470 self, kUIButtonBarButtonTarget,
7471 @"Cydia", kUIButtonBarButtonTitle,
7472 @"0", kUIButtonBarButtonType,
7475 [NSDictionary dictionaryWithObjectsAndKeys:
7476 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7477 @"install-up.png", kUIButtonBarButtonInfo,
7478 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7479 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7480 self, kUIButtonBarButtonTarget,
7481 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7482 @"0", kUIButtonBarButtonType,
7485 [NSDictionary dictionaryWithObjectsAndKeys:
7486 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7487 @"changes-up.png", kUIButtonBarButtonInfo,
7488 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7489 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7490 self, kUIButtonBarButtonTarget,
7491 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7492 @"0", kUIButtonBarButtonType,
7495 [NSDictionary dictionaryWithObjectsAndKeys:
7496 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7497 @"manage-up.png", kUIButtonBarButtonInfo,
7498 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7499 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7500 self, kUIButtonBarButtonTarget,
7501 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7502 @"0", kUIButtonBarButtonType,
7505 [NSDictionary dictionaryWithObjectsAndKeys:
7506 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7507 @"search-up.png", kUIButtonBarButtonInfo,
7508 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7509 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7510 self, kUIButtonBarButtonTarget,
7511 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7512 @"0", kUIButtonBarButtonType,
7516 buttonbar_ = [[UIToolbar alloc]
7518 withFrame:CGRectMake(
7519 0, screenrect.size.height - ButtonBarHeight_,
7520 screenrect.size.width, ButtonBarHeight_
7522 withItemList:buttonitems
7525 [buttonbar_ setDelegate:self];
7526 [buttonbar_ setBarStyle:1];
7527 [buttonbar_ setButtonBarTrackingMode:2];
7529 int buttons[5] = {1, 2, 3, 4, 5};
7530 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7531 [buttonbar_ showButtonGroup:0 withDuration:0];
7533 for (int i = 0; i != 5; ++i)
7534 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7535 i * 64 + 2, 1, 60, ButtonBarHeight_
7538 [buttonbar_ showSelectionForButton:1];
7539 [overlay_ addSubview:buttonbar_];
7541 [UIKeyboard initImplementationNow];
7542 CGSize keysize = [UIKeyboard defaultSize];
7543 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7544 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7545 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7546 [overlay_ addSubview:keyboard_];
7549 [underlay_ addSubview:overlay_];
7553 [self sectionsView];
7554 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7555 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7557 manage_ = (ManageView *) [[self
7558 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7559 withClass:[ManageView class]
7562 [self setPackageView:[self packageView]];
7569 [self _setHomePage];
7572 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7573 NSString *context([sheet context]);
7575 if ([context isEqualToString:@"missing"])
7577 else if ([context isEqualToString:@"cancel"]) {
7595 @synchronized (self) {
7600 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7604 if (confirm_ != nil) {
7609 } else if ([context isEqualToString:@"fixhalf"]) {
7612 @synchronized (self) {
7613 for (Package *broken in broken_) {
7616 NSString *id = [broken id];
7617 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7618 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7619 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7620 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7629 [broken_ removeAllObjects];
7638 } else if ([context isEqualToString:@"role"]) {
7640 case 1: Role_ = @"User"; break;
7641 case 2: Role_ = @"Hacker"; break;
7642 case 3: Role_ = @"Developer"; break;
7649 bool reset = Settings_ != nil;
7651 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7655 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7665 } else if ([context isEqualToString:@"upgrade"]) {
7668 @synchronized (self) {
7669 for (Package *essential in essential_)
7670 [essential install];
7693 - (void) reorganize { _pooled
7694 system("/usr/libexec/cydia/free.sh");
7695 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7698 - (void) applicationSuspend:(__GSEvent *)event {
7699 if (hud_ == nil && ![progress_ isRunning])
7700 [super applicationSuspend:event];
7703 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7705 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7708 - (void) _setSuspended:(BOOL)value {
7710 [super _setSuspended:value];
7713 - (UIProgressHUD *) addProgressHUD {
7714 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7715 [window_ setUserInteractionEnabled:NO];
7717 [progress_ addSubview:hud];
7721 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7723 [hud removeFromSuperview];
7724 [window_ setUserInteractionEnabled:YES];
7727 - (void) openMailToURL:(NSURL *)url {
7728 // XXX: this makes me sad
7730 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7732 [UIApp openURL:url];// asPanel:YES];
7736 - (void) clearFirstResponder {
7737 if (id responder = [window_ firstResponder])
7738 [responder resignFirstResponder];
7741 - (RVPage *) pageForPackage:(NSString *)name {
7742 if (Package *package = [database_ packageWithName:name]) {
7743 PackageView *view([self packageView]);
7744 [view setPackage:package];
7747 UIActionSheet *sheet = [[[UIActionSheet alloc]
7748 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7749 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
7750 defaultButtonIndex:0
7755 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
7757 [sheet popupAlertAnimated:YES];
7762 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7766 NSString *scheme([[url scheme] lowercaseString]);
7767 if (![scheme isEqualToString:@"cydia"])
7769 NSString *path([url absoluteString]);
7770 if ([path length] < 8)
7772 path = [path substringFromIndex:8];
7773 if (![path hasPrefix:@"/"])
7774 path = [@"/" stringByAppendingString:path];
7776 if ([path isEqualToString:@"/add-source"])
7777 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
7778 else if ([path isEqualToString:@"/storage"])
7779 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
7780 else if ([path isEqualToString:@"/sources"])
7781 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
7782 else if ([path isEqualToString:@"/packages"])
7783 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
7784 else if ([path hasPrefix:@"/url/"])
7785 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
7786 else if ([path hasPrefix:@"/launch/"])
7787 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
7788 else if ([path hasPrefix:@"/package-settings/"])
7789 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
7790 else if ([path hasPrefix:@"/package-signature/"])
7791 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
7792 else if ([path hasPrefix:@"/package/"])
7793 return [self pageForPackage:[path substringFromIndex:9]];
7794 else if ([path hasPrefix:@"/files/"]) {
7795 NSString *name = [path substringFromIndex:7];
7797 if (Package *package = [database_ packageWithName:name]) {
7798 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
7799 [files setPackage:package];
7807 - (void) applicationOpenURL:(NSURL *)url {
7808 [super applicationOpenURL:url];
7810 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
7811 [self setPage:page];
7812 [buttonbar_ showSelectionForButton:tag];
7817 - (void) applicationDidFinishLaunching:(id)unused {
7819 Font12_ = [[UIFont systemFontOfSize:12] retain];
7820 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
7821 Font14_ = [[UIFont systemFontOfSize:14] retain];
7822 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
7823 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
7827 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
7828 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
7830 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
7832 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7833 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
7835 [window_ orderFront:self];
7836 [window_ makeKey:self];
7837 [window_ setHidden:NO];
7839 database_ = [Database sharedInstance];
7840 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
7841 [database_ setDelegate:progress_];
7842 [window_ setContentView:progress_];
7844 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
7845 [progress_ setContentView:underlay_];
7847 [progress_ resetView];
7850 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
7851 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
7852 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
7853 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
7854 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
7855 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
7856 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
7858 [self setIdleTimerDisabled:YES];
7860 hud_ = [[self addProgressHUD] retain];
7861 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
7863 [self setStatusBarShowsProgress:YES];
7866 detachNewThreadSelector:@selector(reorganize)
7874 - (void) showKeyboard:(BOOL)show {
7875 CGSize keysize = [UIKeyboard defaultSize];
7876 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
7877 CGRect keyup = keydown;
7878 keyup.origin.y -= keysize.height;
7880 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
7881 [animation setSignificantRectFields:2];
7884 [animation setStartFrame:keydown];
7885 [animation setEndFrame:keyup];
7886 [keyboard_ activate];
7888 [animation setStartFrame:keyup];
7889 [animation setEndFrame:keydown];
7890 [keyboard_ deactivate];
7893 [[UIAnimator sharedAnimator]
7894 addAnimations:[NSArray arrayWithObjects:animation, nil]
7895 withDuration:KeyboardTime_
7900 - (void) slideUp:(UIActionSheet *)alert {
7902 [alert presentSheetFromButtonBar:buttonbar_];
7904 [alert presentSheetInView:overlay_];
7909 void AddPreferences(NSString *plist) { _pooled
7910 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
7911 _assert(settings != NULL);
7912 NSMutableArray *items = [settings objectForKey:@"items"];
7916 for (NSMutableDictionary *item in items) {
7917 NSString *label = [item objectForKey:@"label"];
7918 if (label != nil && [label isEqualToString:@"Cydia"]) {
7925 for (size_t i(0); i != [items count]; ++i) {
7926 NSDictionary *item([items objectAtIndex:i]);
7927 NSString *label = [item objectForKey:@"label"];
7928 if (label != nil && [label isEqualToString:@"General"]) {
7929 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
7930 @"CydiaSettings", @"bundle",
7931 @"PSLinkCell", @"cell",
7932 [NSNumber numberWithBool:YES], @"hasIcon",
7933 [NSNumber numberWithBool:YES], @"isController",
7935 nil] atIndex:(i + 1)];
7941 _assert([settings writeToFile:plist atomically:YES] == YES);
7946 id Alloc_(id self, SEL selector) {
7947 id object = alloc_(self, selector);
7948 lprintf("[%s]A-%p\n", self->isa->name, object);
7953 id Dealloc_(id self, SEL selector) {
7954 id object = dealloc_(self, selector);
7955 lprintf("[%s]D-%p\n", self->isa->name, object);
7959 Class $WebDefaultUIKitDelegate;
7961 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
7963 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
7964 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
7965 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
7966 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
7969 int main(int argc, char *argv[]) { _pooled
7972 PackageName = reinterpret_cast<CFStringRef (*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(name))));
7974 /* Library Hacks {{{ */
7975 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
7977 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
7978 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
7979 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
7980 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
7981 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
7984 /* Set Locale {{{ */
7985 Locale_ = CFLocaleCopyCurrent();
7986 Languages_ = [NSLocale preferredLanguages];
7987 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
7988 //NSLog(@"%@", [Languages_ description]);
7990 if (Languages_ == nil || [Languages_ count] == 0)
7993 lang = [[Languages_ objectAtIndex:0] UTF8String];
7994 setenv("LANG", lang, true);
7995 //std::setlocale(LC_ALL, lang);
7996 NSLog(@"Setting Language: %s", lang);
7999 // XXX: apr_app_initialize?
8002 /* Parse Arguments {{{ */
8003 bool substrate(false);
8009 for (int argi(1); argi != argc; ++argi)
8010 if (strcmp(argv[argi], "--") == 0) {
8012 argv[argi] = argv[0];
8018 for (int argi(1); argi != arge; ++argi)
8019 if (strcmp(args[argi], "--bootstrap") == 0)
8021 else if (strcmp(args[argi], "--substrate") == 0)
8024 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8029 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8030 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8031 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8032 Sounds_Keyboard_ = [keyboard boolValue];
8035 App_ = [[NSBundle mainBundle] bundlePath];
8036 Home_ = NSHomeDirectory();
8041 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8042 alloc_ = alloc->method_imp;
8043 alloc->method_imp = (IMP) &Alloc_;*/
8045 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8046 dealloc_ = dealloc->method_imp;
8047 dealloc->method_imp = (IMP) &Dealloc_;*/
8052 size = sizeof(maxproc);
8053 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8054 perror("sysctlbyname(\"kern.maxproc\", ?)");
8055 else if (maxproc < 64) {
8057 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8058 perror("sysctlbyname(\"kern.maxproc\", #)");
8061 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8062 char *machine = new char[size];
8063 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8064 perror("sysctlbyname(\"hw.machine\", ?)");
8068 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8070 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8071 Build_ = [system objectForKey:@"ProductBuildVersion"];
8072 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8073 Product_ = [info objectForKey:@"SafariProductVersion"];
8074 Safari_ = [info objectForKey:@"CFBundleVersion"];
8077 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8078 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8080 /* Load Database {{{ */
8082 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8084 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8087 if (Metadata_ == NULL)
8088 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8090 Settings_ = [Metadata_ objectForKey:@"Settings"];
8092 Packages_ = [Metadata_ objectForKey:@"Packages"];
8093 Sections_ = [Metadata_ objectForKey:@"Sections"];
8094 Sources_ = [Metadata_ objectForKey:@"Sources"];
8097 if (Settings_ != nil)
8098 Role_ = [Settings_ objectForKey:@"Role"];
8100 if (Packages_ == nil) {
8101 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8102 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8105 if (Sections_ == nil) {
8106 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8107 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8110 if (Sources_ == nil) {
8111 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8112 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8117 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8120 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8121 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8122 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8123 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8125 if (access("/User", F_OK) != 0) {
8127 system("/usr/libexec/cydia/firmware.sh");
8131 _assert([[NSFileManager defaultManager]
8132 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8133 withIntermediateDirectories:YES
8138 if (access("/tmp/cydia.chk", F_OK) == 0) {
8139 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8140 _assert(errno == ENOENT);
8141 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8142 _assert(errno == ENOENT);
8145 _assert(pkgInitConfig(*_config));
8146 _assert(pkgInitSystem(*_config, _system));
8149 _config->Set("APT::Acquire::Translation", lang);
8150 _config->Set("Acquire::http::Timeout", 15);
8151 _config->Set("Acquire::http::MaxParallel", 4);
8153 /* Color Choices {{{ */
8154 space_ = CGColorSpaceCreateDeviceRGB();
8156 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8157 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8158 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8159 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8160 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8161 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8162 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8163 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8164 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8165 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8166 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8167 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8168 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8169 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8170 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8173 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8174 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8177 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8179 /* UIKit Configuration {{{ */
8180 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8181 if ($GSFontSetUseLegacyFontMetrics != NULL)
8182 $GSFontSetUseLegacyFontMetrics(YES);
8184 UIKeyboardDisableAutomaticAppearance();
8188 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8190 CGColorSpaceRelease(space_);