1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008 Jay Freeman (saurik)
6 * Redistribution and use in source and binary
7 * forms, with or without modification, are permitted
8 * provided that the following conditions are met:
10 * 1. Redistributions of source code must retain the
11 * above copyright notice, this list of conditions
12 * and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the
14 * above copyright notice, this list of conditions
15 * and the following disclaimer in the documentation
16 * and/or other materials provided with the
18 * 3. The name of the author may not be used to endorse
19 * or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
23 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
24 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
28 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
33 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 // XXX: wtf/FastMalloc.h... wtf?
39 #define USE_SYSTEM_MALLOC 1
41 /* #include Directives {{{ */
42 #import "UICaboodle.h"
44 #include <objc/message.h>
45 #include <objc/objc.h>
46 #include <objc/runtime.h>
48 #include <CoreGraphics/CoreGraphics.h>
49 #include <GraphicsServices/GraphicsServices.h>
50 #include <Foundation/Foundation.h>
52 #import <QuartzCore/CALayer.h>
53 #import <UIKit/UIKit.h>
55 #include <WebCore/WebCoreThread.h>
56 #import <WebKit/WebDefaultUIKitDelegate.h>
62 #include <ext/stdio_filebuf.h>
64 #include <apt-pkg/acquire.h>
65 #include <apt-pkg/acquire-item.h>
66 #include <apt-pkg/algorithms.h>
67 #include <apt-pkg/cachefile.h>
68 #include <apt-pkg/clean.h>
69 #include <apt-pkg/configuration.h>
70 #include <apt-pkg/debindexfile.h>
71 #include <apt-pkg/debmetaindex.h>
72 #include <apt-pkg/error.h>
73 #include <apt-pkg/init.h>
74 #include <apt-pkg/mmap.h>
75 #include <apt-pkg/pkgrecords.h>
76 #include <apt-pkg/sha1.h>
77 #include <apt-pkg/sourcelist.h>
78 #include <apt-pkg/sptr.h>
79 #include <apt-pkg/strutl.h>
81 #include <apr-1/apr_pools.h>
83 #include <sys/types.h>
85 #include <sys/sysctl.h>
86 #include <sys/param.h>
87 #include <sys/mount.h>
93 #include <mach-o/nlist.h>
103 #include <ext/hash_map>
105 #import "BrowserView.h"
106 #import "ResetView.h"
108 #import "substrate.h"
111 //#define _finline __attribute__((force_inline))
112 #define _finline inline
117 #define _limit(count) do { \
118 static size_t _count(0); \
119 if (++_count == count) \
124 #define _timestamp ({ \
126 gettimeofday(&tv, NULL); \
127 tv.tv_sec * 1000000 + tv.tv_usec; \
130 typedef std::vector<class ProfileTime *> TimeList;
140 ProfileTime(const char *name) :
144 times_.push_back(this);
147 void AddTime(uint64_t time) {
154 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
166 ProfileTimer(ProfileTime &time) :
173 time_.AddTime(_timestamp - start_);
178 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
180 std::cerr << "========" << std::endl;
183 #define _profile(name) { \
184 static ProfileTime name(#name); \
185 ProfileTimer _ ## name(name);
189 /* Objective-C Handle<> {{{ */
190 template <typename Type_>
192 typedef _H<Type_> This_;
197 _finline void Retain_() {
202 _finline void Clear_() {
208 _finline _H(Type_ *value = NULL, bool mended = false) :
219 _finline This_ &operator =(Type_ *value) {
220 if (value_ != value) {
229 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
231 void NSLogPoint(const char *fix, const CGPoint &point) {
232 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
235 void NSLogRect(const char *fix, const CGRect &rect) {
236 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
239 @interface NSObject (Cydia)
240 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
241 - (id) yieldToSelector:(SEL)selector;
244 @implementation NSObject (Cydia)
249 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
250 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
251 id object([[context objectAtIndex:1] nonretainedObjectValue]);
252 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
254 /* XXX: deal with exceptions */
255 id value([self performSelector:selector withObject:object]);
257 [context removeAllObjects];
259 [context addObject:value];
264 performSelectorOnMainThread:@selector(doNothing)
270 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
271 /*return [self performSelector:selector withObject:object];*/
273 volatile bool stopped(false);
275 NSMutableArray *context([NSMutableArray arrayWithObjects:
276 [NSValue valueWithPointer:selector],
277 [NSValue valueWithNonretainedObject:object],
278 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
281 NSThread *thread([[[NSThread alloc]
283 selector:@selector(_yieldToContext:)
289 NSRunLoop *loop([NSRunLoop currentRunLoop]);
290 NSDate *future([NSDate distantFuture]);
292 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
294 return [context count] == 0 ? nil : [context objectAtIndex:0];
297 - (id) yieldToSelector:(SEL)selector {
298 return [self yieldToSelector:selector withObject:nil];
303 /* NSForcedOrderingSearch doesn't work on the iPhone */
304 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
305 static const NSStringCompareOptions BaseCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch;
306 static const NSStringCompareOptions ForcedCompareOptions_ = BaseCompareOptions_;
307 static const NSStringCompareOptions LaxCompareOptions_ = BaseCompareOptions_ | NSCaseInsensitiveSearch;
309 /* iPhoneOS 2.0 Compatibility {{{ */
311 @interface UITextView (iPhoneOS)
312 - (void) setTextSize:(float)size;
315 @implementation UITextView (iPhoneOS)
317 - (void) setTextSize:(float)size {
318 [self setFont:[[self font] fontWithSize:size]];
325 extern NSString * const kCAFilterNearest;
327 /* Information Dictionaries {{{ */
328 @interface NSMutableArray (Cydia)
329 - (void) addInfoDictionary:(NSDictionary *)info;
332 @implementation NSMutableArray (Cydia)
334 - (void) addInfoDictionary:(NSDictionary *)info {
335 [self addObject:info];
340 @interface NSMutableDictionary (Cydia)
341 - (void) addInfoDictionary:(NSDictionary *)info;
344 @implementation NSMutableDictionary (Cydia)
346 - (void) addInfoDictionary:(NSDictionary *)info {
347 NSString *bundle = [info objectForKey:@"CFBundleIdentifier"];
348 [self setObject:info forKey:bundle];
353 /* Pop Transitions {{{ */
354 @interface PopTransitionView : UITransitionView {
359 @implementation PopTransitionView
361 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
362 if (from != nil && to == nil)
363 [self removeFromSuperview];
368 @implementation UIView (PopUpView)
370 - (void) popFromSuperviewAnimated:(BOOL)animated {
371 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
374 - (void) popSubview:(UIView *)view {
375 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
376 [transition setDelegate:transition];
377 [self addSubview:transition];
379 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
380 [transition transition:UITransitionNone toView:blank];
381 [transition transition:UITransitionPushFromBottom toView:view];
387 #define lprintf(args...) fprintf(stderr, args)
390 #define ForSaurik (0 && !ForRelease)
391 #define LogBrowser (1 && !ForRelease)
392 #define TrackResize (0 && !ForRelease)
393 #define ManualRefresh (1 && !ForRelease)
394 #define ShowInternals (0 && !ForRelease)
395 #define IgnoreInstall (0 && !ForRelease)
396 #define RecycleWebViews 0
397 #define AlwaysReload (1 && !ForRelease)
401 #define _trace(args...)
403 #define _profile(name) {
406 #define PrintTimes() do {} while (false)
410 @interface NSMutableArray (Radix)
411 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
412 - (void) radixSortUsingFunction:(uint32_t (*)(id, void *))function withArgument:(void *)argument;
420 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
421 struct RadixItem_ *lhs(swap), *rhs(swap + count);
423 static const size_t width = 32;
424 static const size_t bits = 11;
425 static const size_t slots = 1 << bits;
426 static const size_t passes = (width + (bits - 1)) / bits;
428 size_t *hist(new size_t[slots]);
430 for (size_t pass(0); pass != passes; ++pass) {
431 memset(hist, 0, sizeof(size_t) * slots);
433 for (size_t i(0); i != count; ++i) {
434 uint32_t key(lhs[i].key);
436 key &= _not(uint32_t) >> width - bits;
441 for (size_t i(0); i != slots; ++i) {
442 size_t local(offset);
447 for (size_t i(0); i != count; ++i) {
448 uint32_t key(lhs[i].key);
450 key &= _not(uint32_t) >> width - bits;
451 rhs[hist[key]++] = lhs[i];
454 RadixItem_ *tmp(lhs);
461 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
462 for (size_t i(0); i != count; ++i)
463 [values addObject:[self objectAtIndex:lhs[i].index]];
464 [self setArray:values];
469 @implementation NSMutableArray (Radix)
471 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
472 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
473 [invocation setSelector:selector];
474 [invocation setArgument:&object atIndex:2];
476 size_t count([self count]);
477 struct RadixItem_ *swap(new RadixItem_[count * 2]);
479 for (size_t i(0); i != count; ++i) {
480 RadixItem_ &item(swap[i]);
483 id object([self objectAtIndex:i]);
484 [invocation setTarget:object];
487 [invocation getReturnValue:&item.key];
490 RadixSort_(self, count, swap);
493 - (void) radixSortUsingFunction:(uint32_t (*)(id, void *))function withArgument:(void *)argument {
494 size_t count([self count]);
495 struct RadixItem_ *swap(new RadixItem_[count * 2]);
497 for (size_t i(0); i != count; ++i) {
498 RadixItem_ &item(swap[i]);
501 id object([self objectAtIndex:i]);
502 item.key = function(object, argument);
505 RadixSort_(self, count, swap);
511 /* Apple Bug Fixes {{{ */
512 @implementation UIWebDocumentView (Cydia)
514 - (void) _setScrollerOffset:(CGPoint)offset {
515 UIScroller *scroller([self _scroller]);
517 CGSize size([scroller contentSize]);
518 CGSize bounds([scroller bounds].size);
521 max.x = size.width - bounds.width;
522 max.y = size.height - bounds.height;
530 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
531 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
533 [scroller setOffset:offset];
540 kUIControlEventMouseDown = 1 << 0,
541 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
542 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
543 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
544 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
545 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
546 } UIControlEventMasks;
548 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
549 size_t length([self length] - state->state);
552 else if (length > count)
554 for (size_t i(0); i != length; ++i)
555 objects[i] = [self item:state->state++];
556 state->itemsPtr = objects;
557 state->mutationsPtr = (unsigned long *) self;
561 @interface NSString (UIKit)
562 - (NSString *) stringByAddingPercentEscapes;
563 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
566 @interface NSString (Cydia)
567 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
568 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
569 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
570 - (NSComparisonResult) compareByPath:(NSString *)other;
571 - (NSString *) stringByCachingURLWithCurrentCDN;
572 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
575 @implementation NSString (Cydia)
577 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
578 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
581 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
582 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
583 memcpy(data, bytes, length);
584 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
587 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
588 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
591 - (NSComparisonResult) compareByPath:(NSString *)other {
592 NSString *prefix = [self commonPrefixWithString:other options:0];
593 size_t length = [prefix length];
595 NSRange lrange = NSMakeRange(length, [self length] - length);
596 NSRange rrange = NSMakeRange(length, [other length] - length);
598 lrange = [self rangeOfString:@"/" options:0 range:lrange];
599 rrange = [other rangeOfString:@"/" options:0 range:rrange];
601 NSComparisonResult value;
603 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
604 value = NSOrderedSame;
605 else if (lrange.location == NSNotFound)
606 value = NSOrderedAscending;
607 else if (rrange.location == NSNotFound)
608 value = NSOrderedDescending;
610 value = NSOrderedSame;
612 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
613 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
614 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
615 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
617 NSComparisonResult result = [lpath compare:rpath];
618 return result == NSOrderedSame ? value : result;
621 - (NSString *) stringByCachingURLWithCurrentCDN {
623 stringByReplacingOccurrencesOfString:@"://"
624 withString:@"://ne.edgecastcdn.net/8003A4/"
626 /* XXX: this is somewhat inaccurate */
627 range:NSMakeRange(0, 10)
631 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
632 return [(id)CFURLCreateStringByAddingPercentEscapes(
637 kCFStringEncodingUTF8
643 static inline NSString *CYLocalizeEx(NSString *key, NSString *value = nil) {
644 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:nil];
647 #define CYLocalize(key) CYLocalizeEx(@ key)
655 _finline void clear_() {
661 _finline bool empty() const {
665 _finline size_t size() const {
669 _finline char *data() const {
673 _finline void clear() {
678 _finline CYString() :
685 _finline ~CYString() {
689 void operator =(const CYString &rhs) {
693 if (rhs.cache_ == nil)
696 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
699 void set(apr_pool_t *pool, const char *data, size_t size) {
705 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size)));
706 memcpy(temp, data, size);
712 _finline void set(apr_pool_t *pool, const char *data) {
713 set(pool, data, data == NULL ? 0 : strlen(data));
716 _finline void set(apr_pool_t *pool, const std::string &rhs) {
717 set(pool, rhs.data(), rhs.size());
720 bool operator ==(const CYString &rhs) const {
721 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
725 if (cache_ == NULL) {
728 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
729 } return (id) cache_;
734 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
737 struct NSStringMapHash :
738 std::unary_function<NSString *, size_t>
740 _finline size_t operator ()(NSString *value) const {
741 return CFStringHashNSString((CFStringRef) value);
745 struct NSStringMapLess :
746 std::binary_function<NSString *, NSString *, bool>
748 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
749 return [lhs compare:rhs] == NSOrderedAscending;
753 struct NSStringMapEqual :
754 std::binary_function<NSString *, NSString *, bool>
756 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
757 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
758 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
759 //[lhs isEqualToString:rhs];
763 /* Perl-Compatible RegEx {{{ */
773 Pcre(const char *regex) :
778 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
781 lprintf("%d:%s\n", offset, error);
785 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
786 matches_ = new int[(capture_ + 1) * 3];
794 NSString *operator [](size_t match) {
795 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
798 bool operator ()(NSString *data) {
799 // XXX: length is for characters, not for bytes
800 return operator ()([data UTF8String], [data length]);
803 bool operator ()(const char *data, size_t size) {
805 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
809 /* Mime Addresses {{{ */
810 @interface Address : NSObject {
816 - (NSString *) address;
818 - (void) setAddress:(NSString *)address;
820 + (Address *) addressWithString:(NSString *)string;
821 - (Address *) initWithString:(NSString *)string;
824 @implementation Address
833 - (NSString *) name {
837 - (NSString *) address {
841 - (void) setAddress:(NSString *)address {
843 [address_ autorelease];
847 address_ = [address retain];
850 + (Address *) addressWithString:(NSString *)string {
851 return [[[Address alloc] initWithString:string] autorelease];
854 + (NSArray *) _attributeKeys {
855 return [NSArray arrayWithObjects:@"address", @"name", nil];
858 - (NSArray *) attributeKeys {
859 return [[self class] _attributeKeys];
862 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
863 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
866 - (Address *) initWithString:(NSString *)string {
867 if ((self = [super init]) != nil) {
868 const char *data = [string UTF8String];
869 size_t size = [string length];
871 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
873 if (address_r(data, size)) {
874 name_ = [address_r[1] retain];
875 address_ = [address_r[2] retain];
877 name_ = [string retain];
885 /* CoreGraphics Primitives {{{ */
896 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
899 Set(space, red, green, blue, alpha);
904 CGColorRelease(color_);
911 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
913 float color[] = {red, green, blue, alpha};
914 color_ = CGColorCreate(space, color);
917 operator CGColorRef() {
923 extern "C" void UISetColor(CGColorRef color);
925 /* Random Global Variables {{{ */
926 static const int PulseInterval_ = 50000;
927 static const int ButtonBarHeight_ = 48;
928 static const float KeyboardTime_ = 0.3f;
930 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
931 #define SandboxTemplate_ "/usr/share/sandbox/SandboxTemplate.sb"
932 #define NotifyConfig_ "/etc/notify.conf"
934 static bool Queuing_;
936 static CGColor Blue_;
937 static CGColor Blueish_;
938 static CGColor Black_;
940 static CGColor White_;
941 static CGColor Gray_;
942 static CGColor Green_;
943 static CGColor Purple_;
944 static CGColor Purplish_;
946 static UIColor *InstallingColor_;
947 static UIColor *RemovingColor_;
949 static NSString *App_;
950 static NSString *Home_;
951 static BOOL Sounds_Keyboard_;
953 static BOOL Advanced_;
955 static BOOL Ignored_;
957 static UIFont *Font12_;
958 static UIFont *Font12Bold_;
959 static UIFont *Font14_;
960 static UIFont *Font18Bold_;
961 static UIFont *Font22Bold_;
963 static const char *Machine_ = NULL;
964 static const NSString *UniqueID_ = nil;
965 static const NSString *Build_ = nil;
966 static const NSString *Product_ = nil;
967 static const NSString *Safari_ = nil;
971 CGColorSpaceRef space_;
976 static NSDictionary *SectionMap_;
977 static NSMutableDictionary *Metadata_;
978 static _transient NSMutableDictionary *Settings_;
979 static _transient NSString *Role_;
980 static _transient NSMutableDictionary *Packages_;
981 static _transient NSMutableDictionary *Sections_;
982 static _transient NSMutableDictionary *Sources_;
983 static bool Changed_;
987 static NSMutableArray *Documents_;
990 NSString *GetLastUpdate() {
991 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
994 return CYLocalize("NEVER_OR_UNKNOWN");
996 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
997 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
999 CFRelease(formatter);
1001 return [(NSString *) formatted autorelease];
1004 /* Display Helpers {{{ */
1005 inline float Interpolate(float begin, float end, float fraction) {
1006 return (end - begin) * fraction + begin;
1009 /* XXX: localize this! */
1010 NSString *SizeString(double size) {
1011 bool negative = size < 0;
1016 while (size > 1024) {
1021 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1023 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1026 NSString *StripVersion(NSString *version) {
1027 NSRange colon = [version rangeOfString:@":"];
1028 if (colon.location != NSNotFound)
1029 version = [version substringFromIndex:(colon.location + 1)];
1033 NSString *LocalizeSection(NSString *section) {
1034 static Pcre title_r("^(.*?) \\((.*)\\)$");
1035 if (title_r(section))
1036 return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"),
1037 LocalizeSection(title_r[1]),
1038 LocalizeSection(title_r[2])
1041 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1044 NSString *Simplify(NSString *title) {
1045 const char *data = [title UTF8String];
1046 size_t size = [title length];
1048 static Pcre square_r("^\\[(.*)\\]$");
1049 if (square_r(data, size))
1050 return Simplify(square_r[1]);
1052 static Pcre paren_r("^\\((.*)\\)$");
1053 if (paren_r(data, size))
1054 return Simplify(paren_r[1]);
1056 static Pcre title_r("^(.*?) \\((.*)\\)$");
1057 if (title_r(data, size))
1058 return Simplify(title_r[1]);
1064 bool isSectionVisible(NSString *section) {
1065 NSDictionary *metadata = [Sections_ objectForKey:section];
1066 NSNumber *hidden = metadata == nil ? nil : [metadata objectForKey:@"Hidden"];
1067 return hidden == nil || ![hidden boolValue];
1070 /* Delegate Prototypes {{{ */
1074 @interface NSObject (ProgressDelegate)
1077 @implementation NSObject(ProgressDelegate)
1079 - (void) _setProgressError:(NSArray *)args {
1080 [self performSelector:@selector(setProgressError:forPackage:)
1081 withObject:[args objectAtIndex:0]
1082 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1088 @protocol ProgressDelegate
1089 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1090 - (void) setProgressTitle:(NSString *)title;
1091 - (void) setProgressPercent:(float)percent;
1092 - (void) startProgress;
1093 - (void) addProgressOutput:(NSString *)output;
1094 - (bool) isCancelling:(size_t)received;
1097 @protocol ConfigurationDelegate
1098 - (void) repairWithSelector:(SEL)selector;
1099 - (void) setConfigurationData:(NSString *)data;
1104 @protocol CydiaDelegate
1105 - (void) setPackageView:(PackageView *)view;
1106 - (void) clearPackage:(Package *)package;
1107 - (void) installPackage:(Package *)package;
1108 - (void) removePackage:(Package *)package;
1109 - (void) slideUp:(UIActionSheet *)alert;
1110 - (void) distUpgrade;
1111 - (void) updateData;
1113 - (void) askForSettings;
1114 - (UIProgressHUD *) addProgressHUD;
1115 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1116 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1117 - (RVPage *) pageForPackage:(NSString *)name;
1118 - (void) openMailToURL:(NSURL *)url;
1119 - (void) clearFirstResponder;
1120 - (PackageView *) packageView;
1124 /* Status Delegation {{{ */
1126 public pkgAcquireStatus
1129 _transient NSObject<ProgressDelegate> *delegate_;
1137 void setDelegate(id delegate) {
1138 delegate_ = delegate;
1141 virtual bool MediaChange(std::string media, std::string drive) {
1145 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1148 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1149 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1150 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1153 virtual void Done(pkgAcquire::ItemDesc &item) {
1156 virtual void Fail(pkgAcquire::ItemDesc &item) {
1158 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1159 item.Owner->Status == pkgAcquire::Item::StatDone
1163 std::string &error(item.Owner->ErrorText);
1167 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1168 NSArray *fields([description componentsSeparatedByString:@" "]);
1169 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1171 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1172 withObject:[NSArray arrayWithObjects:
1173 [NSString stringWithUTF8String:error.c_str()],
1180 virtual bool Pulse(pkgAcquire *Owner) {
1181 bool value = pkgAcquireStatus::Pulse(Owner);
1184 double(CurrentBytes + CurrentItems) /
1185 double(TotalBytes + TotalItems)
1188 [delegate_ setProgressPercent:percent];
1189 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1192 virtual void Start() {
1193 [delegate_ startProgress];
1196 virtual void Stop() {
1200 /* Progress Delegation {{{ */
1205 _transient id<ProgressDelegate> delegate_;
1208 virtual void Update() {
1209 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1210 [delegate_ setProgressPercent:(Percent / 100)];*/
1219 void setDelegate(id delegate) {
1220 delegate_ = delegate;
1223 virtual void Done() {
1224 //[delegate_ setProgressPercent:1];
1229 /* Database Interface {{{ */
1230 @interface Database : NSObject {
1236 pkgCacheFile cache_;
1237 pkgDepCache::Policy *policy_;
1238 pkgRecords *records_;
1239 pkgProblemResolver *resolver_;
1240 pkgAcquire *fetcher_;
1242 SPtr<pkgPackageManager> manager_;
1243 pkgSourceList *list_;
1245 NSMutableDictionary *sources_;
1246 NSMutableArray *packages_;
1248 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1257 + (Database *) sharedInstance;
1260 - (void) _readCydia:(NSNumber *)fd;
1261 - (void) _readStatus:(NSNumber *)fd;
1262 - (void) _readOutput:(NSNumber *)fd;
1266 - (Package *) packageWithName:(NSString *)name;
1268 - (pkgCacheFile &) cache;
1269 - (pkgDepCache::Policy *) policy;
1270 - (pkgRecords *) records;
1271 - (pkgProblemResolver *) resolver;
1272 - (pkgAcquire &) fetcher;
1273 - (pkgSourceList &) list;
1274 - (NSArray *) packages;
1275 - (NSArray *) sources;
1276 - (void) reloadData;
1284 - (void) updateWithStatus:(Status &)status;
1286 - (void) setDelegate:(id)delegate;
1287 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1291 /* Source Class {{{ */
1292 @interface Source : NSObject {
1293 NSString *description_;
1299 NSString *distribution_;
1303 NSString *defaultIcon_;
1305 NSDictionary *record_;
1309 - (Source *) initWithMetaIndex:(metaIndex *)index;
1311 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1313 - (NSString *) supportForPackage:(NSString *)package;
1315 - (NSDictionary *) record;
1319 - (NSString *) distribution;
1320 - (NSString *) type;
1322 - (NSString *) host;
1324 - (NSString *) name;
1325 - (NSString *) description;
1326 - (NSString *) label;
1327 - (NSString *) origin;
1328 - (NSString *) version;
1330 - (NSString *) defaultIcon;
1334 @implementation Source
1336 #define _clear(field) \
1343 _clear(distribution_)
1346 _clear(description_)
1351 _clear(defaultIcon_)
1360 + (NSArray *) _attributeKeys {
1361 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1364 - (NSArray *) attributeKeys {
1365 return [[self class] _attributeKeys];
1368 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1369 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1372 - (void) setMetaIndex:(metaIndex *)index {
1375 trusted_ = index->IsTrusted();
1377 uri_ = [[NSString stringWithUTF8String:index->GetURI().c_str()] retain];
1378 distribution_ = [[NSString stringWithUTF8String:index->GetDist().c_str()] retain];
1379 type_ = [[NSString stringWithUTF8String:index->GetType()] retain];
1381 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1382 if (dindex != NULL) {
1383 std::ifstream release(dindex->MetaIndexFile("Release").c_str());
1385 while (std::getline(release, line)) {
1386 std::string::size_type colon(line.find(':'));
1387 if (colon == std::string::npos)
1390 std::string name(line.substr(0, colon));
1391 std::string value(line.substr(colon + 1));
1392 while (!value.empty() && value[0] == ' ')
1393 value = value.substr(1);
1395 if (name == "Default-Icon")
1396 defaultIcon_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1397 else if (name == "Description")
1398 description_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1399 else if (name == "Label")
1400 label_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1401 else if (name == "Origin")
1402 origin_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1403 else if (name == "Support")
1404 support_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1405 else if (name == "Version")
1406 version_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1410 record_ = [Sources_ objectForKey:[self key]];
1412 record_ = [record_ retain];
1415 - (Source *) initWithMetaIndex:(metaIndex *)index {
1416 if ((self = [super init]) != nil) {
1417 [self setMetaIndex:index];
1421 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1422 NSDictionary *lhr = [self record];
1423 NSDictionary *rhr = [source record];
1426 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1428 NSString *lhs = [self name];
1429 NSString *rhs = [source name];
1431 if ([lhs length] != 0 && [rhs length] != 0) {
1432 unichar lhc = [lhs characterAtIndex:0];
1433 unichar rhc = [rhs characterAtIndex:0];
1435 if (isalpha(lhc) && !isalpha(rhc))
1436 return NSOrderedAscending;
1437 else if (!isalpha(lhc) && isalpha(rhc))
1438 return NSOrderedDescending;
1441 return [lhs compare:rhs options:LaxCompareOptions_];
1444 - (NSString *) supportForPackage:(NSString *)package {
1445 return support_ == nil ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1448 - (NSDictionary *) record {
1456 - (NSString *) uri {
1460 - (NSString *) distribution {
1461 return distribution_;
1464 - (NSString *) type {
1468 - (NSString *) key {
1469 return [NSString stringWithFormat:@"%@:%@:%@", type_, uri_, distribution_];
1472 - (NSString *) host {
1473 return [[[NSURL URLWithString:[self uri]] host] lowercaseString];
1476 - (NSString *) name {
1477 return origin_ == nil ? [self host] : origin_;
1480 - (NSString *) description {
1481 return description_;
1484 - (NSString *) label {
1485 return label_ == nil ? [self host] : label_;
1488 - (NSString *) origin {
1492 - (NSString *) version {
1496 - (NSString *) defaultIcon {
1497 return defaultIcon_;
1502 /* Relationship Class {{{ */
1503 @interface Relationship : NSObject {
1508 - (NSString *) type;
1510 - (NSString *) name;
1514 @implementation Relationship
1522 - (NSString *) type {
1530 - (NSString *) name {
1537 /* Package Class {{{ */
1538 @interface Package : NSObject {
1541 pkgCache::VerIterator version_;
1542 pkgCache::PkgIterator iterator_;
1543 _transient Database *database_;
1544 pkgCache::VerFileIterator file_;
1550 NSString *section$_;
1554 NSString *installed_;
1560 CYString depiction_;
1573 NSArray *relationships_;
1574 NSMutableDictionary *metadata_;
1577 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1578 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1580 - (pkgCache::PkgIterator) iterator;
1582 - (NSString *) section;
1583 - (NSString *) simpleSection;
1585 - (NSString *) longSection;
1586 - (NSString *) shortSection;
1590 - (Address *) maintainer;
1592 - (NSString *) description;
1595 - (NSMutableDictionary *) metadata;
1597 - (BOOL) subscribed;
1600 - (NSString *) latest;
1601 - (NSString *) installed;
1604 - (BOOL) upgradableAndEssential:(BOOL)essential;
1607 - (BOOL) unfiltered;
1611 - (BOOL) halfConfigured;
1612 - (BOOL) halfInstalled;
1614 - (NSString *) mode;
1617 - (NSString *) name;
1618 - (NSString *) tagline;
1620 - (NSString *) homepage;
1621 - (NSString *) depiction;
1622 - (Address *) author;
1624 - (NSString *) support;
1626 - (NSArray *) files;
1627 - (NSArray *) relationships;
1628 - (NSArray *) warnings;
1629 - (NSArray *) applications;
1631 - (Source *) source;
1632 - (NSString *) role;
1634 - (BOOL) matches:(NSString *)text;
1636 - (bool) hasSupportingRole;
1637 - (BOOL) hasTag:(NSString *)tag;
1638 - (NSString *) primaryPurpose;
1639 - (NSArray *) purposes;
1640 - (bool) isCommercial;
1642 - (uint32_t) compareByPrefix;
1643 - (NSComparisonResult) compareByName:(Package *)package;
1644 - (uint32_t) compareBySection:(NSArray *)sections;
1646 - (uint32_t) compareForChanges;
1651 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1652 - (bool) isInstalledAndVisible:(NSNumber *)number;
1653 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1654 - (bool) isVisibleInSource:(Source *)source;
1658 uint32_t PackageChangesRadix(Package *self, void *) {
1663 uint32_t timestamp : 30;
1664 uint32_t ignored : 1;
1665 uint32_t upgradable : 1;
1669 bool upgradable([self upgradableAndEssential:YES]);
1670 value.bits.upgradable = upgradable ? 1 : 0;
1673 value.bits.timestamp = 0;
1674 value.bits.ignored = [self ignored] ? 0 : 1;
1675 value.bits.upgradable = 1;
1677 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1678 value.bits.ignored = 0;
1679 value.bits.upgradable = 0;
1682 return _not(uint32_t) - value.key;
1685 @implementation Package
1690 if (section$_ != nil)
1691 [section$_ release];
1695 if (installed_ != nil)
1696 [installed_ release];
1700 if (sponsor$_ != nil)
1701 [sponsor$_ release];
1702 if (author$_ != nil)
1709 if (relationships_ != nil)
1710 [relationships_ release];
1711 if (metadata_ != nil)
1712 [metadata_ release];
1717 + (NSString *) webScriptNameForSelector:(SEL)selector {
1718 if (selector == @selector(hasTag:))
1724 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1725 return [self webScriptNameForSelector:selector] == nil;
1728 + (NSArray *) _attributeKeys {
1729 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];
1732 - (NSArray *) attributeKeys {
1733 return [[self class] _attributeKeys];
1736 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1737 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1740 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
1741 if ((self = [super init]) != nil) {
1742 _profile(Package$initWithVersion)
1743 @synchronized (database) {
1744 era_ = [database era];
1747 iterator_ = version.ParentPkg();
1748 database_ = database;
1750 _profile(Package$initWithVersion$Latest)
1751 latest_ = [StripVersion([NSString stringWithUTF8String:version_.VerStr()]) retain];
1754 pkgCache::VerIterator current;
1755 NSString *installed;
1757 _profile(Package$initWithVersion$Current)
1758 current = iterator_.CurrentVer();
1759 installed = current.end() ? nil : [NSString stringWithUTF8String:current.VerStr()];
1762 _profile(Package$initWithVersion$Installed)
1763 installed_ = [StripVersion(installed) retain];
1766 _profile(Package$initWithVersion$File)
1767 if (!version_.end())
1768 file_ = version_.FileList();
1770 pkgCache &cache([database_ cache]);
1771 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
1775 _profile(Package$initWithVersion$Name)
1776 id_ = [[NSString stringWithUTF8String:iterator_.Name()] retain];
1780 source_ = [database_ getSource:file_.File()];
1785 _profile(Package$initWithVersion$Parse)
1786 pkgRecords::Parser *parser;
1788 _profile(Package$initWithVersion$Parse$Lookup)
1789 parser = &[database_ records]->Lookup(file_);
1792 const char *begin, *end;
1793 parser->GetRec(begin, end);
1804 {"depiction", &depiction_},
1805 {"homepage", &homepage_},
1806 {"website", &website},
1807 {"support", &support_},
1808 {"sponsor", &sponsor_},
1809 {"author", &author_},
1813 while (begin != end)
1814 if (*begin == '\n') {
1817 } else if (isblank(*begin)) next: {
1818 begin = static_cast<char *>(memchr(begin + 1, '\n', end - begin - 1));
1821 } else if (const char *colon = static_cast<char *>(memchr(begin, ':', end - begin))) {
1822 const char *name(begin);
1823 size_t size(colon - begin);
1825 begin = static_cast<char *>(memchr(begin, '\n', end - begin));
1828 const char *stop(begin == NULL ? end : begin);
1829 while (stop[-1] == '\r')
1831 while (++colon != stop && isblank(*colon));
1833 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i)
1834 if (strncasecmp(names[i].name_, name, size) == 0) {
1835 CYString &value(*names[i].value_);
1837 _profile(Package$initWithVersion$Parse$Value)
1838 value.set(pool, colon, stop - colon);
1850 _profile(Package$initWithVersion$Parse$Tagline)
1851 tagline_.set(pool, parser->ShortDesc());
1854 _profile(Package$initWithVersion$Parse$Retain)
1855 if (!homepage_.empty())
1856 homepage_ = website;
1857 if (homepage_ == depiction_)
1860 tags_ = [[tag componentsSeparatedByString:@", "] retain];
1864 _profile(Package$initWithVersion$Tags)
1866 for (NSString *tag in tags_)
1867 if ([tag hasPrefix:@"role::"]) {
1868 role_ = [[tag substringFromIndex:6] retain];
1873 bool changed(false);
1874 NSString *key([id_ lowercaseString]);
1876 _profile(Package$initWithVersion$Metadata)
1877 metadata_ = [Packages_ objectForKey:key];
1878 if (metadata_ == nil) {
1879 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
1883 [metadata_ setObject:latest_ forKey:@"LastVersion"];
1886 NSDate *first([metadata_ objectForKey:@"FirstSeen"]);
1887 NSDate *last([metadata_ objectForKey:@"LastSeen"]);
1888 NSString *version([metadata_ objectForKey:@"LastVersion"]);
1891 first = last == nil ? now_ : last;
1892 [metadata_ setObject:first forKey:@"FirstSeen"];
1896 if (version == nil) {
1897 [metadata_ setObject:latest_ forKey:@"LastVersion"];
1899 } else if (![version isEqualToString:latest_]) {
1900 [metadata_ setObject:latest_ forKey:@"LastVersion"];
1902 [metadata_ setObject:last forKey:@"LastSeen"];
1907 metadata_ = [metadata_ retain];
1910 [Packages_ setObject:metadata_ forKey:key];
1915 _profile(Package$initWithVersion$Section)
1916 section_.set(pool, iterator_.Section());
1919 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
1920 } _end } return self;
1923 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
1924 pkgCache::VerIterator version;
1926 _profile(Package$packageWithIterator$GetCandidateVer)
1927 version = [database policy]->GetCandidateVer(iterator);
1933 return [[[Package alloc]
1934 initWithVersion:version
1941 - (pkgCache::PkgIterator) iterator {
1945 - (NSString *) section {
1946 if (section$_ == nil) {
1947 if (section_.empty())
1950 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
1951 NSString *name(section_);
1954 if (NSDictionary *value = [SectionMap_ objectForKey:name])
1955 if (NSString *rename = [value objectForKey:@"Rename"]) {
1960 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
1964 - (NSString *) simpleSection {
1965 if (NSString *section = [self section])
1966 return Simplify(section);
1971 - (NSString *) longSection {
1972 return LocalizeSection(section_);
1975 - (NSString *) shortSection {
1976 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
1979 - (NSString *) uri {
1982 pkgIndexFile *index;
1983 pkgCache::PkgFileIterator file(file_.File());
1984 if (![database_ list].FindIndex(file, index))
1986 return [NSString stringWithUTF8String:iterator_->Path];
1987 //return [NSString stringWithUTF8String:file.Site()];
1988 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
1992 - (Address *) maintainer {
1995 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
1996 const std::string &maintainer(parser->Maintainer());
1997 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2001 return version_.end() ? 0 : version_->InstalledSize;
2004 - (NSString *) description {
2007 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2008 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2010 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2011 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2012 if ([lines count] < 2)
2015 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2016 for (size_t i(1), e([lines count]); i != e; ++i) {
2017 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2018 [trimmed addObject:trim];
2021 return [trimmed componentsJoinedByString:@"\n"];
2025 _profile(Package$index)
2026 NSString *name([self name]);
2027 if ([name length] == 0)
2029 unichar character([name characterAtIndex:0]);
2030 if (!isalpha(character))
2032 return toupper(character);
2036 - (NSMutableDictionary *) metadata {
2037 if (metadata_ == nil)
2038 metadata_ = [[Packages_ objectForKey:[id_ lowercaseString]] retain];
2043 NSDictionary *metadata([self metadata]);
2044 if ([self subscribed])
2045 if (NSDate *last = [metadata objectForKey:@"LastSeen"])
2047 return [metadata objectForKey:@"FirstSeen"];
2050 - (BOOL) subscribed {
2051 NSDictionary *metadata([self metadata]);
2052 if (NSNumber *subscribed = [metadata objectForKey:@"IsSubscribed"])
2053 return [subscribed boolValue];
2059 NSDictionary *metadata([self metadata]);
2060 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2061 return [ignored boolValue];
2066 - (NSString *) latest {
2070 - (NSString *) installed {
2075 return !version_.end();
2078 - (BOOL) upgradableAndEssential:(BOOL)essential {
2079 pkgCache::VerIterator current = iterator_.CurrentVer();
2083 value = essential && [self essential] && [self visible];
2085 value = !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2089 - (BOOL) essential {
2094 return [database_ cache][iterator_].InstBroken();
2097 - (BOOL) unfiltered {
2098 NSString *section = [self section];
2099 return section == nil || isSectionVisible(section);
2103 return [self hasSupportingRole] && [self unfiltered];
2107 unsigned char current = iterator_->CurrentState;
2108 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2111 - (BOOL) halfConfigured {
2112 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2115 - (BOOL) halfInstalled {
2116 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2120 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2121 return state.Mode != pkgDepCache::ModeKeep;
2124 - (NSString *) mode {
2125 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2127 switch (state.Mode) {
2128 case pkgDepCache::ModeDelete:
2129 if ((state.iFlags & pkgDepCache::Purge) != 0)
2133 case pkgDepCache::ModeKeep:
2134 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2135 return @"REINSTALL";
2136 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2140 case pkgDepCache::ModeInstall:
2141 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2142 return @"REINSTALL";
2143 else*/ switch (state.Status) {
2145 return @"DOWNGRADE";
2151 return @"NEW_INSTALL";
2164 - (NSString *) name {
2165 return name_ == nil ? id_ : name_;
2168 - (NSString *) tagline {
2172 - (UIImage *) icon {
2173 NSString *section = [self simpleSection];
2177 if ([icon_ hasPrefix:@"file:///"])
2178 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2179 if (icon == nil) if (section != nil)
2180 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2181 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2182 if ([dicon hasPrefix:@"file:///"])
2183 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2185 icon = [UIImage applicationImageNamed:@"unknown.png"];
2189 - (NSString *) homepage {
2193 - (NSString *) depiction {
2197 - (Address *) sponsor {
2198 if (sponsor$_ == nil) {
2199 if (sponsor_.empty())
2201 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2205 - (Address *) author {
2206 if (author$_ == nil) {
2207 if (author_.empty())
2209 author$_ = [[Address addressWithString:author_] retain];
2213 - (NSString *) support {
2214 return support_ != nil ? support_ : [[self source] supportForPackage:id_];
2217 - (NSArray *) files {
2218 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", id_];
2219 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2222 fin.open([path UTF8String]);
2227 while (std::getline(fin, line))
2228 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2233 - (NSArray *) relationships {
2234 return relationships_;
2237 - (NSArray *) warnings {
2238 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2239 const char *name(iterator_.Name());
2241 size_t length(strlen(name));
2242 if (length < 2) invalid:
2243 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2244 else for (size_t i(0); i != length; ++i)
2246 /* XXX: technically this is not allowed */
2247 (name[i] < 'A' || name[i] > 'Z') &&
2248 (name[i] < 'a' || name[i] > 'z') &&
2249 (name[i] < '0' || name[i] > '9') &&
2250 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2253 if (strcmp(name, "cydia") != 0) {
2255 bool _private = false;
2258 bool repository = [[self section] isEqualToString:@"Repositories"];
2260 if (NSArray *files = [self files])
2261 for (NSString *file in files)
2262 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2264 else if (!_private && [file isEqualToString:@"/private"])
2266 else if (!stash && [file isEqualToString:@"/var/stash"])
2269 /* XXX: this is not sensitive enough. only some folders are valid. */
2270 if (cydia && !repository)
2271 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2273 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2275 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2278 return [warnings count] == 0 ? nil : warnings;
2281 - (NSArray *) applications {
2282 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2284 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2286 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2287 if (NSArray *files = [self files])
2288 for (NSString *file in files)
2289 if (application_r(file)) {
2290 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2291 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2292 if ([id isEqualToString:me])
2295 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2297 display = application_r[1];
2299 NSString *bundle([file stringByDeletingLastPathComponent]);
2300 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2301 if (icon == nil || [icon length] == 0)
2303 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2305 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2306 [applications addObject:application];
2308 [application addObject:id];
2309 [application addObject:display];
2310 [application addObject:url];
2313 return [applications count] == 0 ? nil : applications;
2316 - (Source *) source {
2318 @synchronized (database_) {
2319 if ([database_ era] != era_ || file_.end())
2322 source_ = [database_ getSource:file_.File()];
2334 - (NSString *) role {
2338 - (BOOL) matches:(NSString *)text {
2344 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2345 if (range.location != NSNotFound)
2348 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2349 if (range.location != NSNotFound)
2352 range = [[self tagline] rangeOfString:text options:MatchCompareOptions_];
2353 if (range.location != NSNotFound)
2359 - (bool) hasSupportingRole {
2362 if ([role_ isEqualToString:@"enduser"])
2364 if ([Role_ isEqualToString:@"User"])
2366 if ([role_ isEqualToString:@"hacker"])
2368 if ([Role_ isEqualToString:@"Hacker"])
2370 if ([role_ isEqualToString:@"developer"])
2372 if ([Role_ isEqualToString:@"Developer"])
2377 - (BOOL) hasTag:(NSString *)tag {
2378 return tags_ == nil ? NO : [tags_ containsObject:tag];
2381 - (NSString *) primaryPurpose {
2382 for (NSString *tag in tags_)
2383 if ([tag hasPrefix:@"purpose::"])
2384 return [tag substringFromIndex:9];
2388 - (NSArray *) purposes {
2389 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2390 for (NSString *tag in tags_)
2391 if ([tag hasPrefix:@"purpose::"])
2392 [purposes addObject:[tag substringFromIndex:9]];
2393 return [purposes count] == 0 ? nil : purposes;
2396 - (bool) isCommercial {
2397 return [self hasTag:@"cydia::commercial"];
2400 - (uint32_t) compareByPrefix {
2404 - (NSComparisonResult) compareByName:(Package *)package {
2405 NSString *lhs = [self name];
2406 NSString *rhs = [package name];
2408 if ([lhs length] != 0 && [rhs length] != 0) {
2409 unichar lhc = [lhs characterAtIndex:0];
2410 unichar rhc = [rhs characterAtIndex:0];
2412 if (isalpha(lhc) && !isalpha(rhc))
2413 return NSOrderedAscending;
2414 else if (!isalpha(lhc) && isalpha(rhc))
2415 return NSOrderedDescending;
2418 return [lhs compare:rhs options:LaxCompareOptions_];
2421 - (uint32_t) compareBySection:(NSArray *)sections {
2422 NSString *section([self section]);
2423 for (size_t i(0), e([sections count]); i != e; ++i) {
2424 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2428 return _not(uint32_t);
2431 - (uint32_t) compareForChanges {
2436 uint32_t timestamp : 30;
2437 uint32_t ignored : 1;
2438 uint32_t upgradable : 1;
2442 bool upgradable([self upgradableAndEssential:YES]);
2443 value.bits.upgradable = upgradable ? 1 : 0;
2446 value.bits.timestamp = 0;
2447 value.bits.ignored = [self ignored] ? 0 : 1;
2448 value.bits.upgradable = 1;
2450 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2451 value.bits.ignored = 0;
2452 value.bits.upgradable = 0;
2455 return _not(uint32_t) - value.key;
2459 pkgProblemResolver *resolver = [database_ resolver];
2460 resolver->Clear(iterator_);
2461 resolver->Protect(iterator_);
2465 pkgProblemResolver *resolver = [database_ resolver];
2466 resolver->Clear(iterator_);
2467 resolver->Protect(iterator_);
2468 pkgCacheFile &cache([database_ cache]);
2469 cache->MarkInstall(iterator_, false);
2470 pkgDepCache::StateCache &state((*cache)[iterator_]);
2471 if (!state.Install())
2472 cache->SetReInstall(iterator_, true);
2476 pkgProblemResolver *resolver = [database_ resolver];
2477 resolver->Clear(iterator_);
2478 resolver->Protect(iterator_);
2479 resolver->Remove(iterator_);
2480 [database_ cache]->MarkDelete(iterator_, true);
2483 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2484 _profile(Package$isUnfilteredAndSearchedForBy)
2487 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2488 value &= [self unfiltered];
2491 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2492 value &= [self matches:search];
2499 - (bool) isInstalledAndVisible:(NSNumber *)number {
2500 return (![number boolValue] || [self visible]) && [self installed] != nil;
2503 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2504 NSString *section = [self section];
2508 [self installed] == nil && (
2510 section == nil && [name length] == 0 ||
2511 [name isEqualToString:section]
2515 - (bool) isVisibleInSource:(Source *)source {
2516 return [self source] == source && [self visible];
2521 /* Section Class {{{ */
2522 @interface Section : NSObject {
2527 NSString *localized_;
2530 - (NSComparisonResult) compareByName:(Section *)section;
2531 - (Section *) initWithName:(NSString *)name;
2532 - (Section *) initWithName:(NSString *)name row:(size_t)row;
2533 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2534 - (NSString *) name;
2541 - (void) addToCount;
2543 - (void) setCount:(size_t)count;
2547 @implementation Section
2551 if (localized_ != nil)
2552 [localized_ release];
2556 - (NSComparisonResult) compareByName:(Section *)section {
2557 NSString *lhs = [self name];
2558 NSString *rhs = [section name];
2560 if ([lhs length] != 0 && [rhs length] != 0) {
2561 unichar lhc = [lhs characterAtIndex:0];
2562 unichar rhc = [rhs characterAtIndex:0];
2564 if (isalpha(lhc) && !isalpha(rhc))
2565 return NSOrderedAscending;
2566 else if (!isalpha(lhc) && isalpha(rhc))
2567 return NSOrderedDescending;
2570 return [lhs compare:rhs options:LaxCompareOptions_];
2573 - (Section *) initWithName:(NSString *)name {
2574 return [self initWithName:name row:0];
2577 - (Section *) initWithName:(NSString *)name row:(size_t)row {
2578 if ((self = [super init]) != nil) {
2579 name_ = [name retain];
2582 localized_ = [LocalizeSection(name_) retain];
2586 /* XXX: localize the index thingees */
2587 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2588 if ((self = [super init]) != nil) {
2589 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2595 - (NSString *) name {
2615 - (void) addToCount {
2619 - (void) setCount:(size_t)count {
2623 - (NSString *) localized {
2631 static NSArray *Finishes_;
2633 /* Database Implementation {{{ */
2634 @implementation Database
2636 + (Database *) sharedInstance {
2637 static Database *instance;
2638 if (instance == nil)
2639 instance = [[Database alloc] init];
2649 NSRecycleZone(zone_);
2650 // XXX: malloc_destroy_zone(zone_);
2651 apr_pool_destroy(pool_);
2655 - (void) _readCydia:(NSNumber *)fd { _pooled
2656 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2657 std::istream is(&ib);
2660 static Pcre finish_r("^finish:([^:]*)$");
2662 while (std::getline(is, line)) {
2663 const char *data(line.c_str());
2664 size_t size = line.size();
2665 lprintf("C:%s\n", data);
2667 if (finish_r(data, size)) {
2668 NSString *finish = finish_r[1];
2669 int index = [Finishes_ indexOfObject:finish];
2670 if (index != INT_MAX && index > Finish_)
2678 - (void) _readStatus:(NSNumber *)fd { _pooled
2679 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2680 std::istream is(&ib);
2683 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2684 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2686 while (std::getline(is, line)) {
2687 const char *data(line.c_str());
2688 size_t size = line.size();
2689 lprintf("S:%s\n", data);
2691 if (conffile_r(data, size)) {
2692 [delegate_ setConfigurationData:conffile_r[1]];
2693 } else if (strncmp(data, "status: ", 8) == 0) {
2694 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2695 [delegate_ setProgressTitle:string];
2696 } else if (pmstatus_r(data, size)) {
2697 std::string type([pmstatus_r[1] UTF8String]);
2698 NSString *id = pmstatus_r[2];
2700 float percent([pmstatus_r[3] floatValue]);
2701 [delegate_ setProgressPercent:(percent / 100)];
2703 NSString *string = pmstatus_r[4];
2705 if (type == "pmerror")
2706 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2707 withObject:[NSArray arrayWithObjects:string, id, nil]
2710 else if (type == "pmstatus") {
2711 [delegate_ setProgressTitle:string];
2712 } else if (type == "pmconffile")
2713 [delegate_ setConfigurationData:string];
2714 else _assert(false);
2715 } else _assert(false);
2721 - (void) _readOutput:(NSNumber *)fd { _pooled
2722 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2723 std::istream is(&ib);
2726 while (std::getline(is, line)) {
2727 lprintf("O:%s\n", line.c_str());
2728 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2738 - (Package *) packageWithName:(NSString *)name {
2739 if (static_cast<pkgDepCache *>(cache_) == NULL)
2741 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2742 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2745 - (Database *) init {
2746 if ((self = [super init]) != nil) {
2753 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2754 apr_pool_create(&pool_, NULL);
2756 sources_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];
2757 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
2761 _assert(pipe(fds) != -1);
2764 _config->Set("APT::Keep-Fds::", cydiafd_);
2765 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
2768 detachNewThreadSelector:@selector(_readCydia:)
2770 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2773 _assert(pipe(fds) != -1);
2777 detachNewThreadSelector:@selector(_readStatus:)
2779 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2782 _assert(pipe(fds) != -1);
2783 _assert(dup2(fds[0], 0) != -1);
2784 _assert(close(fds[0]) != -1);
2786 input_ = fdopen(fds[1], "a");
2788 _assert(pipe(fds) != -1);
2789 _assert(dup2(fds[1], 1) != -1);
2790 _assert(close(fds[1]) != -1);
2793 detachNewThreadSelector:@selector(_readOutput:)
2795 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2800 - (pkgCacheFile &) cache {
2804 - (pkgDepCache::Policy *) policy {
2808 - (pkgRecords *) records {
2812 - (pkgProblemResolver *) resolver {
2816 - (pkgAcquire &) fetcher {
2820 - (pkgSourceList &) list {
2824 - (NSArray *) packages {
2828 - (NSArray *) sources {
2829 return [sources_ allValues];
2832 - (NSArray *) issues {
2833 if (cache_->BrokenCount() == 0)
2836 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
2838 for (Package *package in packages_) {
2839 if (![package broken])
2841 pkgCache::PkgIterator pkg([package iterator]);
2843 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
2844 [entry addObject:[package name]];
2845 [issues addObject:entry];
2847 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
2851 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
2852 pkgCache::DepIterator start;
2853 pkgCache::DepIterator end;
2854 dep.GlobOr(start, end); // ++dep
2856 if (!cache_->IsImportantDep(end))
2858 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
2861 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
2862 [entry addObject:failure];
2863 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
2865 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
2866 [failure addObject:[package name]];
2868 pkgCache::PkgIterator target(start.TargetPkg());
2869 if (target->ProvidesList != 0)
2870 [failure addObject:@"?"];
2872 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
2874 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
2875 else if (!cache_[target].CandidateVerIter(cache_).end())
2876 [failure addObject:@"-"];
2877 else if (target->ProvidesList == 0)
2878 [failure addObject:@"!"];
2880 [failure addObject:@"%"];
2884 if (start.TargetVer() != 0)
2885 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
2896 - (void) reloadData { _pooled
2897 @synchronized (self) {
2919 apr_pool_clear(pool_);
2920 NSRecycleZone(zone_);
2922 int chk(creat("/tmp/cydia.chk", 0644));
2927 if (!cache_.Open(progress_, true)) {
2929 if (!_error->PopMessage(error))
2932 lprintf("cache_.Open():[%s]\n", error.c_str());
2934 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
2935 [delegate_ repairWithSelector:@selector(configure)];
2936 else if (error == "The package lists or status file could not be parsed or opened.")
2937 [delegate_ repairWithSelector:@selector(update)];
2938 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
2939 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
2940 // else if (error == "The list of sources could not be read.")
2941 else _assert(false);
2947 unlink("/tmp/cydia.chk");
2949 now_ = [[NSDate date] retain];
2951 policy_ = new pkgDepCache::Policy();
2952 records_ = new pkgRecords(cache_);
2953 resolver_ = new pkgProblemResolver(cache_);
2954 fetcher_ = new pkgAcquire(&status_);
2957 list_ = new pkgSourceList();
2958 _assert(list_->ReadMainList());
2960 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
2961 _assert(pkgApplyStatus(cache_));
2963 if (cache_->BrokenCount() != 0) {
2964 _assert(pkgFixBroken(cache_));
2965 _assert(cache_->BrokenCount() == 0);
2966 _assert(pkgMinimizeUpgrade(cache_));
2971 std::string lists(_config->FindDir("Dir::State::lists"));
2973 [sources_ removeAllObjects];
2974 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
2975 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
2976 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
2977 if (debPackagesIndex *packages = dynamic_cast<debPackagesIndex *>(*index))
2979 setObject:[[[Source alloc] initWithMetaIndex:*source] autorelease]
2980 forKey:[NSString stringWithFormat:@"%s%s",
2982 URItoFileName(packages->IndexURI("Packages")).c_str()
2989 [packages_ removeAllObjects];
2991 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
2992 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
2993 [packages_ addObject:package];
2995 [packages_ sortUsingSelector:@selector(compareByName:)];
2998 _config->Set("Acquire::http::Timeout", 15);
2999 _config->Set("Acquire::http::MaxParallel", 4);
3002 - (void) configure {
3003 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3004 system([dpkg UTF8String]);
3012 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3013 _assert(!_error->PendingError());
3016 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3019 public pkgArchiveCleaner
3022 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3027 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3029 while (_error->PopMessage(error))
3030 lprintf("ArchiveCleaner: %s\n", error.c_str());
3035 pkgRecords records(cache_);
3037 lock_ = new FileFd();
3038 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3039 _assert(!_error->PendingError());
3042 // XXX: explain this with an error message
3043 _assert(list.ReadMainList());
3045 manager_ = (_system->CreatePM(cache_));
3046 _assert(manager_->GetArchives(fetcher_, &list, &records));
3047 _assert(!_error->PendingError());
3051 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3053 _assert(list.ReadMainList());
3054 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3055 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3058 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3063 bool failed = false;
3064 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3065 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3068 std::string uri = (*item)->DescURI();
3069 std::string error = (*item)->ErrorText;
3071 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3074 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3075 withObject:[NSArray arrayWithObjects:
3076 [NSString stringWithUTF8String:error.c_str()],
3088 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3090 if (_error->PendingError()) {
3095 if (result == pkgPackageManager::Failed) {
3100 if (result != pkgPackageManager::Completed) {
3105 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3107 _assert(list.ReadMainList());
3108 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3109 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3112 if (![before isEqualToArray:after])
3117 _assert(pkgDistUpgrade(cache_));
3121 [self updateWithStatus:status_];
3124 - (void) updateWithStatus:(Status &)status {
3126 _assert(list.ReadMainList());
3129 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3130 _assert(!_error->PendingError());
3132 pkgAcquire fetcher(&status);
3133 _assert(list.GetIndexes(&fetcher));
3135 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3136 bool failed = false;
3137 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3138 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3139 (*item)->Finished();
3143 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3144 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3145 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3148 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3153 - (void) setDelegate:(id)delegate {
3154 delegate_ = delegate;
3155 status_.setDelegate(delegate);
3156 progress_.setDelegate(delegate);
3159 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3160 if (const char *name = file.FileName())
3161 if (Source *source = [sources_ objectForKey:[NSString stringWithUTF8String:name]])
3169 /* PopUp Windows {{{ */
3170 @interface PopUpView : UIView {
3171 _transient id delegate_;
3172 UITransitionView *transition_;
3177 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3181 @implementation PopUpView
3184 [transition_ setDelegate:nil];
3185 [transition_ release];
3191 [transition_ transition:UITransitionPushFromTop toView:nil];
3194 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3195 if (from != nil && to == nil)
3196 [self removeFromSuperview];
3199 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3200 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3201 delegate_ = delegate;
3203 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3204 [self addSubview:transition_];
3206 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3208 [view addSubview:self];
3210 [transition_ setDelegate:self];
3212 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3213 [transition_ transition:UITransitionNone toView:blank];
3214 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3222 /* Mail Composition {{{ */
3223 @interface MailToView : PopUpView {
3224 MailComposeController *controller_;
3227 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3231 @implementation MailToView
3234 [controller_ release];
3238 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3242 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3243 NSLog(@"did:%@", delivery);
3244 // [UIApp setStatusBarShowsProgress:NO];
3245 if ([controller error]){
3246 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3247 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3248 [mailAlertSheet setBodyText:[controller error]];
3249 [mailAlertSheet popupAlertAnimated:YES];
3253 - (void) showError {
3254 NSLog(@"%@", [controller_ error]);
3255 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3256 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3257 [mailAlertSheet setBodyText:[controller_ error]];
3258 [mailAlertSheet popupAlertAnimated:YES];
3261 - (void) deliverMessage { _pooled
3265 if (![controller_ deliverMessage])
3266 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3269 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3270 if ([controller_ needsDelivery])
3271 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3276 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3277 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3278 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3279 [controller_ setDelegate:self];
3280 [controller_ initializeUI];
3281 [controller_ setupForURL:url];
3283 UIView *view([controller_ view]);
3284 [overlay_ addSubview:view];
3292 /* Confirmation View {{{ */
3293 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3294 if (!iterator.end())
3295 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3296 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3298 pkgCache::PkgIterator package(dep.TargetPkg());
3301 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3308 @protocol ConfirmationViewDelegate
3314 @interface ConfirmationView : BrowserView {
3315 _transient Database *database_;
3316 UIActionSheet *essential_;
3323 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3327 @implementation ConfirmationView
3334 if (essential_ != nil)
3335 [essential_ release];
3341 [book_ popFromSuperviewAnimated:YES];
3344 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3345 NSString *context([sheet context]);
3347 if ([context isEqualToString:@"remove"]) {
3355 [delegate_ confirm];
3362 } else if ([context isEqualToString:@"unable"]) {
3366 [super alertSheet:sheet buttonClicked:button];
3369 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3370 [super webView:sender didClearWindowObject:window forFrame:frame];
3371 [window setValue:changes_ forKey:@"changes"];
3372 [window setValue:issues_ forKey:@"issues"];
3373 [window setValue:sizes_ forKey:@"sizes"];
3376 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3377 if ((self = [super initWithBook:book]) != nil) {
3378 database_ = database;
3380 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3381 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3382 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3383 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3384 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3388 pkgDepCache::Policy *policy([database_ policy]);
3390 pkgCacheFile &cache([database_ cache]);
3391 NSArray *packages = [database_ packages];
3392 for (Package *package in packages) {
3393 pkgCache::PkgIterator iterator = [package iterator];
3394 pkgDepCache::StateCache &state(cache[iterator]);
3396 NSString *name([package name]);
3398 if (state.NewInstall())
3399 [installing addObject:name];
3400 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3401 [reinstalling addObject:name];
3402 else if (state.Upgrade())
3403 [upgrading addObject:name];
3404 else if (state.Downgrade())
3405 [downgrading addObject:name];
3406 else if (state.Delete()) {
3407 if ([package essential])
3409 [removing addObject:name];
3412 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3413 substrate_ |= DepSubstrate(iterator.CurrentVer());
3418 else if (Advanced_ || true) {
3419 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3421 essential_ = [[UIActionSheet alloc]
3422 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3423 buttons:[NSArray arrayWithObjects:
3424 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3425 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3427 defaultButtonIndex:0
3433 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3435 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3437 essential_ = [[UIActionSheet alloc]
3438 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3439 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3440 defaultButtonIndex:0
3445 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3448 changes_ = [[NSArray alloc] initWithObjects:
3456 issues_ = [database_ issues];
3458 issues_ = [issues_ retain];
3460 sizes_ = [[NSArray alloc] initWithObjects:
3461 SizeString([database_ fetcher].FetchNeeded()),
3462 SizeString([database_ fetcher].PartialPresent()),
3463 SizeString([database_ cache]->UsrSize()),
3466 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3470 - (NSString *) backButtonTitle {
3471 return CYLocalize("CONFIRM");
3474 - (NSString *) leftButtonTitle {
3475 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3478 - (id) rightButtonTitle {
3479 return issues_ != nil ? nil : [super rightButtonTitle];
3482 - (id) _rightButtonTitle {
3483 #if AlwaysReload || IgnoreInstall
3484 return [super _rightButtonTitle];
3486 return CYLocalize("CONFIRM");
3490 - (void) _leftButtonClicked {
3495 - (void) _rightButtonClicked {
3497 return [super _rightButtonClicked];
3499 if (essential_ != nil)
3500 [essential_ popupAlertAnimated:YES];
3504 [delegate_ confirm];
3512 /* Progress Data {{{ */
3513 @interface ProgressData : NSObject {
3519 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3526 @implementation ProgressData
3528 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3529 if ((self = [super init]) != nil) {
3530 selector_ = selector;
3550 /* Progress View {{{ */
3551 @interface ProgressView : UIView <
3552 ConfigurationDelegate,
3555 _transient Database *database_;
3557 UIView *background_;
3558 UITransitionView *transition_;
3560 UINavigationBar *navbar_;
3561 UIProgressBar *progress_;
3562 UITextView *output_;
3563 UITextLabel *status_;
3564 UIPushButton *close_;
3567 SHA1SumValue springlist_;
3568 SHA1SumValue notifyconf_;
3569 SHA1SumValue sandplate_;
3572 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3574 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3575 - (void) setContentView:(UIView *)view;
3578 - (void) _retachThread;
3579 - (void) _detachNewThreadData:(ProgressData *)data;
3580 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3586 @protocol ProgressViewDelegate
3587 - (void) progressViewIsComplete:(ProgressView *)sender;
3590 @implementation ProgressView
3593 [transition_ setDelegate:nil];
3594 [navbar_ setDelegate:nil];
3597 if (background_ != nil)
3598 [background_ release];
3599 [transition_ release];
3602 [progress_ release];
3609 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3610 if (bootstrap_ && from == overlay_ && to == view_)
3614 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3615 if ((self = [super initWithFrame:frame]) != nil) {
3616 database_ = database;
3617 delegate_ = delegate;
3619 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3620 [transition_ setDelegate:self];
3622 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3625 [overlay_ setBackgroundColor:[UIColor blackColor]];
3627 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3628 [background_ setBackgroundColor:[UIColor blackColor]];
3629 [self addSubview:background_];
3632 [self addSubview:transition_];
3634 CGSize navsize = [UINavigationBar defaultSize];
3635 CGRect navrect = {{0, 0}, navsize};
3637 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3638 [overlay_ addSubview:navbar_];
3640 [navbar_ setBarStyle:1];
3641 [navbar_ setDelegate:self];
3643 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3644 [navbar_ pushNavigationItem:navitem];
3646 CGRect bounds = [overlay_ bounds];
3647 CGSize prgsize = [UIProgressBar defaultSize];
3650 (bounds.size.width - prgsize.width) / 2,
3651 bounds.size.height - prgsize.height - 20
3654 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3655 [progress_ setStyle:0];
3657 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3659 bounds.size.height - prgsize.height - 50,
3660 bounds.size.width - 20,
3664 [status_ setColor:[UIColor whiteColor]];
3665 [status_ setBackgroundColor:[UIColor clearColor]];
3667 [status_ setCentersHorizontally:YES];
3668 //[status_ setFont:font];
3671 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3673 navrect.size.height + 20,
3674 bounds.size.width - 20,
3675 bounds.size.height - navsize.height - 62 - navrect.size.height
3679 //[output_ setTextFont:@"Courier New"];
3680 [output_ setTextSize:12];
3682 [output_ setTextColor:[UIColor whiteColor]];
3683 [output_ setBackgroundColor:[UIColor clearColor]];
3685 [output_ setMarginTop:0];
3686 [output_ setAllowsRubberBanding:YES];
3687 [output_ setEditable:NO];
3689 [overlay_ addSubview:output_];
3691 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3693 bounds.size.height - prgsize.height - 50,
3694 bounds.size.width - 20,
3698 [close_ setAutosizesToFit:NO];
3699 [close_ setDrawsShadow:YES];
3700 [close_ setStretchBackground:YES];
3701 [close_ setEnabled:YES];
3703 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3704 [close_ setTitleFont:bold];
3706 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3707 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3708 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3712 - (void) setContentView:(UIView *)view {
3713 view_ = [view retain];
3716 - (void) resetView {
3717 [transition_ transition:6 toView:view_];
3720 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3721 NSString *context([sheet context]);
3723 if ([context isEqualToString:@"error"])
3725 else if ([context isEqualToString:@"conffile"]) {
3726 FILE *input = [database_ input];
3730 fprintf(input, "N\n");
3734 fprintf(input, "Y\n");
3745 - (void) closeButtonPushed {
3754 [delegate_ suspendWithAnimation:YES];
3758 system("launchctl stop com.apple.SpringBoard");
3762 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
3771 - (void) _retachThread {
3772 UINavigationItem *item = [navbar_ topItem];
3773 [item setTitle:CYLocalize("COMPLETE")];
3775 [overlay_ addSubview:close_];
3776 [progress_ removeFromSuperview];
3777 [status_ removeFromSuperview];
3779 [delegate_ progressViewIsComplete:self];
3782 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
3783 MMap mmap(file, MMap::ReadOnly);
3785 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3786 if (!(sandplate_ == sha1.Result()))
3791 FileFd file(NotifyConfig_, FileFd::ReadOnly);
3792 MMap mmap(file, MMap::ReadOnly);
3794 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3795 if (!(notifyconf_ == sha1.Result()))
3800 FileFd file(SpringBoard_, FileFd::ReadOnly);
3801 MMap mmap(file, MMap::ReadOnly);
3803 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3804 if (!(springlist_ == sha1.Result()))
3809 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
3810 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
3811 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
3812 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
3813 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
3816 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
3818 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
3819 [cache autorelease];
3821 NSFileManager *manager = [NSFileManager defaultManager];
3822 NSError *error = nil;
3824 id system = [cache objectForKey:@"System"];
3829 if (stat(Cache_, &info) == -1)
3832 [system removeAllObjects];
3834 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
3835 for (NSString *app in apps)
3836 if ([app hasSuffix:@".app"]) {
3837 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
3838 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
3839 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
3841 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
3842 [info setObject:path forKey:@"Path"];
3843 [info setObject:@"System" forKey:@"ApplicationType"];
3844 [system addInfoDictionary:info];
3850 [cache writeToFile:@Cache_ atomically:YES];
3852 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
3854 if (chmod(Cache_, info.st_mode) == -1)
3858 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
3861 notify_post("com.apple.mobile.application_installed");
3863 [delegate_ setStatusBarShowsProgress:NO];
3866 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
3867 [[data target] performSelector:[data selector] withObject:[data object]];
3870 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
3873 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
3874 UINavigationItem *item = [navbar_ topItem];
3875 [item setTitle:title];
3877 [status_ setText:nil];
3878 [output_ setText:@""];
3879 [progress_ setProgress:0];
3881 [close_ removeFromSuperview];
3882 [overlay_ addSubview:progress_];
3883 [overlay_ addSubview:status_];
3885 [delegate_ setStatusBarShowsProgress:YES];
3889 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
3890 MMap mmap(file, MMap::ReadOnly);
3892 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3893 sandplate_ = sha1.Result();
3897 FileFd file(NotifyConfig_, FileFd::ReadOnly);
3898 MMap mmap(file, MMap::ReadOnly);
3900 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3901 notifyconf_ = sha1.Result();
3905 FileFd file(SpringBoard_, FileFd::ReadOnly);
3906 MMap mmap(file, MMap::ReadOnly);
3908 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3909 springlist_ = sha1.Result();
3912 [transition_ transition:6 toView:overlay_];
3915 detachNewThreadSelector:@selector(_detachNewThreadData:)
3917 withObject:[[ProgressData alloc]
3918 initWithSelector:selector
3925 - (void) repairWithSelector:(SEL)selector {
3927 detachNewThreadSelector:selector
3930 title:CYLocalize("REPAIRING")
3934 - (void) setConfigurationData:(NSString *)data {
3936 performSelectorOnMainThread:@selector(_setConfigurationData:)
3942 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
3943 Package *package = id == nil ? nil : [database_ packageWithName:id];
3945 UIActionSheet *sheet = [[[UIActionSheet alloc]
3946 initWithTitle:(package == nil ? id : [package name])
3947 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3948 defaultButtonIndex:0
3953 [sheet setBodyText:error];
3954 [sheet popupAlertAnimated:YES];
3957 - (void) setProgressTitle:(NSString *)title {
3959 performSelectorOnMainThread:@selector(_setProgressTitle:)
3965 - (void) setProgressPercent:(float)percent {
3967 performSelectorOnMainThread:@selector(_setProgressPercent:)
3968 withObject:[NSNumber numberWithFloat:percent]
3973 - (void) startProgress {
3976 - (void) addProgressOutput:(NSString *)output {
3978 performSelectorOnMainThread:@selector(_addProgressOutput:)
3984 - (bool) isCancelling:(size_t)received {
3988 - (void) _setConfigurationData:(NSString *)data {
3989 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
3991 _assert(conffile_r(data));
3993 NSString *ofile = conffile_r[1];
3994 //NSString *nfile = conffile_r[2];
3996 UIActionSheet *sheet = [[[UIActionSheet alloc]
3997 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
3998 buttons:[NSArray arrayWithObjects:
3999 CYLocalize("KEEP_OLD_COPY"),
4000 CYLocalize("ACCEPT_NEW_COPY"),
4001 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
4003 defaultButtonIndex:0
4008 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4009 [sheet popupAlertAnimated:YES];
4012 - (void) _setProgressTitle:(NSString *)title {
4013 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4014 for (size_t i(0), e([words count]); i != e; ++i) {
4015 NSString *word([words objectAtIndex:i]);
4016 if (Package *package = [database_ packageWithName:word])
4017 [words replaceObjectAtIndex:i withObject:[package name]];
4020 [status_ setText:[words componentsJoinedByString:@" "]];
4023 - (void) _setProgressPercent:(NSNumber *)percent {
4024 [progress_ setProgress:[percent floatValue]];
4027 - (void) _addProgressOutput:(NSString *)output {
4028 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4029 CGSize size = [output_ contentSize];
4030 CGRect rect = {{0, size.height}, {size.width, 0}};
4031 [output_ scrollRectToVisible:rect animated:YES];
4034 - (BOOL) isRunning {
4041 /* Package Cell {{{ */
4042 @interface PackageCell : UITableCell {
4045 NSString *description_;
4052 UITextLabel *status_;
4056 - (PackageCell *) init;
4057 - (void) setPackage:(Package *)package;
4059 + (int) heightForPackage:(Package *)package;
4063 @implementation PackageCell
4065 - (void) clearPackage {
4076 if (description_ != nil) {
4077 [description_ release];
4081 if (source_ != nil) {
4086 if (badge_ != nil) {
4096 [self clearPackage];
4103 - (PackageCell *) init {
4104 if ((self = [super init]) != nil) {
4106 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4107 [status_ setBackgroundColor:[UIColor clearColor]];
4108 [status_ setFont:small];
4113 - (void) setPackage:(Package *)package {
4114 [self clearPackage];
4116 Source *source = [package source];
4118 icon_ = [[package icon] retain];
4119 name_ = [[package name] retain];
4120 description_ = [[package tagline] retain];
4121 commercial_ = [package isCommercial];
4123 package_ = [package retain];
4125 NSString *label = nil;
4126 bool trusted = false;
4128 if (source != nil) {
4129 label = [source label];
4130 trusted = [source trusted];
4131 } else if ([[package id] isEqualToString:@"firmware"])
4132 label = CYLocalize("APPLE");
4134 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4136 NSString *from(label);
4138 NSString *section = [package simpleSection];
4139 if (section != nil && ![section isEqualToString:label]) {
4140 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4141 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4144 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4145 source_ = [from retain];
4147 if (NSString *purpose = [package primaryPurpose])
4148 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4149 badge_ = [badge_ retain];
4152 if (NSString *mode = [package mode]) {
4153 [badge_ setImage:[UIImage applicationImageNamed:
4154 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4157 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4158 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4159 } else if ([package half]) {
4160 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4161 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4162 [status_ setColor:[UIColor redColor]];
4164 [badge_ setImage:nil];
4165 [status_ setText:nil];
4172 - (void) drawRect:(CGRect)rect {
4176 if (NSString *mode = [package_ mode]) {
4177 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4178 color = remove ? RemovingColor_ : InstallingColor_;
4180 color = [UIColor whiteColor];
4182 [self setBackgroundColor:color];
4186 [super drawRect:rect];
4189 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4191 CGContextRef context(UIGraphicsGetCurrentContext());
4192 [[self backgroundColor] set];
4194 back.size.height -= 1;
4195 CGContextFillRect(context, back);
4198 [super drawBackgroundInRect:rect withFade:fade];
4201 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4204 rect.size = [icon_ size];
4206 rect.size.width /= 2;
4207 rect.size.height /= 2;
4209 rect.origin.x = 25 - rect.size.width / 2;
4210 rect.origin.y = 25 - rect.size.height / 2;
4212 [icon_ drawInRect:rect];
4215 if (badge_ != nil) {
4216 CGSize size = [badge_ size];
4218 [badge_ drawAtPoint:CGPointMake(
4219 36 - size.width / 2,
4220 36 - size.height / 2
4228 UISetColor(commercial_ ? Purple_ : Black_);
4229 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4230 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4233 UISetColor(commercial_ ? Purplish_ : Gray_);
4234 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4236 [super drawContentInRect:rect selected:selected];
4239 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4241 [super setSelected:selected withFade:fade];
4244 + (int) heightForPackage:(Package *)package {
4245 NSString *tagline([package tagline]);
4246 int height = tagline == nil || [tagline length] == 0 ? -17 : 0;
4248 if ([package hasMode] || [package half])
4257 /* Section Cell {{{ */
4258 @interface SectionCell : UISimpleTableCell {
4263 _UISwitchSlider *switch_;
4268 - (void) setSection:(Section *)section editing:(BOOL)editing;
4272 @implementation SectionCell
4274 - (void) clearSection {
4275 if (section_ != nil) {
4285 if (count_ != nil) {
4292 [self clearSection];
4299 if ((self = [super init]) != nil) {
4300 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4302 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4303 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4307 - (void) onSwitch:(id)sender {
4308 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4309 if (metadata == nil) {
4310 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4311 [Sections_ setObject:metadata forKey:section_];
4315 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4318 - (void) setSection:(Section *)section editing:(BOOL)editing {
4319 if (editing != editing_) {
4321 [switch_ removeFromSuperview];
4323 [self addSubview:switch_];
4327 [self clearSection];
4329 if (section == nil) {
4330 name_ = [CYLocalize("ALL_PACKAGES") retain];
4333 section_ = [section name];
4334 if (section_ != nil)
4335 section_ = [section_ retain];
4336 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4337 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4340 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4344 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4345 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4352 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4354 CGSize size = [count_ sizeWithFont:Font14_];
4358 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4360 [super drawContentInRect:rect selected:selected];
4366 /* File Table {{{ */
4367 @interface FileTable : RVPage {
4368 _transient Database *database_;
4371 NSMutableArray *files_;
4375 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4376 - (void) setPackage:(Package *)package;
4380 @implementation FileTable
4383 if (package_ != nil)
4392 - (int) numberOfRowsInTable:(UITable *)table {
4393 return files_ == nil ? 0 : [files_ count];
4396 - (float) table:(UITable *)table heightForRow:(int)row {
4400 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4401 if (reusing == nil) {
4402 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4403 UIFont *font = [UIFont systemFontOfSize:16];
4404 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4406 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4410 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4414 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4415 if ((self = [super initWithBook:book]) != nil) {
4416 database_ = database;
4418 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4420 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4421 [self addSubview:list_];
4423 UITableColumn *column = [[[UITableColumn alloc]
4424 initWithTitle:CYLocalize("NAME")
4426 width:[self frame].size.width
4429 [list_ setDataSource:self];
4430 [list_ setSeparatorStyle:1];
4431 [list_ addTableColumn:column];
4432 [list_ setDelegate:self];
4433 [list_ setReusesTableCells:YES];
4437 - (void) setPackage:(Package *)package {
4438 if (package_ != nil) {
4439 [package_ autorelease];
4448 [files_ removeAllObjects];
4450 if (package != nil) {
4451 package_ = [package retain];
4452 name_ = [[package id] retain];
4454 if (NSArray *files = [package files])
4455 [files_ addObjectsFromArray:files];
4457 if ([files_ count] != 0) {
4458 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4459 [files_ removeObjectAtIndex:0];
4460 [files_ sortUsingSelector:@selector(compareByPath:)];
4462 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4463 [stack addObject:@"/"];
4465 for (int i(0), e([files_ count]); i != e; ++i) {
4466 NSString *file = [files_ objectAtIndex:i];
4467 while (![file hasPrefix:[stack lastObject]])
4468 [stack removeLastObject];
4469 NSString *directory = [stack lastObject];
4470 [stack addObject:[file stringByAppendingString:@"/"]];
4471 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4472 ([stack count] - 2) * 3, "",
4473 [file substringFromIndex:[directory length]]
4482 - (void) resetViewAnimated:(BOOL)animated {
4483 [list_ resetViewAnimated:animated];
4486 - (void) reloadData {
4487 [self setPackage:[database_ packageWithName:name_]];
4488 [self reloadButtons];
4491 - (NSString *) title {
4492 return CYLocalize("INSTALLED_FILES");
4495 - (NSString *) backButtonTitle {
4496 return CYLocalize("FILES");
4501 /* Package View {{{ */
4502 @interface PackageView : BrowserView {
4503 _transient Database *database_;
4507 NSMutableArray *buttons_;
4510 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4511 - (void) setPackage:(Package *)package;
4515 @implementation PackageView
4518 if (package_ != nil)
4527 if ([self retainCount] == 1)
4528 [delegate_ setPackageView:self];
4532 /* XXX: this is not safe at all... localization of /fail/ */
4533 - (void) _clickButtonWithName:(NSString *)name {
4534 if ([name isEqualToString:CYLocalize("CLEAR")])
4535 [delegate_ clearPackage:package_];
4536 else if ([name isEqualToString:CYLocalize("INSTALL")])
4537 [delegate_ installPackage:package_];
4538 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4539 [delegate_ installPackage:package_];
4540 else if ([name isEqualToString:CYLocalize("REMOVE")])
4541 [delegate_ removePackage:package_];
4542 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4543 [delegate_ installPackage:package_];
4544 else _assert(false);
4547 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4548 NSString *context([sheet context]);
4550 if ([context isEqualToString:@"modify"]) {
4551 int count = [buttons_ count];
4552 _assert(count != 0);
4553 _assert(button <= count + 1);
4555 if (count != button - 1)
4556 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4560 [super alertSheet:sheet buttonClicked:button];
4563 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4564 return [super webView:sender didFinishLoadForFrame:frame];
4567 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4568 [super webView:sender didClearWindowObject:window forFrame:frame];
4569 [window setValue:package_ forKey:@"package"];
4572 - (bool) _allowJavaScriptPanel {
4577 - (void) __rightButtonClicked {
4578 int count = [buttons_ count];
4579 _assert(count != 0);
4582 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4584 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4585 [buttons addObjectsFromArray:buttons_];
4586 [buttons addObject:CYLocalize("CANCEL")];
4588 [delegate_ slideUp:[[[UIActionSheet alloc]
4591 defaultButtonIndex:([buttons count] - 1)
4598 - (void) _rightButtonClicked {
4600 [super _rightButtonClicked];
4602 [self __rightButtonClicked];
4606 - (id) _rightButtonTitle {
4607 int count = [buttons_ count];
4608 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4611 - (NSString *) backButtonTitle {
4615 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4616 if ((self = [super initWithBook:book]) != nil) {
4617 database_ = database;
4618 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4619 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4623 - (void) setPackage:(Package *)package {
4624 if (package_ != nil) {
4625 [package_ autorelease];
4634 [buttons_ removeAllObjects];
4636 if (package != nil) {
4637 package_ = [package retain];
4638 name_ = [[package id] retain];
4639 commercial_ = [package isCommercial];
4641 if ([package_ mode] != nil)
4642 [buttons_ addObject:CYLocalize("CLEAR")];
4643 if ([package_ source] == nil);
4644 else if ([package_ upgradableAndEssential:NO])
4645 [buttons_ addObject:CYLocalize("UPGRADE")];
4646 else if ([package_ installed] == nil)
4647 [buttons_ addObject:CYLocalize("INSTALL")];
4649 [buttons_ addObject:CYLocalize("REINSTALL")];
4650 if ([package_ installed] != nil)
4651 [buttons_ addObject:CYLocalize("REMOVE")];
4653 if (special_ != NULL) {
4654 CGRect frame([webview_ frame]);
4655 frame.size.width = 320;
4656 frame.size.height = 0;
4657 [webview_ setFrame:frame];
4659 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4662 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4664 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4666 [self setFinishHook:nil];
4667 [self setPopupHook:nil];
4670 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
4671 [super callFunction:special_];
4675 [self reloadButtons];
4678 - (bool) isLoading {
4679 return commercial_ ? [super isLoading] : false;
4682 - (void) reloadData {
4683 [self setPackage:[database_ packageWithName:name_]];
4688 /* Package Table {{{ */
4689 @interface PackageTable : RVPage {
4690 _transient Database *database_;
4692 NSMutableArray *packages_;
4693 NSMutableArray *sections_;
4694 UISectionList *list_;
4697 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
4699 - (void) setDelegate:(id)delegate;
4701 - (void) reloadData;
4702 - (void) resetCursor;
4704 - (UISectionList *) list;
4706 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4710 @implementation PackageTable
4713 [list_ setDataSource:nil];
4716 [packages_ release];
4717 [sections_ release];
4722 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4723 return [sections_ count];
4726 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4727 return [[sections_ objectAtIndex:section] name];
4730 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4731 return [[sections_ objectAtIndex:section] row];
4734 - (int) numberOfRowsInTable:(UITable *)table {
4735 return [packages_ count];
4738 - (float) table:(UITable *)table heightForRow:(int)row {
4739 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
4742 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4744 reusing = [[[PackageCell alloc] init] autorelease];
4745 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
4749 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
4753 - (void) tableRowSelected:(NSNotification *)notification {
4754 int row = [[notification object] selectedRow];
4758 Package *package = [packages_ objectAtIndex:row];
4759 package = [database_ packageWithName:[package id]];
4760 PackageView *view([delegate_ packageView]);
4761 [view setPackage:package];
4762 [view setDelegate:delegate_];
4763 [book_ pushPage:view];
4766 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
4767 if ((self = [super initWithBook:book]) != nil) {
4768 database_ = database;
4769 title_ = [title retain];
4771 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
4772 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
4774 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
4775 [list_ setDataSource:self];
4777 UITableColumn *column = [[[UITableColumn alloc]
4778 initWithTitle:CYLocalize("NAME")
4780 width:[self frame].size.width
4783 UITable *table = [list_ table];
4784 [table setSeparatorStyle:1];
4785 [table addTableColumn:column];
4786 [table setDelegate:self];
4787 [table setReusesTableCells:YES];
4789 [self addSubview:list_];
4791 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4792 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4796 - (void) setDelegate:(id)delegate {
4797 delegate_ = delegate;
4800 - (bool) hasPackage:(Package *)package {
4804 - (void) reloadData {
4805 NSArray *packages = [database_ packages];
4807 [packages_ removeAllObjects];
4808 [sections_ removeAllObjects];
4810 _profile(PackageTable$reloadData$Filter)
4811 for (Package *package in packages)
4812 if ([self hasPackage:package])
4813 [packages_ addObject:package];
4816 Section *section = nil;
4818 _profile(PackageTable$reloadData$Section)
4819 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
4823 _profile(PackageTable$reloadData$Section$Package)
4824 package = [packages_ objectAtIndex:offset];
4825 index = [package index];
4828 if (section == nil || [section index] != index) {
4829 _profile(PackageTable$reloadData$Section$Allocate)
4830 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
4833 _profile(PackageTable$reloadData$Section$Add)
4834 [sections_ addObject:section];
4838 [section addToCount];
4842 _profile(PackageTable$reloadData$List)
4847 - (NSString *) title {
4851 - (void) resetViewAnimated:(BOOL)animated {
4852 [list_ resetViewAnimated:animated];
4855 - (void) resetCursor {
4856 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
4859 - (UISectionList *) list {
4863 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
4864 [list_ setShouldHideHeaderInShortLists:hide];
4869 /* Filtered Package Table {{{ */
4870 @interface FilteredPackageTable : PackageTable {
4876 - (void) setObject:(id)object;
4878 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
4882 @implementation FilteredPackageTable
4890 - (void) setObject:(id)object {
4896 object_ = [object retain];
4899 - (bool) hasPackage:(Package *)package {
4900 _profile(FilteredPackageTable$hasPackage)
4901 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
4905 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
4906 if ((self = [super initWithBook:book database:database title:title]) != nil) {
4908 object_ = object == nil ? nil : [object retain];
4910 /* XXX: this is an unsafe optimization of doomy hell */
4911 Method method = class_getInstanceMethod([Package class], filter);
4912 imp_ = method_getImplementation(method);
4913 _assert(imp_ != NULL);
4922 /* Add Source View {{{ */
4923 @interface AddSourceView : RVPage {
4924 _transient Database *database_;
4927 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4931 @implementation AddSourceView
4933 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4934 if ((self = [super initWithBook:book]) != nil) {
4935 database_ = database;
4941 /* Source Cell {{{ */
4942 @interface SourceCell : UITableCell {
4945 NSString *description_;
4951 - (SourceCell *) initWithSource:(Source *)source;
4955 @implementation SourceCell
4960 [description_ release];
4965 - (SourceCell *) initWithSource:(Source *)source {
4966 if ((self = [super init]) != nil) {
4968 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
4970 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
4971 icon_ = [icon_ retain];
4973 origin_ = [[source name] retain];
4974 label_ = [[source uri] retain];
4975 description_ = [[source description] retain];
4979 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4981 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
4988 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4992 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4996 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4998 [super drawContentInRect:rect selected:selected];
5003 /* Source Table {{{ */
5004 @interface SourceTable : RVPage {
5005 _transient Database *database_;
5006 UISectionList *list_;
5007 NSMutableArray *sources_;
5008 UIActionSheet *alert_;
5012 UIProgressHUD *hud_;
5015 //NSURLConnection *installer_;
5016 NSURLConnection *trivial_bz2_;
5017 NSURLConnection *trivial_gz_;
5018 //NSURLConnection *automatic_;
5023 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5027 @implementation SourceTable
5029 - (void) _deallocConnection:(NSURLConnection *)connection {
5030 if (connection != nil) {
5031 [connection cancel];
5032 //[connection setDelegate:nil];
5033 [connection release];
5038 [[list_ table] setDelegate:nil];
5039 [list_ setDataSource:nil];
5048 //[self _deallocConnection:installer_];
5049 [self _deallocConnection:trivial_gz_];
5050 [self _deallocConnection:trivial_bz2_];
5051 //[self _deallocConnection:automatic_];
5058 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5059 return offset_ == 0 ? 1 : 2;
5062 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5063 switch (section + (offset_ == 0 ? 1 : 0)) {
5064 case 0: return CYLocalize("ENTERED_BY_USER");
5065 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5073 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5074 switch (section + (offset_ == 0 ? 1 : 0)) {
5076 case 1: return offset_;
5084 - (int) numberOfRowsInTable:(UITable *)table {
5085 return [sources_ count];
5088 - (float) table:(UITable *)table heightForRow:(int)row {
5089 Source *source = [sources_ objectAtIndex:row];
5090 return [source description] == nil ? 56 : 73;
5093 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5094 Source *source = [sources_ objectAtIndex:row];
5095 // XXX: weird warning, stupid selectors ;P
5096 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5099 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5103 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5107 - (void) tableRowSelected:(NSNotification*)notification {
5108 UITable *table([list_ table]);
5109 int row([table selectedRow]);
5113 Source *source = [sources_ objectAtIndex:row];
5115 PackageTable *packages = [[[FilteredPackageTable alloc]
5118 title:[source label]
5119 filter:@selector(isVisibleInSource:)
5123 [packages setDelegate:delegate_];
5125 [book_ pushPage:packages];
5128 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5129 Source *source = [sources_ objectAtIndex:row];
5130 return [source record] != nil;
5133 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5134 [[list_ table] setDeleteConfirmationRow:row];
5137 - (void) table:(UITable *)table deleteRow:(int)row {
5138 Source *source = [sources_ objectAtIndex:row];
5139 [Sources_ removeObjectForKey:[source key]];
5140 [delegate_ syncData];
5144 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5147 @"./", @"Distribution",
5148 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5150 [delegate_ syncData];
5153 - (NSString *) getWarning {
5154 NSString *href(href_);
5155 NSRange colon([href rangeOfString:@"://"]);
5156 if (colon.location != NSNotFound)
5157 href = [href substringFromIndex:(colon.location + 3)];
5158 href = [href stringByAddingPercentEscapes];
5159 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5160 href = [href stringByCachingURLWithCurrentCDN];
5162 NSURL *url([NSURL URLWithString:href]);
5164 NSStringEncoding encoding;
5165 NSError *error(nil);
5167 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5168 return [warning length] == 0 ? nil : warning;
5172 - (void) _endConnection:(NSURLConnection *)connection {
5173 NSURLConnection **field = NULL;
5174 if (connection == trivial_bz2_)
5175 field = &trivial_bz2_;
5176 else if (connection == trivial_gz_)
5177 field = &trivial_gz_;
5178 _assert(field != NULL);
5179 [connection release];
5183 trivial_bz2_ == nil &&
5189 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5192 UIActionSheet *sheet = [[[UIActionSheet alloc]
5193 initWithTitle:CYLocalize("SOURCE_WARNING")
5194 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5195 defaultButtonIndex:0
5200 [sheet setNumberOfRows:1];
5202 [sheet setBodyText:warning];
5203 [sheet popupAlertAnimated:YES];
5206 } else if (error_ != nil) {
5207 UIActionSheet *sheet = [[[UIActionSheet alloc]
5208 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5209 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5210 defaultButtonIndex:0
5215 [sheet setBodyText:[error_ localizedDescription]];
5216 [sheet popupAlertAnimated:YES];
5218 UIActionSheet *sheet = [[[UIActionSheet alloc]
5219 initWithTitle:CYLocalize("NOT_REPOSITORY")
5220 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5221 defaultButtonIndex:0
5226 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5227 [sheet popupAlertAnimated:YES];
5230 [delegate_ setStatusBarShowsProgress:NO];
5231 [delegate_ removeProgressHUD:hud_];
5241 if (error_ != nil) {
5248 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5249 switch ([response statusCode]) {
5255 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5256 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5258 error_ = [error retain];
5259 [self _endConnection:connection];
5262 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5263 [self _endConnection:connection];
5266 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5267 NSMutableURLRequest *request = [NSMutableURLRequest
5268 requestWithURL:[NSURL URLWithString:href]
5269 cachePolicy:NSURLRequestUseProtocolCachePolicy
5270 timeoutInterval:20.0
5273 [request setHTTPMethod:method];
5275 if (Machine_ != NULL)
5276 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5277 if (UniqueID_ != nil)
5278 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5281 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5283 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5286 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5287 NSString *context([sheet context]);
5289 if ([context isEqualToString:@"source"]) {
5292 NSString *href = [[sheet textField] text];
5294 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5296 if (![href hasSuffix:@"/"])
5297 href_ = [href stringByAppendingString:@"/"];
5300 href_ = [href_ retain];
5302 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5303 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5304 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5308 hud_ = [[delegate_ addProgressHUD] retain];
5309 [hud_ setText:CYLocalize("VERIFYING_URL")];
5320 } else if ([context isEqualToString:@"trivial"])
5322 else if ([context isEqualToString:@"urlerror"])
5324 else if ([context isEqualToString:@"warning"]) {
5344 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5345 if ((self = [super initWithBook:book]) != nil) {
5346 database_ = database;
5347 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5349 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5350 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5351 [list_ setShouldHideHeaderInShortLists:NO];
5353 [self addSubview:list_];
5354 [list_ setDataSource:self];
5356 UITableColumn *column = [[UITableColumn alloc]
5357 initWithTitle:CYLocalize("NAME")
5359 width:[self frame].size.width
5362 UITable *table = [list_ table];
5363 [table setSeparatorStyle:1];
5364 [table addTableColumn:column];
5365 [table setDelegate:self];
5369 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5370 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5374 - (void) reloadData {
5376 _assert(list.ReadMainList());
5378 [sources_ removeAllObjects];
5379 [sources_ addObjectsFromArray:[database_ sources]];
5381 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5384 int count = [sources_ count];
5385 for (offset_ = 0; offset_ != count; ++offset_) {
5386 Source *source = [sources_ objectAtIndex:offset_];
5387 if ([source record] == nil)
5394 - (void) resetViewAnimated:(BOOL)animated {
5395 [list_ resetViewAnimated:animated];
5398 - (void) _leftButtonClicked {
5399 /*[book_ pushPage:[[[AddSourceView alloc]
5404 UIActionSheet *sheet = [[[UIActionSheet alloc]
5405 initWithTitle:CYLocalize("ENTER_APT_URL")
5406 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5407 defaultButtonIndex:0
5412 [sheet setNumberOfRows:1];
5414 [sheet addTextFieldWithValue:@"http://" label:@""];
5416 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5417 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5418 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5419 [traits setKeyboardType:UIKeyboardTypeURL];
5420 // XXX: UIReturnKeyDone
5421 [traits setReturnKeyType:UIReturnKeyNext];
5423 [sheet popupAlertAnimated:YES];
5426 - (void) _rightButtonClicked {
5427 UITable *table = [list_ table];
5428 BOOL editing = [table isRowDeletionEnabled];
5429 [table enableRowDeletion:!editing animated:YES];
5430 [book_ reloadButtonsForPage:self];
5433 - (NSString *) title {
5434 return CYLocalize("SOURCES");
5437 - (NSString *) leftButtonTitle {
5438 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5441 - (id) rightButtonTitle {
5442 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5445 - (UINavigationButtonStyle) rightButtonStyle {
5446 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5452 /* Installed View {{{ */
5453 @interface InstalledView : RVPage {
5454 _transient Database *database_;
5455 FilteredPackageTable *packages_;
5459 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5463 @implementation InstalledView
5466 [packages_ release];
5470 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5471 if ((self = [super initWithBook:book]) != nil) {
5472 database_ = database;
5474 packages_ = [[FilteredPackageTable alloc]
5478 filter:@selector(isInstalledAndVisible:)
5479 with:[NSNumber numberWithBool:YES]
5482 [self addSubview:packages_];
5484 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5485 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5489 - (void) resetViewAnimated:(BOOL)animated {
5490 [packages_ resetViewAnimated:animated];
5493 - (void) reloadData {
5494 [packages_ reloadData];
5497 - (void) _rightButtonClicked {
5498 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5499 [packages_ reloadData];
5501 [book_ reloadButtonsForPage:self];
5504 - (NSString *) title {
5505 return CYLocalize("INSTALLED");
5508 - (NSString *) backButtonTitle {
5509 return CYLocalize("PACKAGES");
5512 - (id) rightButtonTitle {
5513 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5516 - (UINavigationButtonStyle) rightButtonStyle {
5517 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5520 - (void) setDelegate:(id)delegate {
5521 [super setDelegate:delegate];
5522 [packages_ setDelegate:delegate];
5529 @interface HomeView : BrowserView {
5534 @implementation HomeView
5536 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5537 NSString *context([sheet context]);
5539 if ([context isEqualToString:@"about"])
5542 [super alertSheet:sheet buttonClicked:button];
5545 - (void) _leftButtonClicked {
5546 UIActionSheet *sheet = [[[UIActionSheet alloc]
5547 initWithTitle:CYLocalize("ABOUT_CYDIA")
5548 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5549 defaultButtonIndex:0
5555 @"Copyright (C) 2008-2009\n"
5556 "Jay Freeman (saurik)\n"
5557 "saurik@saurik.com\n"
5558 "http://www.saurik.com/\n"
5561 "http://www.theokorigroup.com/\n"
5563 "College of Creative Studies,\n"
5564 "University of California,\n"
5566 "http://www.ccs.ucsb.edu/"
5569 [sheet popupAlertAnimated:YES];
5572 - (NSString *) leftButtonTitle {
5573 return CYLocalize("ABOUT");
5578 /* Manage View {{{ */
5579 @interface ManageView : BrowserView {
5584 @implementation ManageView
5586 - (NSString *) title {
5587 return CYLocalize("MANAGE");
5590 - (void) _leftButtonClicked {
5591 [delegate_ askForSettings];
5594 - (NSString *) leftButtonTitle {
5595 return CYLocalize("SETTINGS");
5599 - (id) _rightButtonTitle {
5600 return Queuing_ ? CYLocalize("QUEUE") : nil;
5603 - (UINavigationButtonStyle) rightButtonStyle {
5604 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5607 - (void) _rightButtonClicked {
5612 - (bool) isLoading {
5619 #include <BrowserView.m>
5621 /* Cydia Book {{{ */
5622 @interface CYBook : RVBook <
5625 _transient Database *database_;
5626 UINavigationBar *overlay_;
5627 UINavigationBar *underlay_;
5628 UIProgressIndicator *indicator_;
5629 UITextLabel *prompt_;
5630 UIProgressBar *progress_;
5631 UINavigationButton *cancel_;
5635 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5641 @implementation CYBook
5645 [indicator_ release];
5647 [progress_ release];
5652 - (NSString *) getTitleForPage:(RVPage *)page {
5653 return [super getTitleForPage:page];
5661 [UIView beginAnimations:nil context:NULL];
5663 CGRect ovrframe = [overlay_ frame];
5664 ovrframe.origin.y = 0;
5665 [overlay_ setFrame:ovrframe];
5667 CGRect barframe = [navbar_ frame];
5668 barframe.origin.y += ovrframe.size.height;
5669 [navbar_ setFrame:barframe];
5671 CGRect trnframe = [transition_ frame];
5672 trnframe.origin.y += ovrframe.size.height;
5673 trnframe.size.height -= ovrframe.size.height;
5674 [transition_ setFrame:trnframe];
5676 [UIView endAnimations];
5678 [indicator_ startAnimation];
5679 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5680 [progress_ setProgress:0];
5683 [overlay_ addSubview:cancel_];
5686 detachNewThreadSelector:@selector(_update)
5695 [indicator_ stopAnimation];
5697 [UIView beginAnimations:nil context:NULL];
5699 CGRect ovrframe = [overlay_ frame];
5700 ovrframe.origin.y = -ovrframe.size.height;
5701 [overlay_ setFrame:ovrframe];
5703 CGRect barframe = [navbar_ frame];
5704 barframe.origin.y -= ovrframe.size.height;
5705 [navbar_ setFrame:barframe];
5707 CGRect trnframe = [transition_ frame];
5708 trnframe.origin.y -= ovrframe.size.height;
5709 trnframe.size.height += ovrframe.size.height;
5710 [transition_ setFrame:trnframe];
5712 [UIView commitAnimations];
5714 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5717 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
5718 if ((self = [super initWithFrame:frame]) != nil) {
5719 database_ = database;
5721 CGRect ovrrect = [navbar_ bounds];
5722 ovrrect.size.height = [UINavigationBar defaultSize].height;
5723 ovrrect.origin.y = -ovrrect.size.height;
5725 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5726 [self addSubview:overlay_];
5728 ovrrect.origin.y = frame.size.height;
5729 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5730 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
5731 [self addSubview:underlay_];
5733 [overlay_ setBarStyle:1];
5734 [underlay_ setBarStyle:1];
5736 int barstyle = [overlay_ _barStyle:NO];
5737 bool ugly = barstyle == 0;
5739 UIProgressIndicatorStyle style = ugly ?
5740 UIProgressIndicatorStyleMediumBrown :
5741 UIProgressIndicatorStyleMediumWhite;
5743 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
5744 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
5745 CGRect indrect = {{indoffset, indoffset}, indsize};
5747 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
5748 [indicator_ setStyle:style];
5749 [overlay_ addSubview:indicator_];
5751 CGSize prmsize = {215, indsize.height + 4};
5754 indoffset * 2 + indsize.width,
5758 unsigned(ovrrect.size.height - prmsize.height) / 2
5761 UIFont *font = [UIFont systemFontOfSize:15];
5763 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
5765 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
5766 [prompt_ setBackgroundColor:[UIColor clearColor]];
5767 [prompt_ setFont:font];
5769 [overlay_ addSubview:prompt_];
5771 CGSize prgsize = {75, 100};
5774 ovrrect.size.width - prgsize.width - 10,
5775 (ovrrect.size.height - prgsize.height) / 2
5778 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
5779 [progress_ setStyle:0];
5780 [overlay_ addSubview:progress_];
5782 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
5783 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
5785 CGRect frame = [cancel_ frame];
5786 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
5787 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
5788 [cancel_ setFrame:frame];
5790 [cancel_ setBarStyle:barstyle];
5794 - (void) _onCancel {
5796 [cancel_ removeFromSuperview];
5799 - (void) _update { _pooled
5801 status.setDelegate(self);
5803 [database_ updateWithStatus:status];
5806 performSelectorOnMainThread:@selector(_update_)
5812 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
5813 [prompt_ setText:[NSString stringWithFormat:CYLocalize("ERROR_MESSAGE"), error]];
5816 - (void) setProgressTitle:(NSString *)title {
5818 performSelectorOnMainThread:@selector(_setProgressTitle:)
5824 - (void) setProgressPercent:(float)percent {
5826 performSelectorOnMainThread:@selector(_setProgressPercent:)
5827 withObject:[NSNumber numberWithFloat:percent]
5832 - (void) startProgress {
5835 - (void) addProgressOutput:(NSString *)output {
5837 performSelectorOnMainThread:@selector(_addProgressOutput:)
5843 - (bool) isCancelling:(size_t)received {
5847 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5851 - (void) _setProgressTitle:(NSString *)title {
5852 [prompt_ setText:title];
5855 - (void) _setProgressPercent:(NSNumber *)percent {
5856 [progress_ setProgress:[percent floatValue]];
5859 - (void) _addProgressOutput:(NSString *)output {
5864 /* Cydia:// Protocol {{{ */
5865 @interface CydiaURLProtocol : NSURLProtocol {
5870 @implementation CydiaURLProtocol
5872 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
5873 NSURL *url([request URL]);
5876 NSString *scheme([[url scheme] lowercaseString]);
5877 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
5882 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
5886 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
5887 id<NSURLProtocolClient> client([self client]);
5889 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
5891 NSData *data(UIImagePNGRepresentation(icon));
5893 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
5894 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
5895 [client URLProtocol:self didLoadData:data];
5896 [client URLProtocolDidFinishLoading:self];
5900 - (void) startLoading {
5901 id<NSURLProtocolClient> client([self client]);
5902 NSURLRequest *request([self request]);
5904 NSURL *url([request URL]);
5905 NSString *href([url absoluteString]);
5907 NSString *path([href substringFromIndex:8]);
5908 NSRange slash([path rangeOfString:@"/"]);
5911 if (slash.location == NSNotFound) {
5915 command = [path substringToIndex:slash.location];
5916 path = [path substringFromIndex:(slash.location + 1)];
5919 Database *database([Database sharedInstance]);
5921 if ([command isEqualToString:@"package-icon"]) {
5924 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5925 Package *package([database packageWithName:path]);
5928 UIImage *icon([package icon]);
5929 [self _returnPNGWithImage:icon forRequest:request];
5930 } else if ([command isEqualToString:@"source-icon"]) {
5933 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5934 NSString *source(Simplify(path));
5935 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
5937 icon = [UIImage applicationImageNamed:@"unknown.png"];
5938 [self _returnPNGWithImage:icon forRequest:request];
5939 } else if ([command isEqualToString:@"uikit-image"]) {
5942 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5943 UIImage *icon(_UIImageWithName(path));
5944 [self _returnPNGWithImage:icon forRequest:request];
5945 } else if ([command isEqualToString:@"section-icon"]) {
5948 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5949 NSString *section(Simplify(path));
5950 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
5952 icon = [UIImage applicationImageNamed:@"unknown.png"];
5953 [self _returnPNGWithImage:icon forRequest:request];
5955 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
5959 - (void) stopLoading {
5965 /* Sections View {{{ */
5966 @interface SectionsView : RVPage {
5967 _transient Database *database_;
5968 NSMutableArray *sections_;
5969 NSMutableArray *filtered_;
5970 UITransitionView *transition_;
5976 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5977 - (void) reloadData;
5982 @implementation SectionsView
5985 [list_ setDataSource:nil];
5986 [list_ setDelegate:nil];
5988 [sections_ release];
5989 [filtered_ release];
5990 [transition_ release];
5992 [accessory_ release];
5996 - (int) numberOfRowsInTable:(UITable *)table {
5997 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6000 - (float) table:(UITable *)table heightForRow:(int)row {
6004 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6006 reusing = [[[SectionCell alloc] init] autorelease];
6007 [(SectionCell *)reusing setSection:(editing_ ?
6008 [sections_ objectAtIndex:row] :
6009 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6010 ) editing:editing_];
6014 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6018 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6022 - (void) tableRowSelected:(NSNotification *)notification {
6023 int row = [[notification object] selectedRow];
6034 title = CYLocalize("ALL_PACKAGES");
6036 section = [filtered_ objectAtIndex:(row - 1)];
6037 name = [section name];
6040 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6043 title = CYLocalize("NO_SECTION");
6047 PackageTable *table = [[[FilteredPackageTable alloc]
6051 filter:@selector(isVisiblyUninstalledInSection:)
6055 [table setDelegate:delegate_];
6057 [book_ pushPage:table];
6060 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6061 if ((self = [super initWithBook:book]) != nil) {
6062 database_ = database;
6064 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6065 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6067 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6068 [self addSubview:transition_];
6070 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6071 [transition_ transition:0 toView:list_];
6073 UITableColumn *column = [[[UITableColumn alloc]
6074 initWithTitle:CYLocalize("NAME")
6076 width:[self frame].size.width
6079 [list_ setDataSource:self];
6080 [list_ setSeparatorStyle:1];
6081 [list_ addTableColumn:column];
6082 [list_ setDelegate:self];
6083 [list_ setReusesTableCells:YES];
6087 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6088 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6092 - (void) reloadData {
6093 NSArray *packages = [database_ packages];
6095 [sections_ removeAllObjects];
6096 [filtered_ removeAllObjects];
6099 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6100 SectionMap sections;
6101 sections.resize(64);
6103 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6107 for (Package *package in packages) {
6108 NSString *name([package section]);
6109 NSString *key(name == nil ? @"" : name);
6114 _profile(SectionsView$reloadData$Section)
6115 section = §ions[key];
6116 if (*section == nil) {
6117 _profile(SectionsView$reloadData$Section$Allocate)
6118 *section = [[[Section alloc] initWithName:name] autorelease];
6123 [*section addToCount];
6125 _profile(SectionsView$reloadData$Filter)
6126 if (![package valid] || [package installed] != nil || ![package visible])
6130 [*section addToRow];
6134 _profile(SectionsView$reloadData$Section)
6135 section = [sections objectForKey:key];
6136 if (section == nil) {
6137 _profile(SectionsView$reloadData$Section$Allocate)
6138 section = [[[Section alloc] initWithName:name] autorelease];
6139 [sections setObject:section forKey:key];
6144 [section addToCount];
6146 _profile(SectionsView$reloadData$Filter)
6147 if (![package valid] || [package installed] != nil || ![package visible])
6157 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6158 [sections_ addObject:i->second];
6160 [sections_ addObjectsFromArray:[sections allValues]];
6163 [sections_ sortUsingSelector:@selector(compareByName:)];
6165 for (Section *section in sections_) {
6166 size_t count([section row]);
6167 if ([section row] == 0)
6170 section = [[[Section alloc] initWithName:[section name]] autorelease];
6171 [section setCount:count];
6172 [filtered_ addObject:section];
6179 - (void) resetView {
6181 [self _rightButtonClicked];
6184 - (void) resetViewAnimated:(BOOL)animated {
6185 [list_ resetViewAnimated:animated];
6188 - (void) _rightButtonClicked {
6189 if ((editing_ = !editing_))
6192 [delegate_ updateData];
6193 [book_ reloadTitleForPage:self];
6194 [book_ reloadButtonsForPage:self];
6197 - (NSString *) title {
6198 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6201 - (NSString *) backButtonTitle {
6202 return CYLocalize("SECTIONS");
6205 - (id) rightButtonTitle {
6206 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6209 - (UINavigationButtonStyle) rightButtonStyle {
6210 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6213 - (UIView *) accessoryView {
6219 /* Changes View {{{ */
6220 @interface ChangesView : RVPage {
6221 _transient Database *database_;
6222 NSMutableArray *packages_;
6223 NSMutableArray *sections_;
6224 UISectionList *list_;
6228 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6229 - (void) reloadData;
6233 @implementation ChangesView
6236 [[list_ table] setDelegate:nil];
6237 [list_ setDataSource:nil];
6239 [packages_ release];
6240 [sections_ release];
6245 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6246 return [sections_ count];
6249 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6250 return [[sections_ objectAtIndex:section] name];
6253 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6254 return [[sections_ objectAtIndex:section] row];
6257 - (int) numberOfRowsInTable:(UITable *)table {
6258 return [packages_ count];
6261 - (float) table:(UITable *)table heightForRow:(int)row {
6262 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6265 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6267 reusing = [[[PackageCell alloc] init] autorelease];
6268 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6272 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6276 - (void) tableRowSelected:(NSNotification *)notification {
6277 int row = [[notification object] selectedRow];
6280 Package *package = [packages_ objectAtIndex:row];
6281 PackageView *view([delegate_ packageView]);
6282 [view setDelegate:delegate_];
6283 [view setPackage:package];
6284 [book_ pushPage:view];
6287 - (void) _leftButtonClicked {
6288 [(CYBook *)book_ update];
6289 [self reloadButtons];
6292 - (void) _rightButtonClicked {
6293 [delegate_ distUpgrade];
6296 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6297 if ((self = [super initWithBook:book]) != nil) {
6298 database_ = database;
6300 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6301 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6303 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6304 [self addSubview:list_];
6306 [list_ setShouldHideHeaderInShortLists:NO];
6307 [list_ setDataSource:self];
6308 //[list_ setSectionListStyle:1];
6310 UITableColumn *column = [[[UITableColumn alloc]
6311 initWithTitle:CYLocalize("NAME")
6313 width:[self frame].size.width
6316 UITable *table = [list_ table];
6317 [table setSeparatorStyle:1];
6318 [table addTableColumn:column];
6319 [table setDelegate:self];
6320 [table setReusesTableCells:YES];
6324 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6325 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6329 - (void) reloadData {
6330 NSArray *packages = [database_ packages];
6332 [packages_ removeAllObjects];
6333 [sections_ removeAllObjects];
6336 for (Package *package in packages)
6338 [package installed] == nil && [package valid] && [package visible] ||
6339 [package upgradableAndEssential:YES]
6341 [packages_ addObject:package];
6344 [packages_ radixSortUsingFunction:reinterpret_cast<uint32_t (*)(id, void *)>(&PackageChangesRadix) withArgument:NULL];
6347 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES")] autorelease];
6348 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES")] autorelease];
6349 Section *section = nil;
6353 bool unseens = false;
6355 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
6358 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6359 Package *package = [packages_ objectAtIndex:offset];
6362 _profile(ChangesView$reloadData$Upgrade)
6363 uae = [package upgradableAndEssential:YES];
6370 _profile(ChangesView$reloadData$Remember)
6371 seen = [package seen];
6375 _profile(ChangesView$reloadData$Compare)
6376 different = section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame);
6384 name = CYLocalize("UNKNOWN");
6386 _profile(ChangesView$reloadData$Format)
6387 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6393 _profile(ChangesView$reloadData$Allocate)
6394 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6395 section = [[[Section alloc] initWithName:name row:offset] autorelease];
6396 [sections_ addObject:section];
6400 [section addToCount];
6401 } else if ([package ignored])
6402 [ignored addToCount];
6405 [upgradable addToCount];
6410 CFRelease(formatter);
6413 Section *last = [sections_ lastObject];
6414 size_t count = [last count];
6415 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6416 [sections_ removeLastObject];
6419 if ([ignored count] != 0)
6420 [sections_ insertObject:ignored atIndex:0];
6422 [sections_ insertObject:upgradable atIndex:0];
6425 [self reloadButtons];
6428 - (void) resetViewAnimated:(BOOL)animated {
6429 [list_ resetViewAnimated:animated];
6432 - (NSString *) leftButtonTitle {
6433 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6436 - (id) rightButtonTitle {
6437 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6440 - (NSString *) title {
6441 return CYLocalize("CHANGES");
6446 /* Search View {{{ */
6447 @protocol SearchViewDelegate
6448 - (void) showKeyboard:(BOOL)show;
6451 @interface SearchView : RVPage {
6453 UISearchField *field_;
6454 UITransitionView *transition_;
6455 FilteredPackageTable *table_;
6456 UIPreferencesTable *advanced_;
6462 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6463 - (void) reloadData;
6467 @implementation SearchView
6470 [field_ setDelegate:nil];
6472 [accessory_ release];
6474 [transition_ release];
6476 [advanced_ release];
6481 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6485 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6487 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6489 default: _assert(false);
6493 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6497 default: _assert(false);
6501 - (void) _showKeyboard:(BOOL)show {
6502 CGSize keysize = [UIKeyboard defaultSize];
6503 CGRect keydown = [book_ pageBounds];
6504 CGRect keyup = keydown;
6505 keyup.size.height -= keysize.height - ButtonBarHeight_;
6507 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6509 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6510 [animation setSignificantRectFields:8];
6513 [animation setStartFrame:keydown];
6514 [animation setEndFrame:keyup];
6516 [animation setStartFrame:keyup];
6517 [animation setEndFrame:keydown];
6520 UIAnimator *animator = [UIAnimator sharedAnimator];
6523 addAnimations:[NSArray arrayWithObjects:animation, nil]
6524 withDuration:(KeyboardTime_ - delay)
6529 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6531 [delegate_ showKeyboard:show];
6534 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6535 [self _showKeyboard:YES];
6538 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6539 [self _showKeyboard:NO];
6542 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6544 NSString *text([field_ text]);
6545 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6551 - (void) textFieldClearButtonPressed:(UITextField *)field {
6555 - (void) keyboardInputShouldDelete:(id)input {
6559 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6560 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6564 [field_ resignFirstResponder];
6569 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6570 if ((self = [super initWithBook:book]) != nil) {
6571 CGRect pageBounds = [book_ pageBounds];
6573 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6574 [self addSubview:transition_];
6576 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6578 [advanced_ setReusesTableCells:YES];
6579 [advanced_ setDataSource:self];
6580 [advanced_ reloadData];
6582 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6583 CGColor dimmed(space_, 0, 0, 0, 0.5);
6584 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6586 table_ = [[FilteredPackageTable alloc]
6590 filter:@selector(isUnfilteredAndSearchedForBy:)
6594 [table_ setShouldHideHeaderInShortLists:NO];
6595 [transition_ transition:0 toView:table_];
6604 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6611 [self bounds].size.width - area.origin.x - 18;
6613 area.size.height = [UISearchField defaultHeight];
6615 field_ = [[UISearchField alloc] initWithFrame:area];
6617 UIFont *font = [UIFont systemFontOfSize:16];
6618 [field_ setFont:font];
6620 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6621 [field_ setDelegate:self];
6623 [field_ setPaddingTop:5];
6625 UITextInputTraits *traits([field_ textInputTraits]);
6626 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6627 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6628 [traits setReturnKeyType:UIReturnKeySearch];
6630 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6632 accessory_ = [[UIView alloc] initWithFrame:accrect];
6633 [accessory_ addSubview:field_];
6635 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6636 [configure setShowPressFeedback:YES];
6637 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6638 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6639 [accessory_ addSubview:configure];*/
6641 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6642 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6648 LKAnimation *animation = [LKTransition animation];
6649 [animation setType:@"oglFlip"];
6650 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6651 [animation setFillMode:@"extended"];
6652 [animation setTransitionFlags:3];
6653 [animation setDuration:10];
6654 [animation setSpeed:0.35];
6655 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6656 [[transition_ _layer] addAnimation:animation forKey:0];
6657 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6658 flipped_ = !flipped_;
6662 - (void) configurePushed {
6663 [field_ resignFirstResponder];
6667 - (void) resetViewAnimated:(BOOL)animated {
6670 [table_ resetViewAnimated:animated];
6673 - (void) _reloadData {
6676 - (void) reloadData {
6679 [table_ setObject:[field_ text]];
6680 _profile(SearchView$reloadData)
6681 [table_ reloadData];
6684 [table_ resetCursor];
6687 - (UIView *) accessoryView {
6691 - (NSString *) title {
6695 - (NSString *) backButtonTitle {
6696 return CYLocalize("SEARCH");
6699 - (void) setDelegate:(id)delegate {
6700 [table_ setDelegate:delegate];
6701 [super setDelegate:delegate];
6707 @interface SettingsView : RVPage {
6708 _transient Database *database_;
6711 UIPreferencesTable *table_;
6712 _UISwitchSlider *subscribedSwitch_;
6713 _UISwitchSlider *ignoredSwitch_;
6714 UIPreferencesControlTableCell *subscribedCell_;
6715 UIPreferencesControlTableCell *ignoredCell_;
6718 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6722 @implementation SettingsView
6725 [table_ setDataSource:nil];
6728 if (package_ != nil)
6731 [subscribedSwitch_ release];
6732 [ignoredSwitch_ release];
6733 [subscribedCell_ release];
6734 [ignoredCell_ release];
6738 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6739 if (package_ == nil)
6745 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6746 if (package_ == nil)
6753 default: _assert(false);
6759 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
6760 if (package_ == nil)
6767 default: _assert(false);
6773 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6774 if (package_ == nil)
6781 default: _assert(false);
6787 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
6788 if (package_ == nil)
6791 _UISwitchSlider *slider([cell control]);
6792 BOOL value([slider value] != 0);
6793 NSMutableDictionary *metadata([package_ metadata]);
6796 if (NSNumber *number = [metadata objectForKey:key])
6797 before = [number boolValue];
6801 if (value != before) {
6802 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
6804 [delegate_ updateData];
6808 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
6809 [self onSomething:cell withKey:@"IsSubscribed"];
6812 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
6813 [self onSomething:cell withKey:@"IsIgnored"];
6816 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
6817 if (package_ == nil)
6821 case 0: switch (row) {
6823 return subscribedCell_;
6825 return ignoredCell_;
6826 default: _assert(false);
6829 case 1: switch (row) {
6831 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
6832 [cell setShowSelection:NO];
6833 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
6837 default: _assert(false);
6840 default: _assert(false);
6846 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
6847 if ((self = [super initWithBook:book])) {
6848 database_ = database;
6849 name_ = [package retain];
6851 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
6852 [self addSubview:table_];
6854 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
6855 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
6857 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
6858 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
6860 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
6861 [subscribedCell_ setShowSelection:NO];
6862 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
6863 [subscribedCell_ setControl:subscribedSwitch_];
6865 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
6866 [ignoredCell_ setShowSelection:NO];
6867 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
6868 [ignoredCell_ setControl:ignoredSwitch_];
6870 [table_ setDataSource:self];
6875 - (void) resetViewAnimated:(BOOL)animated {
6876 [table_ resetViewAnimated:animated];
6879 - (void) reloadData {
6880 if (package_ != nil)
6881 [package_ autorelease];
6882 package_ = [database_ packageWithName:name_];
6883 if (package_ != nil) {
6885 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
6886 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
6889 [table_ reloadData];
6892 - (NSString *) title {
6893 return CYLocalize("SETTINGS");
6898 /* Signature View {{{ */
6899 @interface SignatureView : BrowserView {
6900 _transient Database *database_;
6904 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6908 @implementation SignatureView
6915 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
6917 [super webView:sender didClearWindowObject:window forFrame:frame];
6920 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
6921 if ((self = [super initWithBook:book]) != nil) {
6922 database_ = database;
6923 package_ = [package retain];
6928 - (void) resetViewAnimated:(BOOL)animated {
6931 - (void) reloadData {
6932 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
6938 @interface Cydia : UIApplication <
6939 ConfirmationViewDelegate,
6940 ProgressViewDelegate,
6949 UIToolbar *buttonbar_;
6953 NSMutableArray *essential_;
6954 NSMutableArray *broken_;
6956 Database *database_;
6957 ProgressView *progress_;
6961 UIKeyboard *keyboard_;
6962 UIProgressHUD *hud_;
6964 SectionsView *sections_;
6965 ChangesView *changes_;
6966 ManageView *manage_;
6967 SearchView *search_;
6969 PackageView *package_;
6974 @implementation Cydia
6977 if ([broken_ count] != 0) {
6978 int count = [broken_ count];
6980 UIActionSheet *sheet = [[[UIActionSheet alloc]
6981 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
6982 buttons:[NSArray arrayWithObjects:
6983 CYLocalize("FORCIBLY_CLEAR"),
6984 CYLocalize("TEMPORARY_IGNORE"),
6986 defaultButtonIndex:0
6991 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
6992 [sheet popupAlertAnimated:YES];
6993 } else if (!Ignored_ && [essential_ count] != 0) {
6994 int count = [essential_ count];
6996 UIActionSheet *sheet = [[[UIActionSheet alloc]
6997 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
6998 buttons:[NSArray arrayWithObjects:
6999 CYLocalize("UPGRADE_ESSENTIAL"),
7000 CYLocalize("COMPLETE_UPGRADE"),
7001 CYLocalize("TEMPORARY_IGNORE"),
7003 defaultButtonIndex:0
7008 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
7009 [sheet popupAlertAnimated:YES];
7013 - (void) _reloadData {
7016 static bool loaded(false);
7017 UIProgressHUD *hud([self addProgressHUD]);
7018 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7021 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7024 [self removeProgressHUD:hud];
7028 [essential_ removeAllObjects];
7029 [broken_ removeAllObjects];
7031 NSArray *packages = [database_ packages];
7032 for (Package *package in packages) {
7034 [broken_ addObject:package];
7035 if ([package upgradableAndEssential:NO]) {
7036 if ([package essential])
7037 [essential_ addObject:package];
7043 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7044 [buttonbar_ setBadgeValue:badge forButton:3];
7045 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7046 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7047 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7048 [self setApplicationBadge:badge];
7050 [self setApplicationBadgeString:badge];
7052 [buttonbar_ setBadgeValue:nil forButton:3];
7053 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7054 [buttonbar_ setBadgeAnimated:NO forButton:3];
7055 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7056 [self removeApplicationBadge];
7057 else // XXX: maybe use setApplicationBadgeString also?
7058 [self setApplicationIconBadgeNumber:0];
7062 [buttonbar_ setBadgeValue:nil forButton:4];
7066 // XXX: what is this line of code for?
7067 if ([packages count] == 0);
7068 else if (Loaded_ || ManualRefresh) loaded:
7073 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7074 NSTimeInterval interval([update timeIntervalSinceNow]);
7075 if (interval <= 0 && interval > -600)
7083 - (void) _saveConfig {
7086 NSString *error(nil);
7087 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7089 NSError *error(nil);
7090 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7091 NSLog(@"failure to save metadata data: %@", error);
7094 NSLog(@"failure to serialize metadata: %@", error);
7102 - (void) updateData {
7105 /* XXX: this is just stupid */
7106 if (tag_ != 2 && sections_ != nil)
7107 [sections_ reloadData];
7108 if (tag_ != 3 && changes_ != nil)
7109 [changes_ reloadData];
7110 if (tag_ != 5 && search_ != nil)
7111 [search_ reloadData];
7121 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7122 _assert(file != NULL);
7124 NSArray *keys = [Sources_ allKeys];
7126 for (NSString *key in keys) {
7127 NSDictionary *source = [Sources_ objectForKey:key];
7129 fprintf(file, "%s %s %s\n",
7130 [[source objectForKey:@"Type"] UTF8String],
7131 [[source objectForKey:@"URI"] UTF8String],
7132 [[source objectForKey:@"Distribution"] UTF8String]
7141 detachNewThreadSelector:@selector(update_)
7144 title:CYLocalize("UPDATING_SOURCES")
7148 - (void) reloadData {
7149 @synchronized (self) {
7150 if (confirm_ == nil)
7156 pkgProblemResolver *resolver = [database_ resolver];
7158 resolver->InstallProtect();
7159 if (!resolver->Resolve(true))
7163 - (void) popUpBook:(RVBook *)book {
7164 [underlay_ popSubview:book];
7167 - (CGRect) popUpBounds {
7168 return [underlay_ bounds];
7172 [database_ prepare];
7174 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7175 [confirm_ setDelegate:self];
7177 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7178 [page setDelegate:self];
7180 [confirm_ setPage:page];
7181 [self popUpBook:confirm_];
7185 @synchronized (self) {
7190 - (void) clearPackage:(Package *)package {
7191 @synchronized (self) {
7198 - (void) installPackage:(Package *)package {
7199 @synchronized (self) {
7206 - (void) removePackage:(Package *)package {
7207 @synchronized (self) {
7214 - (void) distUpgrade {
7215 @synchronized (self) {
7216 [database_ upgrade];
7222 [self slideUp:[[[UIActionSheet alloc]
7224 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7225 defaultButtonIndex:1
7232 @synchronized (self) {
7235 if (confirm_ != nil) {
7243 [overlay_ removeFromSuperview];
7247 detachNewThreadSelector:@selector(perform)
7250 title:CYLocalize("RUNNING")
7254 - (void) bootstrap_ {
7256 [database_ upgrade];
7257 [database_ prepare];
7258 [database_ perform];
7261 /* XXX: replace and localize */
7262 - (void) bootstrap {
7264 detachNewThreadSelector:@selector(bootstrap_)
7267 title:@"Bootstrap Install"
7271 - (void) progressViewIsComplete:(ProgressView *)progress {
7272 if (confirm_ != nil) {
7273 [underlay_ addSubview:overlay_];
7274 [confirm_ popFromSuperviewAnimated:NO];
7280 - (void) setPage:(RVPage *)page {
7281 [page resetViewAnimated:NO];
7282 [page setDelegate:self];
7283 [book_ setPage:page];
7286 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7287 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7288 [browser loadURL:url];
7292 - (void) _setHomePage {
7293 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7296 - (SectionsView *) sectionsView {
7297 if (sections_ == nil)
7298 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7302 - (void) buttonBarItemTapped:(id)sender {
7303 unsigned tag = [sender tag];
7305 [book_ resetViewAnimated:YES];
7307 } else if (tag_ == 2 && tag != 2)
7308 [[self sectionsView] resetView];
7311 case 1: [self _setHomePage]; break;
7313 case 2: [self setPage:[self sectionsView]]; break;
7314 case 3: [self setPage:changes_]; break;
7315 case 4: [self setPage:manage_]; break;
7316 case 5: [self setPage:search_]; break;
7318 default: _assert(false);
7324 - (void) applicationWillSuspend {
7326 [super applicationWillSuspend];
7329 - (void) askForSettings {
7330 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7332 UIActionSheet *role = [[[UIActionSheet alloc]
7333 initWithTitle:CYLocalize("WHO_ARE_YOU")
7334 buttons:[NSArray arrayWithObjects:
7335 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7336 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7337 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7339 defaultButtonIndex:-1
7344 [role setBodyText:CYLocalize("ROLE_EX")];
7345 [role popupAlertAnimated:YES];
7348 - (void) setPackageView:(PackageView *)view {
7349 if (package_ == nil)
7350 package_ = [view retain];
7353 - (PackageView *) packageView {
7356 if (package_ == nil)
7357 view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7360 view = [package_ autorelease];
7369 [self setStatusBarShowsProgress:NO];
7370 [self removeProgressHUD:hud_];
7375 pid_t pid = ExecFork();
7377 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7378 perror("launchctl stop");
7385 [self askForSettings];
7390 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7392 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7393 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7394 0, 0, screenrect.size.width, screenrect.size.height - 48
7395 ) database:database_];
7397 [book_ setDelegate:self];
7399 [overlay_ addSubview:book_];
7401 NSArray *buttonitems = [NSArray arrayWithObjects:
7402 [NSDictionary dictionaryWithObjectsAndKeys:
7403 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7404 @"home-up.png", kUIButtonBarButtonInfo,
7405 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7406 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7407 self, kUIButtonBarButtonTarget,
7408 @"Cydia", kUIButtonBarButtonTitle,
7409 @"0", kUIButtonBarButtonType,
7412 [NSDictionary dictionaryWithObjectsAndKeys:
7413 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7414 @"install-up.png", kUIButtonBarButtonInfo,
7415 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7416 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7417 self, kUIButtonBarButtonTarget,
7418 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7419 @"0", kUIButtonBarButtonType,
7422 [NSDictionary dictionaryWithObjectsAndKeys:
7423 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7424 @"changes-up.png", kUIButtonBarButtonInfo,
7425 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7426 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7427 self, kUIButtonBarButtonTarget,
7428 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7429 @"0", kUIButtonBarButtonType,
7432 [NSDictionary dictionaryWithObjectsAndKeys:
7433 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7434 @"manage-up.png", kUIButtonBarButtonInfo,
7435 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7436 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7437 self, kUIButtonBarButtonTarget,
7438 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7439 @"0", kUIButtonBarButtonType,
7442 [NSDictionary dictionaryWithObjectsAndKeys:
7443 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7444 @"search-up.png", kUIButtonBarButtonInfo,
7445 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7446 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7447 self, kUIButtonBarButtonTarget,
7448 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7449 @"0", kUIButtonBarButtonType,
7453 buttonbar_ = [[UIToolbar alloc]
7455 withFrame:CGRectMake(
7456 0, screenrect.size.height - ButtonBarHeight_,
7457 screenrect.size.width, ButtonBarHeight_
7459 withItemList:buttonitems
7462 [buttonbar_ setDelegate:self];
7463 [buttonbar_ setBarStyle:1];
7464 [buttonbar_ setButtonBarTrackingMode:2];
7466 int buttons[5] = {1, 2, 3, 4, 5};
7467 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7468 [buttonbar_ showButtonGroup:0 withDuration:0];
7470 for (int i = 0; i != 5; ++i)
7471 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7472 i * 64 + 2, 1, 60, ButtonBarHeight_
7475 [buttonbar_ showSelectionForButton:1];
7476 [overlay_ addSubview:buttonbar_];
7478 [UIKeyboard initImplementationNow];
7479 CGSize keysize = [UIKeyboard defaultSize];
7480 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7481 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7482 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7483 [overlay_ addSubview:keyboard_];
7486 [underlay_ addSubview:overlay_];
7490 [self sectionsView];
7491 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7492 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7494 manage_ = (ManageView *) [[self
7495 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7496 withClass:[ManageView class]
7499 [self setPackageView:[self packageView]];
7506 [self _setHomePage];
7509 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7510 NSString *context([sheet context]);
7512 if ([context isEqualToString:@"missing"])
7514 else if ([context isEqualToString:@"cancel"]) {
7532 @synchronized (self) {
7537 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7541 if (confirm_ != nil) {
7546 } else if ([context isEqualToString:@"fixhalf"]) {
7549 @synchronized (self) {
7550 for (Package *broken in broken_) {
7553 NSString *id = [broken id];
7554 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7555 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7556 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7557 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7566 [broken_ removeAllObjects];
7575 } else if ([context isEqualToString:@"role"]) {
7577 case 1: Role_ = @"User"; break;
7578 case 2: Role_ = @"Hacker"; break;
7579 case 3: Role_ = @"Developer"; break;
7586 bool reset = Settings_ != nil;
7588 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7592 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7602 } else if ([context isEqualToString:@"upgrade"]) {
7605 @synchronized (self) {
7606 for (Package *essential in essential_)
7607 [essential install];
7630 - (void) reorganize { _pooled
7631 system("/usr/libexec/cydia/free.sh");
7632 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7635 - (void) applicationSuspend:(__GSEvent *)event {
7636 if (hud_ == nil && ![progress_ isRunning])
7637 [super applicationSuspend:event];
7640 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7642 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7645 - (void) _setSuspended:(BOOL)value {
7647 [super _setSuspended:value];
7650 - (UIProgressHUD *) addProgressHUD {
7651 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7652 [window_ setUserInteractionEnabled:NO];
7654 [progress_ addSubview:hud];
7658 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7660 [hud removeFromSuperview];
7661 [window_ setUserInteractionEnabled:YES];
7664 - (void) openMailToURL:(NSURL *)url {
7665 // XXX: this makes me sad
7667 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7669 [UIApp openURL:url];// asPanel:YES];
7673 - (void) clearFirstResponder {
7674 if (id responder = [window_ firstResponder])
7675 [responder resignFirstResponder];
7678 - (RVPage *) pageForPackage:(NSString *)name {
7679 if (Package *package = [database_ packageWithName:name]) {
7680 PackageView *view([self packageView]);
7681 [view setPackage:package];
7684 UIActionSheet *sheet = [[[UIActionSheet alloc]
7685 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7686 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
7687 defaultButtonIndex:0
7692 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
7694 [sheet popupAlertAnimated:YES];
7699 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7703 NSString *scheme([[url scheme] lowercaseString]);
7704 if (![scheme isEqualToString:@"cydia"])
7706 NSString *path([url absoluteString]);
7707 if ([path length] < 8)
7709 path = [path substringFromIndex:8];
7710 if (![path hasPrefix:@"/"])
7711 path = [@"/" stringByAppendingString:path];
7713 if ([path isEqualToString:@"/add-source"])
7714 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
7715 else if ([path isEqualToString:@"/storage"])
7716 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
7717 else if ([path isEqualToString:@"/sources"])
7718 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
7719 else if ([path isEqualToString:@"/packages"])
7720 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
7721 else if ([path hasPrefix:@"/url/"])
7722 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
7723 else if ([path hasPrefix:@"/launch/"])
7724 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
7725 else if ([path hasPrefix:@"/package-settings/"])
7726 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
7727 else if ([path hasPrefix:@"/package-signature/"])
7728 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
7729 else if ([path hasPrefix:@"/package/"])
7730 return [self pageForPackage:[path substringFromIndex:9]];
7731 else if ([path hasPrefix:@"/files/"]) {
7732 NSString *name = [path substringFromIndex:7];
7734 if (Package *package = [database_ packageWithName:name]) {
7735 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
7736 [files setPackage:package];
7744 - (void) applicationOpenURL:(NSURL *)url {
7745 [super applicationOpenURL:url];
7747 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
7748 [self setPage:page];
7749 [buttonbar_ showSelectionForButton:tag];
7754 - (void) applicationDidFinishLaunching:(id)unused {
7756 Font12_ = [[UIFont systemFontOfSize:12] retain];
7757 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
7758 Font14_ = [[UIFont systemFontOfSize:14] retain];
7759 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
7760 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
7764 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
7765 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
7767 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
7769 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7770 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
7772 [window_ orderFront:self];
7773 [window_ makeKey:self];
7774 [window_ setHidden:NO];
7776 database_ = [Database sharedInstance];
7777 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
7778 [database_ setDelegate:progress_];
7779 [window_ setContentView:progress_];
7781 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
7782 [progress_ setContentView:underlay_];
7784 [progress_ resetView];
7787 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
7788 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
7789 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
7790 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
7791 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
7792 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
7793 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
7795 [self setIdleTimerDisabled:YES];
7797 hud_ = [[self addProgressHUD] retain];
7798 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
7800 [self setStatusBarShowsProgress:YES];
7803 detachNewThreadSelector:@selector(reorganize)
7811 - (void) showKeyboard:(BOOL)show {
7812 CGSize keysize = [UIKeyboard defaultSize];
7813 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
7814 CGRect keyup = keydown;
7815 keyup.origin.y -= keysize.height;
7817 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
7818 [animation setSignificantRectFields:2];
7821 [animation setStartFrame:keydown];
7822 [animation setEndFrame:keyup];
7823 [keyboard_ activate];
7825 [animation setStartFrame:keyup];
7826 [animation setEndFrame:keydown];
7827 [keyboard_ deactivate];
7830 [[UIAnimator sharedAnimator]
7831 addAnimations:[NSArray arrayWithObjects:animation, nil]
7832 withDuration:KeyboardTime_
7837 - (void) slideUp:(UIActionSheet *)alert {
7839 [alert presentSheetFromButtonBar:buttonbar_];
7841 [alert presentSheetInView:overlay_];
7846 void AddPreferences(NSString *plist) { _pooled
7847 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
7848 _assert(settings != NULL);
7849 NSMutableArray *items = [settings objectForKey:@"items"];
7853 for (NSMutableDictionary *item in items) {
7854 NSString *label = [item objectForKey:@"label"];
7855 if (label != nil && [label isEqualToString:@"Cydia"]) {
7862 for (size_t i(0); i != [items count]; ++i) {
7863 NSDictionary *item([items objectAtIndex:i]);
7864 NSString *label = [item objectForKey:@"label"];
7865 if (label != nil && [label isEqualToString:@"General"]) {
7866 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
7867 @"CydiaSettings", @"bundle",
7868 @"PSLinkCell", @"cell",
7869 [NSNumber numberWithBool:YES], @"hasIcon",
7870 [NSNumber numberWithBool:YES], @"isController",
7872 nil] atIndex:(i + 1)];
7878 _assert([settings writeToFile:plist atomically:YES] == YES);
7883 id Alloc_(id self, SEL selector) {
7884 id object = alloc_(self, selector);
7885 lprintf("[%s]A-%p\n", self->isa->name, object);
7890 id Dealloc_(id self, SEL selector) {
7891 id object = dealloc_(self, selector);
7892 lprintf("[%s]D-%p\n", self->isa->name, object);
7896 Class $WebDefaultUIKitDelegate;
7898 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
7900 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
7901 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
7902 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
7903 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
7906 int main(int argc, char *argv[]) { _pooled
7909 /* Library Hacks {{{ */
7910 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
7912 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
7913 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
7914 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
7915 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
7916 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
7919 /* Set Locale {{{ */
7920 Locale_ = CFLocaleCopyCurrent();
7921 Languages_ = [NSLocale preferredLanguages];
7922 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
7923 NSLog(@"%@", [Languages_ description]);
7925 if (Languages_ == nil || [Languages_ count] == 0)
7928 lang = [[Languages_ objectAtIndex:0] UTF8String];
7929 setenv("LANG", lang, true);
7930 //std::setlocale(LC_ALL, lang);
7931 NSLog(@"Setting Language: %s", lang);
7934 // XXX: apr_app_initialize?
7937 /* Parse Arguments {{{ */
7938 bool substrate(false);
7944 for (int argi(1); argi != argc; ++argi)
7945 if (strcmp(argv[argi], "--") == 0) {
7947 argv[argi] = argv[0];
7953 for (int argi(1); argi != arge; ++argi)
7954 if (strcmp(args[argi], "--bootstrap") == 0)
7956 else if (strcmp(args[argi], "--substrate") == 0)
7959 fprintf(stderr, "unknown argument: %s\n", args[argi]);
7964 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
7965 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
7966 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
7967 Sounds_Keyboard_ = [keyboard boolValue];
7970 App_ = [[NSBundle mainBundle] bundlePath];
7971 Home_ = NSHomeDirectory();
7976 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
7977 alloc_ = alloc->method_imp;
7978 alloc->method_imp = (IMP) &Alloc_;*/
7980 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
7981 dealloc_ = dealloc->method_imp;
7982 dealloc->method_imp = (IMP) &Dealloc_;*/
7987 size = sizeof(maxproc);
7988 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
7989 perror("sysctlbyname(\"kern.maxproc\", ?)");
7990 else if (maxproc < 64) {
7992 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
7993 perror("sysctlbyname(\"kern.maxproc\", #)");
7996 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
7997 char *machine = new char[size];
7998 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
7999 perror("sysctlbyname(\"hw.machine\", ?)");
8003 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8005 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8006 Build_ = [system objectForKey:@"ProductBuildVersion"];
8007 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8008 Product_ = [info objectForKey:@"SafariProductVersion"];
8009 Safari_ = [info objectForKey:@"CFBundleVersion"];
8012 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8013 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8015 /* Load Database {{{ */
8017 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8019 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8022 if (Metadata_ == NULL)
8023 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8025 Settings_ = [Metadata_ objectForKey:@"Settings"];
8027 Packages_ = [Metadata_ objectForKey:@"Packages"];
8028 Sections_ = [Metadata_ objectForKey:@"Sections"];
8029 Sources_ = [Metadata_ objectForKey:@"Sources"];
8032 if (Settings_ != nil)
8033 Role_ = [Settings_ objectForKey:@"Role"];
8035 if (Packages_ == nil) {
8036 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8037 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8040 if (Sections_ == nil) {
8041 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8042 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8045 if (Sources_ == nil) {
8046 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8047 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8052 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8055 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8056 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8057 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8058 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8060 if (access("/User", F_OK) != 0) {
8062 system("/usr/libexec/cydia/firmware.sh");
8066 _assert([[NSFileManager defaultManager]
8067 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8068 withIntermediateDirectories:YES
8073 if (access("/tmp/cydia.chk", F_OK) == 0) {
8074 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8075 _assert(errno == ENOENT);
8076 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8077 _assert(errno == ENOENT);
8080 _assert(pkgInitConfig(*_config));
8081 _assert(pkgInitSystem(*_config, _system));
8084 _config->Set("APT::Acquire::Translation", lang);
8086 /* Color Choices {{{ */
8087 space_ = CGColorSpaceCreateDeviceRGB();
8089 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8090 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8091 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8092 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8093 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8094 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8095 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8096 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8097 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8098 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8099 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8100 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8101 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8102 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8103 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8106 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8107 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8110 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8112 /* UIKit Configuration {{{ */
8113 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8114 if ($GSFontSetUseLegacyFontMetrics != NULL)
8115 $GSFontSetUseLegacyFontMetrics(YES);
8117 UIKeyboardDisableAutomaticAppearance();
8121 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8123 CGColorSpaceRelease(space_);