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>
53 #define DEPLOYMENT_TARGET_MACOSX 1
54 #define CF_BUILDING_CF 1
55 #include <CoreFoundation/CFInternal.h>
58 #include <CoreFoundation/CFPriv.h>
59 #include <CoreFoundation/CFUniChar.h>
61 #import <QuartzCore/CALayer.h>
62 #import <UIKit/UIKit.h>
64 #include <WebCore/WebCoreThread.h>
65 #import <WebKit/WebDefaultUIKitDelegate.h>
72 #include <ext/stdio_filebuf.h>
74 #include <apt-pkg/acquire.h>
75 #include <apt-pkg/acquire-item.h>
76 #include <apt-pkg/algorithms.h>
77 #include <apt-pkg/cachefile.h>
78 #include <apt-pkg/clean.h>
79 #include <apt-pkg/configuration.h>
80 #include <apt-pkg/debindexfile.h>
81 #include <apt-pkg/debmetaindex.h>
82 #include <apt-pkg/error.h>
83 #include <apt-pkg/init.h>
84 #include <apt-pkg/mmap.h>
85 #include <apt-pkg/pkgrecords.h>
86 #include <apt-pkg/sha1.h>
87 #include <apt-pkg/sourcelist.h>
88 #include <apt-pkg/sptr.h>
89 #include <apt-pkg/strutl.h>
91 #include <apr-1/apr_pools.h>
93 #include <sys/types.h>
95 #include <sys/sysctl.h>
96 #include <sys/param.h>
97 #include <sys/mount.h>
103 #include <mach-o/nlist.h>
113 #include <ext/hash_map>
115 #import "BrowserView.h"
116 #import "ResetView.h"
118 #import "substrate.h"
121 //#define _finline __attribute__((force_inline))
122 #define _finline inline
127 #define _limit(count) do { \
128 static size_t _count(0); \
129 if (++_count == count) \
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
199 /* Objective-C Handle<> {{{ */
200 template <typename Type_>
202 typedef _H<Type_> This_;
207 _finline void Retain_() {
212 _finline void Clear_() {
218 _finline _H(Type_ *value = NULL, bool mended = false) :
229 _finline This_ &operator =(Type_ *value) {
230 if (value_ != value) {
239 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
241 void NSLogPoint(const char *fix, const CGPoint &point) {
242 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
245 void NSLogRect(const char *fix, const CGRect &rect) {
246 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
249 @interface NSObject (Cydia)
250 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
251 - (id) yieldToSelector:(SEL)selector;
254 @implementation NSObject (Cydia)
259 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
260 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
261 id object([[context objectAtIndex:1] nonretainedObjectValue]);
262 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
264 /* XXX: deal with exceptions */
265 id value([self performSelector:selector withObject:object]);
267 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
268 [context removeAllObjects];
269 if ([signature methodReturnLength] != 0 && value != nil)
270 [context addObject:value];
275 performSelectorOnMainThread:@selector(doNothing)
281 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
282 /*return [self performSelector:selector withObject:object];*/
284 volatile bool stopped(false);
286 NSMutableArray *context([NSMutableArray arrayWithObjects:
287 [NSValue valueWithPointer:selector],
288 [NSValue valueWithNonretainedObject:object],
289 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
292 NSThread *thread([[[NSThread alloc]
294 selector:@selector(_yieldToContext:)
300 NSRunLoop *loop([NSRunLoop currentRunLoop]);
301 NSDate *future([NSDate distantFuture]);
303 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
305 return [context count] == 0 ? nil : [context objectAtIndex:0];
308 - (id) yieldToSelector:(SEL)selector {
309 return [self yieldToSelector:selector withObject:nil];
314 /* NSForcedOrderingSearch doesn't work on the iPhone */
315 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
316 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
317 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
319 /* iPhoneOS 2.0 Compatibility {{{ */
321 @interface UITextView (iPhoneOS)
322 - (void) setTextSize:(float)size;
325 @implementation UITextView (iPhoneOS)
327 - (void) setTextSize:(float)size {
328 [self setFont:[[self font] fontWithSize:size]];
335 extern NSString * const kCAFilterNearest;
337 /* Information Dictionaries {{{ */
338 @interface NSMutableArray (Cydia)
339 - (void) addInfoDictionary:(NSDictionary *)info;
342 @implementation NSMutableArray (Cydia)
344 - (void) addInfoDictionary:(NSDictionary *)info {
345 [self addObject:info];
350 @interface NSMutableDictionary (Cydia)
351 - (void) addInfoDictionary:(NSDictionary *)info;
354 @implementation NSMutableDictionary (Cydia)
356 - (void) addInfoDictionary:(NSDictionary *)info {
357 NSString *bundle = [info objectForKey:@"CFBundleIdentifier"];
358 [self setObject:info forKey:bundle];
363 /* Pop Transitions {{{ */
364 @interface PopTransitionView : UITransitionView {
369 @implementation PopTransitionView
371 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
372 if (from != nil && to == nil)
373 [self removeFromSuperview];
378 @implementation UIView (PopUpView)
380 - (void) popFromSuperviewAnimated:(BOOL)animated {
381 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
384 - (void) popSubview:(UIView *)view {
385 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
386 [transition setDelegate:transition];
387 [self addSubview:transition];
389 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
390 [transition transition:UITransitionNone toView:blank];
391 [transition transition:UITransitionPushFromBottom toView:view];
397 #define lprintf(args...) fprintf(stderr, args)
400 #define ForSaurik (0 && !ForRelease)
401 #define LogBrowser (0 && !ForRelease)
402 #define TrackResize (0 && !ForRelease)
403 #define ManualRefresh (1 && !ForRelease)
404 #define ShowInternals (0 && !ForRelease)
405 #define IgnoreInstall (0 && !ForRelease)
406 #define RecycleWebViews 0
407 #define AlwaysReload (1 && !ForRelease)
411 #define _trace(args...)
413 #define _profile(name) {
416 #define PrintTimes() do {} while (false)
420 @interface NSMutableArray (Radix)
421 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
422 - (void) radixSortUsingFunction:(uint32_t (*)(id, void *))function withArgument:(void *)argument;
430 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
431 struct RadixItem_ *lhs(swap), *rhs(swap + count);
433 static const size_t width = 32;
434 static const size_t bits = 11;
435 static const size_t slots = 1 << bits;
436 static const size_t passes = (width + (bits - 1)) / bits;
438 size_t *hist(new size_t[slots]);
440 for (size_t pass(0); pass != passes; ++pass) {
441 memset(hist, 0, sizeof(size_t) * slots);
443 for (size_t i(0); i != count; ++i) {
444 uint32_t key(lhs[i].key);
446 key &= _not(uint32_t) >> width - bits;
451 for (size_t i(0); i != slots; ++i) {
452 size_t local(offset);
457 for (size_t i(0); i != count; ++i) {
458 uint32_t key(lhs[i].key);
460 key &= _not(uint32_t) >> width - bits;
461 rhs[hist[key]++] = lhs[i];
464 RadixItem_ *tmp(lhs);
471 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
472 for (size_t i(0); i != count; ++i)
473 [values addObject:[self objectAtIndex:lhs[i].index]];
474 [self setArray:values];
479 @implementation NSMutableArray (Radix)
481 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
482 size_t count([self count]);
487 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
488 [invocation setSelector:selector];
489 [invocation setArgument:&object atIndex:2];
491 /* XXX: this is an unsafe optimization of doomy hell */
492 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
493 _assert(method != NULL);
494 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
495 _assert(imp != NULL);
498 struct RadixItem_ *swap(new RadixItem_[count * 2]);
500 for (size_t i(0); i != count; ++i) {
501 RadixItem_ &item(swap[i]);
504 id object([self objectAtIndex:i]);
507 [invocation setTarget:object];
509 [invocation getReturnValue:&item.key];
511 item.key = imp(object, selector, object);
515 RadixSort_(self, count, swap);
518 - (void) radixSortUsingFunction:(uint32_t (*)(id, void *))function withArgument:(void *)argument {
519 size_t count([self count]);
520 struct RadixItem_ *swap(new RadixItem_[count * 2]);
522 for (size_t i(0); i != count; ++i) {
523 RadixItem_ &item(swap[i]);
526 id object([self objectAtIndex:i]);
527 item.key = function(object, argument);
530 RadixSort_(self, count, swap);
535 /* Insertion Sort {{{ */
537 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
538 const char *ptr = (const char *)list;
540 CFIndex half = count / 2;
541 const char *probe = ptr + elementSize * half;
542 CFComparisonResult cr = comparator(element, probe, context);
543 if (0 == cr) return (probe - (const char *)list) / elementSize;
544 ptr = (cr < 0) ? ptr : probe + elementSize;
545 count = (cr < 0) ? half : (half + (count & 1) - 1);
547 return (ptr - (const char *)list) / elementSize;
550 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
551 if (range.length == 0)
553 const void **values(new const void *[range.length]);
554 CFArrayGetValues(array, range, values);
556 for (CFIndex index(1); index != range.length; ++index) {
557 const void *value(values[index]);
558 CFIndex correct(CFBSearch_(&value, sizeof(const void *), values, index, comparator, context));
559 //NSLog(@"%u %u", index, correct);
560 if (correct != index) {
561 memmove(values + correct + 1, values + correct, sizeof(const void *) * (index - correct));
562 values[correct] = value;
566 CFArrayReplaceValues(array, range, values, range.length);
572 /* Apple Bug Fixes {{{ */
573 @implementation UIWebDocumentView (Cydia)
575 - (void) _setScrollerOffset:(CGPoint)offset {
576 UIScroller *scroller([self _scroller]);
578 CGSize size([scroller contentSize]);
579 CGSize bounds([scroller bounds].size);
582 max.x = size.width - bounds.width;
583 max.y = size.height - bounds.height;
591 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
592 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
594 [scroller setOffset:offset];
601 kUIControlEventMouseDown = 1 << 0,
602 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
603 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
604 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
605 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
606 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
607 } UIControlEventMasks;
609 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
610 size_t length([self length] - state->state);
613 else if (length > count)
615 for (size_t i(0); i != length; ++i)
616 objects[i] = [self item:state->state++];
617 state->itemsPtr = objects;
618 state->mutationsPtr = (unsigned long *) self;
622 @interface NSString (UIKit)
623 - (NSString *) stringByAddingPercentEscapes;
624 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
627 @interface NSString (Cydia)
628 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
629 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
630 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
631 - (NSComparisonResult) compareByPath:(NSString *)other;
632 - (NSString *) stringByCachingURLWithCurrentCDN;
633 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
636 @implementation NSString (Cydia)
638 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
639 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
642 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
643 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
644 memcpy(data, bytes, length);
645 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
648 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
649 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
652 - (NSComparisonResult) compareByPath:(NSString *)other {
653 NSString *prefix = [self commonPrefixWithString:other options:0];
654 size_t length = [prefix length];
656 NSRange lrange = NSMakeRange(length, [self length] - length);
657 NSRange rrange = NSMakeRange(length, [other length] - length);
659 lrange = [self rangeOfString:@"/" options:0 range:lrange];
660 rrange = [other rangeOfString:@"/" options:0 range:rrange];
662 NSComparisonResult value;
664 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
665 value = NSOrderedSame;
666 else if (lrange.location == NSNotFound)
667 value = NSOrderedAscending;
668 else if (rrange.location == NSNotFound)
669 value = NSOrderedDescending;
671 value = NSOrderedSame;
673 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
674 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
675 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
676 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
678 NSComparisonResult result = [lpath compare:rpath];
679 return result == NSOrderedSame ? value : result;
682 - (NSString *) stringByCachingURLWithCurrentCDN {
684 stringByReplacingOccurrencesOfString:@"://"
685 withString:@"://ne.edgecastcdn.net/8003A4/"
687 /* XXX: this is somewhat inaccurate */
688 range:NSMakeRange(0, 10)
692 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
693 return [(id)CFURLCreateStringByAddingPercentEscapes(
698 kCFStringEncodingUTF8
704 static inline NSString *CYLocalizeEx(NSString *key, NSString *value = nil) {
705 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:nil];
708 #define CYLocalize(key) CYLocalizeEx(@ key)
716 _finline void clear_() {
722 _finline bool empty() const {
726 _finline size_t size() const {
730 _finline char *data() const {
734 _finline void clear() {
739 _finline CYString() :
746 _finline ~CYString() {
750 void operator =(const CYString &rhs) {
754 if (rhs.cache_ == nil)
757 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
760 void set(apr_pool_t *pool, const char *data, size_t size) {
766 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
767 memcpy(temp, data, size);
774 _finline void set(apr_pool_t *pool, const char *data) {
775 set(pool, data, data == NULL ? 0 : strlen(data));
778 _finline void set(apr_pool_t *pool, const std::string &rhs) {
779 set(pool, rhs.data(), rhs.size());
782 bool operator ==(const CYString &rhs) const {
783 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
787 if (cache_ == NULL) {
790 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
791 } return (id) cache_;
796 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
799 struct NSStringMapHash :
800 std::unary_function<NSString *, size_t>
802 _finline size_t operator ()(NSString *value) const {
803 return CFStringHashNSString((CFStringRef) value);
807 struct NSStringMapLess :
808 std::binary_function<NSString *, NSString *, bool>
810 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
811 return [lhs compare:rhs] == NSOrderedAscending;
815 struct NSStringMapEqual :
816 std::binary_function<NSString *, NSString *, bool>
818 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
819 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
820 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
821 //[lhs isEqualToString:rhs];
825 /* Perl-Compatible RegEx {{{ */
835 Pcre(const char *regex) :
840 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
843 lprintf("%d:%s\n", offset, error);
847 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
848 matches_ = new int[(capture_ + 1) * 3];
856 NSString *operator [](size_t match) {
857 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
860 bool operator ()(NSString *data) {
861 // XXX: length is for characters, not for bytes
862 return operator ()([data UTF8String], [data length]);
865 bool operator ()(const char *data, size_t size) {
867 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
871 /* Mime Addresses {{{ */
872 @interface Address : NSObject {
878 - (NSString *) address;
880 - (void) setAddress:(NSString *)address;
882 + (Address *) addressWithString:(NSString *)string;
883 - (Address *) initWithString:(NSString *)string;
886 @implementation Address
895 - (NSString *) name {
899 - (NSString *) address {
903 - (void) setAddress:(NSString *)address {
905 [address_ autorelease];
909 address_ = [address retain];
912 + (Address *) addressWithString:(NSString *)string {
913 return [[[Address alloc] initWithString:string] autorelease];
916 + (NSArray *) _attributeKeys {
917 return [NSArray arrayWithObjects:@"address", @"name", nil];
920 - (NSArray *) attributeKeys {
921 return [[self class] _attributeKeys];
924 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
925 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
928 - (Address *) initWithString:(NSString *)string {
929 if ((self = [super init]) != nil) {
930 const char *data = [string UTF8String];
931 size_t size = [string length];
933 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
935 if (address_r(data, size)) {
936 name_ = [address_r[1] retain];
937 address_ = [address_r[2] retain];
939 name_ = [string retain];
947 /* CoreGraphics Primitives {{{ */
958 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
961 Set(space, red, green, blue, alpha);
966 CGColorRelease(color_);
973 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
975 float color[] = {red, green, blue, alpha};
976 color_ = CGColorCreate(space, color);
979 operator CGColorRef() {
985 extern "C" void UISetColor(CGColorRef color);
987 /* Random Global Variables {{{ */
988 static const int PulseInterval_ = 50000;
989 static const int ButtonBarHeight_ = 48;
990 static const float KeyboardTime_ = 0.3f;
992 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
993 #define SandboxTemplate_ "/usr/share/sandbox/SandboxTemplate.sb"
994 #define NotifyConfig_ "/etc/notify.conf"
996 static bool Queuing_;
998 static CGColor Blue_;
999 static CGColor Blueish_;
1000 static CGColor Black_;
1001 static CGColor Off_;
1002 static CGColor White_;
1003 static CGColor Gray_;
1004 static CGColor Green_;
1005 static CGColor Purple_;
1006 static CGColor Purplish_;
1008 static UIColor *InstallingColor_;
1009 static UIColor *RemovingColor_;
1011 static NSString *App_;
1012 static NSString *Home_;
1013 static BOOL Sounds_Keyboard_;
1015 static BOOL Advanced_;
1016 static BOOL Loaded_;
1017 static BOOL Ignored_;
1019 static UIFont *Font12_;
1020 static UIFont *Font12Bold_;
1021 static UIFont *Font14_;
1022 static UIFont *Font18Bold_;
1023 static UIFont *Font22Bold_;
1025 static const char *Machine_ = NULL;
1026 static const NSString *UniqueID_ = nil;
1027 static const NSString *Build_ = nil;
1028 static const NSString *Product_ = nil;
1029 static const NSString *Safari_ = nil;
1031 CFLocaleRef Locale_;
1032 NSArray *Languages_;
1033 CGColorSpaceRef space_;
1038 static NSDictionary *SectionMap_;
1039 static NSMutableDictionary *Metadata_;
1040 static _transient NSMutableDictionary *Settings_;
1041 static _transient NSString *Role_;
1042 static _transient NSMutableDictionary *Packages_;
1043 static _transient NSMutableDictionary *Sections_;
1044 static _transient NSMutableDictionary *Sources_;
1045 static bool Changed_;
1046 static NSDate *now_;
1049 static NSMutableArray *Documents_;
1052 NSString *GetLastUpdate() {
1053 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1056 return CYLocalize("NEVER_OR_UNKNOWN");
1058 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1059 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1061 CFRelease(formatter);
1063 return [(NSString *) formatted autorelease];
1066 /* Display Helpers {{{ */
1067 inline float Interpolate(float begin, float end, float fraction) {
1068 return (end - begin) * fraction + begin;
1071 /* XXX: localize this! */
1072 NSString *SizeString(double size) {
1073 bool negative = size < 0;
1078 while (size > 1024) {
1083 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1085 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1088 NSString *StripVersion(const char *version) {
1089 const char *colon(strchr(version, ':'));
1091 version = colon + 1;
1092 return [NSString stringWithUTF8String:version];
1095 NSString *StripVersion(NSString *version) {
1096 NSRange colon = [version rangeOfString:@":"];
1097 if (colon.location != NSNotFound)
1098 version = [version substringFromIndex:(colon.location + 1)];
1102 NSString *LocalizeSection(NSString *section) {
1103 static Pcre title_r("^(.*?) \\((.*)\\)$");
1104 if (title_r(section)) {
1105 NSString *parent(title_r[1]);
1106 NSString *child(title_r[2]);
1108 return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"),
1109 LocalizeSection(parent),
1110 LocalizeSection(child)
1114 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1117 NSString *Simplify(NSString *title) {
1118 const char *data = [title UTF8String];
1119 size_t size = [title length];
1121 static Pcre square_r("^\\[(.*)\\]$");
1122 if (square_r(data, size))
1123 return Simplify(square_r[1]);
1125 static Pcre paren_r("^\\((.*)\\)$");
1126 if (paren_r(data, size))
1127 return Simplify(paren_r[1]);
1129 static Pcre title_r("^(.*?) \\((.*)\\)$");
1130 if (title_r(data, size))
1131 return Simplify(title_r[1]);
1136 _finline static void Stifle(char &value) {
1137 value = (value & 0xdf) ^ 0x40;
1141 bool isSectionVisible(NSString *section) {
1142 NSDictionary *metadata([Sections_ objectForKey:section]);
1143 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1144 return hidden == nil || ![hidden boolValue];
1147 /* Delegate Prototypes {{{ */
1151 @interface NSObject (ProgressDelegate)
1154 @implementation NSObject(ProgressDelegate)
1156 - (void) _setProgressError:(NSArray *)args {
1157 [self performSelector:@selector(setProgressError:forPackage:)
1158 withObject:[args objectAtIndex:0]
1159 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1165 @protocol ProgressDelegate
1166 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1167 - (void) setProgressTitle:(NSString *)title;
1168 - (void) setProgressPercent:(float)percent;
1169 - (void) startProgress;
1170 - (void) addProgressOutput:(NSString *)output;
1171 - (bool) isCancelling:(size_t)received;
1174 @protocol ConfigurationDelegate
1175 - (void) repairWithSelector:(SEL)selector;
1176 - (void) setConfigurationData:(NSString *)data;
1181 @protocol CydiaDelegate
1182 - (void) setPackageView:(PackageView *)view;
1183 - (void) clearPackage:(Package *)package;
1184 - (void) installPackage:(Package *)package;
1185 - (void) removePackage:(Package *)package;
1186 - (void) slideUp:(UIActionSheet *)alert;
1187 - (void) distUpgrade;
1188 - (void) updateData;
1190 - (void) askForSettings;
1191 - (UIProgressHUD *) addProgressHUD;
1192 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1193 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1194 - (RVPage *) pageForPackage:(NSString *)name;
1195 - (void) openMailToURL:(NSURL *)url;
1196 - (void) clearFirstResponder;
1197 - (PackageView *) packageView;
1201 /* Status Delegation {{{ */
1203 public pkgAcquireStatus
1206 _transient NSObject<ProgressDelegate> *delegate_;
1214 void setDelegate(id delegate) {
1215 delegate_ = delegate;
1218 virtual bool MediaChange(std::string media, std::string drive) {
1222 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1225 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1226 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1227 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1230 virtual void Done(pkgAcquire::ItemDesc &item) {
1233 virtual void Fail(pkgAcquire::ItemDesc &item) {
1235 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1236 item.Owner->Status == pkgAcquire::Item::StatDone
1240 std::string &error(item.Owner->ErrorText);
1244 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1245 NSArray *fields([description componentsSeparatedByString:@" "]);
1246 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1248 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1249 withObject:[NSArray arrayWithObjects:
1250 [NSString stringWithUTF8String:error.c_str()],
1257 virtual bool Pulse(pkgAcquire *Owner) {
1258 bool value = pkgAcquireStatus::Pulse(Owner);
1261 double(CurrentBytes + CurrentItems) /
1262 double(TotalBytes + TotalItems)
1265 [delegate_ setProgressPercent:percent];
1266 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1269 virtual void Start() {
1270 [delegate_ startProgress];
1273 virtual void Stop() {
1277 /* Progress Delegation {{{ */
1282 _transient id<ProgressDelegate> delegate_;
1285 virtual void Update() {
1286 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1287 [delegate_ setProgressPercent:(Percent / 100)];*/
1296 void setDelegate(id delegate) {
1297 delegate_ = delegate;
1300 virtual void Done() {
1301 //[delegate_ setProgressPercent:1];
1306 /* Database Interface {{{ */
1307 @interface Database : NSObject {
1313 pkgCacheFile cache_;
1314 pkgDepCache::Policy *policy_;
1315 pkgRecords *records_;
1316 pkgProblemResolver *resolver_;
1317 pkgAcquire *fetcher_;
1319 SPtr<pkgPackageManager> manager_;
1320 pkgSourceList *list_;
1322 NSMutableDictionary *sources_;
1323 NSMutableArray *packages_;
1325 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1334 + (Database *) sharedInstance;
1337 - (void) _readCydia:(NSNumber *)fd;
1338 - (void) _readStatus:(NSNumber *)fd;
1339 - (void) _readOutput:(NSNumber *)fd;
1343 - (Package *) packageWithName:(NSString *)name;
1345 - (pkgCacheFile &) cache;
1346 - (pkgDepCache::Policy *) policy;
1347 - (pkgRecords *) records;
1348 - (pkgProblemResolver *) resolver;
1349 - (pkgAcquire &) fetcher;
1350 - (pkgSourceList &) list;
1351 - (NSArray *) packages;
1352 - (NSArray *) sources;
1353 - (void) reloadData;
1361 - (void) updateWithStatus:(Status &)status;
1363 - (void) setDelegate:(id)delegate;
1364 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1368 /* Source Class {{{ */
1369 @interface Source : NSObject {
1370 NSString *description_;
1376 NSString *distribution_;
1380 NSString *defaultIcon_;
1382 NSDictionary *record_;
1386 - (Source *) initWithMetaIndex:(metaIndex *)index;
1388 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1390 - (NSString *) supportForPackage:(NSString *)package;
1392 - (NSDictionary *) record;
1396 - (NSString *) distribution;
1397 - (NSString *) type;
1399 - (NSString *) host;
1401 - (NSString *) name;
1402 - (NSString *) description;
1403 - (NSString *) label;
1404 - (NSString *) origin;
1405 - (NSString *) version;
1407 - (NSString *) defaultIcon;
1411 @implementation Source
1413 #define _clear(field) \
1420 _clear(distribution_)
1423 _clear(description_)
1428 _clear(defaultIcon_)
1437 + (NSArray *) _attributeKeys {
1438 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1441 - (NSArray *) attributeKeys {
1442 return [[self class] _attributeKeys];
1445 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1446 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1449 - (void) setMetaIndex:(metaIndex *)index {
1452 trusted_ = index->IsTrusted();
1454 uri_ = [[NSString stringWithUTF8String:index->GetURI().c_str()] retain];
1455 distribution_ = [[NSString stringWithUTF8String:index->GetDist().c_str()] retain];
1456 type_ = [[NSString stringWithUTF8String:index->GetType()] retain];
1458 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1459 if (dindex != NULL) {
1460 std::ifstream release(dindex->MetaIndexFile("Release").c_str());
1462 while (std::getline(release, line)) {
1463 std::string::size_type colon(line.find(':'));
1464 if (colon == std::string::npos)
1467 std::string name(line.substr(0, colon));
1468 std::string value(line.substr(colon + 1));
1469 while (!value.empty() && value[0] == ' ')
1470 value = value.substr(1);
1472 if (name == "Default-Icon")
1473 defaultIcon_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1474 else if (name == "Description")
1475 description_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1476 else if (name == "Label")
1477 label_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1478 else if (name == "Origin")
1479 origin_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1480 else if (name == "Support")
1481 support_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1482 else if (name == "Version")
1483 version_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1487 record_ = [Sources_ objectForKey:[self key]];
1489 record_ = [record_ retain];
1492 - (Source *) initWithMetaIndex:(metaIndex *)index {
1493 if ((self = [super init]) != nil) {
1494 [self setMetaIndex:index];
1498 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1499 NSDictionary *lhr = [self record];
1500 NSDictionary *rhr = [source record];
1503 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1505 NSString *lhs = [self name];
1506 NSString *rhs = [source name];
1508 if ([lhs length] != 0 && [rhs length] != 0) {
1509 unichar lhc = [lhs characterAtIndex:0];
1510 unichar rhc = [rhs characterAtIndex:0];
1512 if (isalpha(lhc) && !isalpha(rhc))
1513 return NSOrderedAscending;
1514 else if (!isalpha(lhc) && isalpha(rhc))
1515 return NSOrderedDescending;
1518 return [lhs compare:rhs options:LaxCompareOptions_];
1521 - (NSString *) supportForPackage:(NSString *)package {
1522 return support_ == nil ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1525 - (NSDictionary *) record {
1533 - (NSString *) uri {
1537 - (NSString *) distribution {
1538 return distribution_;
1541 - (NSString *) type {
1545 - (NSString *) key {
1546 return [NSString stringWithFormat:@"%@:%@:%@", type_, uri_, distribution_];
1549 - (NSString *) host {
1550 return [[[NSURL URLWithString:[self uri]] host] lowercaseString];
1553 - (NSString *) name {
1554 return origin_ == nil ? [self host] : origin_;
1557 - (NSString *) description {
1558 return description_;
1561 - (NSString *) label {
1562 return label_ == nil ? [self host] : label_;
1565 - (NSString *) origin {
1569 - (NSString *) version {
1573 - (NSString *) defaultIcon {
1574 return defaultIcon_;
1579 /* Relationship Class {{{ */
1580 @interface Relationship : NSObject {
1585 - (NSString *) type;
1587 - (NSString *) name;
1591 @implementation Relationship
1599 - (NSString *) type {
1607 - (NSString *) name {
1614 /* Package Class {{{ */
1615 @interface Package : NSObject {
1618 pkgCache::VerIterator version_;
1619 pkgCache::PkgIterator iterator_;
1620 _transient Database *database_;
1621 pkgCache::VerFileIterator file_;
1627 NSString *section$_;
1632 NSString *installed_;
1638 CYString depiction_;
1651 NSArray *relationships_;
1653 NSMutableDictionary *metadata_;
1654 _transient NSDate *firstSeen_;
1655 _transient NSDate *lastSeen_;
1659 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1660 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1662 - (pkgCache::PkgIterator) iterator;
1664 - (NSString *) section;
1665 - (NSString *) simpleSection;
1667 - (NSString *) longSection;
1668 - (NSString *) shortSection;
1672 - (Address *) maintainer;
1674 - (NSString *) longDescription;
1675 - (NSString *) shortDescription;
1678 - (NSMutableDictionary *) metadata;
1680 - (BOOL) subscribed;
1683 - (NSString *) latest;
1684 - (NSString *) installed;
1687 - (BOOL) upgradableAndEssential:(BOOL)essential;
1690 - (BOOL) unfiltered;
1694 - (BOOL) halfConfigured;
1695 - (BOOL) halfInstalled;
1697 - (NSString *) mode;
1700 - (NSString *) name;
1702 - (NSString *) homepage;
1703 - (NSString *) depiction;
1704 - (Address *) author;
1706 - (NSString *) support;
1708 - (NSArray *) files;
1709 - (NSArray *) relationships;
1710 - (NSArray *) warnings;
1711 - (NSArray *) applications;
1713 - (Source *) source;
1714 - (NSString *) role;
1716 - (BOOL) matches:(NSString *)text;
1718 - (bool) hasSupportingRole;
1719 - (BOOL) hasTag:(NSString *)tag;
1720 - (NSString *) primaryPurpose;
1721 - (NSArray *) purposes;
1722 - (bool) isCommercial;
1724 - (uint32_t) compareByPrefix;
1725 - (uint32_t) compareBySection:(NSArray *)sections;
1727 - (uint32_t) compareForChanges;
1732 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1733 - (bool) isInstalledAndVisible:(NSNumber *)number;
1734 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1735 - (bool) isVisibleInSource:(Source *)source;
1739 uint32_t PackageChangesRadix(Package *self, void *) {
1744 uint32_t timestamp : 30;
1745 uint32_t ignored : 1;
1746 uint32_t upgradable : 1;
1750 bool upgradable([self upgradableAndEssential:YES]);
1751 value.bits.upgradable = upgradable ? 1 : 0;
1754 value.bits.timestamp = 0;
1755 value.bits.ignored = [self ignored] ? 0 : 1;
1756 value.bits.upgradable = 1;
1758 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1759 value.bits.ignored = 0;
1760 value.bits.upgradable = 0;
1763 return _not(uint32_t) - value.key;
1766 CFStringRef (*PackageName)(Package *self, SEL sel);
1768 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1769 _profile(PackageNameCompare)
1770 CFStringRef lhn, rhn;
1773 _profile(PackageNameCompare$Setup)
1774 lhn = PackageName(lhs, @selector(name));
1775 rhn = PackageName(rhs, @selector(name));
1778 _profile(PackageNameCompare$Nothing)
1781 _profile(PackageNameCompare$Length)
1782 length = CFStringGetLength(lhn);
1785 _profile(PackageNameCompare$NumbersLast)
1786 if (length != 0 && CFStringGetLength(rhn) != 0) {
1787 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1788 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1789 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1790 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1791 return lha ? NSOrderedAscending : NSOrderedDescending;
1795 _profile(PackageNameCompare$Compare)
1796 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1801 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1802 return PackageNameCompare(*lhs, *rhs, context);
1805 struct PackageNameOrdering :
1806 std::binary_function<Package *, Package *, bool>
1808 _finline bool operator ()(Package *lhs, Package *rhs) const {
1809 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1813 @implementation Package
1818 if (section$_ != nil)
1819 [section$_ release];
1823 if (installed_ != nil)
1824 [installed_ release];
1826 if (sponsor$_ != nil)
1827 [sponsor$_ release];
1828 if (author$_ != nil)
1835 if (relationships_ != nil)
1836 [relationships_ release];
1837 if (metadata_ != nil)
1838 [metadata_ release];
1843 + (NSString *) webScriptNameForSelector:(SEL)selector {
1844 if (selector == @selector(hasTag:))
1850 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1851 return [self webScriptNameForSelector:selector] == nil;
1854 + (NSArray *) _attributeKeys {
1855 return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"longDescription", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"longSection", @"maintainer", @"mode", @"name", @"purposes", @"section", @"shortDescription", @"shortSection", @"simpleSection", @"size", @"source", @"sponsor", @"support", @"warnings", nil];
1858 - (NSArray *) attributeKeys {
1859 return [[self class] _attributeKeys];
1862 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1863 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1866 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
1867 if ((self = [super init]) != nil) {
1868 _profile(Package$initWithVersion)
1869 @synchronized (database) {
1870 era_ = [database era];
1873 iterator_ = version.ParentPkg();
1874 database_ = database;
1876 _profile(Package$initWithVersion$Latest)
1877 latest_ = [StripVersion(version_.VerStr()) retain];
1880 pkgCache::VerIterator current(iterator_.CurrentVer());
1882 installed_ = [StripVersion(current.VerStr()) retain];
1884 if (!version_.end())
1885 file_ = version_.FileList();
1887 pkgCache &cache([database_ cache]);
1888 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
1891 _profile(Package$initWithVersion$Name)
1892 id_.set(pool, iterator_.Name());
1896 source_ = [database_ getSource:file_.File()];
1901 _profile(Package$initWithVersion$Parse)
1902 pkgRecords::Parser *parser;
1904 _profile(Package$initWithVersion$Parse$Lookup)
1905 parser = &[database_ records]->Lookup(file_);
1911 _profile(Package$initWithVersion$Parse$Find)
1918 {"depiction", &depiction_},
1919 {"homepage", &homepage_},
1920 {"website", &website},
1921 {"support", &support_},
1922 {"sponsor", &sponsor_},
1923 {"author", &author_},
1927 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1928 const char *start, *end;
1930 if (parser->Find(names[i].name_, start, end)) {
1931 CYString &value(*names[i].value_);
1932 _profile(Package$initWithVersion$Parse$Value)
1933 value.set(pool, start, end - start);
1939 _profile(Package$initWithVersion$Parse$Tagline)
1940 tagline_.set(pool, parser->ShortDesc());
1943 _profile(Package$initWithVersion$Parse$Retain)
1944 if (!homepage_.empty())
1945 homepage_ = website;
1946 if (homepage_ == depiction_)
1949 tags_ = [[tag componentsSeparatedByString:@", "] retain];
1953 _profile(Package$initWithVersion$Tags)
1955 for (NSString *tag in tags_)
1956 if ([tag hasPrefix:@"role::"]) {
1957 role_ = [[tag substringFromIndex:6] retain];
1962 bool changed(false);
1963 NSString *key([id_ lowercaseString]);
1965 _profile(Package$initWithVersion$Metadata)
1966 metadata_ = [Packages_ objectForKey:key];
1968 if (metadata_ == nil) {
1969 firstSeen_ = [now_ retain];
1971 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
1972 firstSeen_, @"FirstSeen",
1973 latest_, @"LastVersion",
1978 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
1979 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
1981 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
1982 subscribed_ = [subscribed boolValue];
1984 NSString *version([metadata_ objectForKey:@"LastVersion"]);
1986 if (firstSeen_ == nil) {
1987 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
1988 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
1992 if (version == nil) {
1993 [metadata_ setObject:latest_ forKey:@"LastVersion"];
1995 } else if (![version isEqualToString:latest_]) {
1996 [metadata_ setObject:latest_ forKey:@"LastVersion"];
1998 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2003 metadata_ = [metadata_ retain];
2006 [Packages_ setObject:metadata_ forKey:key];
2011 _profile(Package$initWithVersion$Section)
2012 section_.set(pool, iterator_.Section());
2015 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2016 visible_ = [self hasSupportingRole] && [self unfiltered];
2017 } _end } return self;
2020 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2021 pkgCache::VerIterator version;
2023 _profile(Package$packageWithIterator$GetCandidateVer)
2024 version = [database policy]->GetCandidateVer(iterator);
2030 return [[[Package alloc]
2031 initWithVersion:version
2038 - (pkgCache::PkgIterator) iterator {
2042 - (NSString *) section {
2043 if (section$_ == nil) {
2044 if (section_.empty())
2047 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2048 NSString *name(section_);
2051 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2052 if (NSString *rename = [value objectForKey:@"Rename"]) {
2057 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2061 - (NSString *) simpleSection {
2062 if (NSString *section = [self section])
2063 return Simplify(section);
2068 - (NSString *) longSection {
2069 return LocalizeSection(section_);
2072 - (NSString *) shortSection {
2073 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2076 - (NSString *) uri {
2079 pkgIndexFile *index;
2080 pkgCache::PkgFileIterator file(file_.File());
2081 if (![database_ list].FindIndex(file, index))
2083 return [NSString stringWithUTF8String:iterator_->Path];
2084 //return [NSString stringWithUTF8String:file.Site()];
2085 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2089 - (Address *) maintainer {
2092 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2093 const std::string &maintainer(parser->Maintainer());
2094 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2098 return version_.end() ? 0 : version_->InstalledSize;
2101 - (NSString *) longDescription {
2104 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2105 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2107 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2108 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2109 if ([lines count] < 2)
2112 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2113 for (size_t i(1), e([lines count]); i != e; ++i) {
2114 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2115 [trimmed addObject:trim];
2118 return [trimmed componentsJoinedByString:@"\n"];
2121 - (NSString *) shortDescription {
2126 _profile(Package$index)
2127 CFStringRef name((CFStringRef) [self name]);
2128 if (CFStringGetLength(name) == 0)
2130 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2131 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2133 return toupper(character);
2137 - (NSMutableDictionary *) metadata {
2142 if (subscribed_ && lastSeen_ != nil)
2147 - (BOOL) subscribed {
2152 NSDictionary *metadata([self metadata]);
2153 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2154 return [ignored boolValue];
2159 - (NSString *) latest {
2163 - (NSString *) installed {
2168 return !version_.end();
2171 - (BOOL) upgradableAndEssential:(BOOL)essential {
2172 _profile(Package$upgradableAndEssential)
2173 pkgCache::VerIterator current(iterator_.CurrentVer());
2175 return essential && essential_ && visible_;
2177 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2181 - (BOOL) essential {
2186 return [database_ cache][iterator_].InstBroken();
2189 - (BOOL) unfiltered {
2190 NSString *section([self section]);
2191 return section == nil || isSectionVisible(section);
2199 unsigned char current(iterator_->CurrentState);
2200 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2203 - (BOOL) halfConfigured {
2204 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2207 - (BOOL) halfInstalled {
2208 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2212 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2213 return state.Mode != pkgDepCache::ModeKeep;
2216 - (NSString *) mode {
2217 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2219 switch (state.Mode) {
2220 case pkgDepCache::ModeDelete:
2221 if ((state.iFlags & pkgDepCache::Purge) != 0)
2225 case pkgDepCache::ModeKeep:
2226 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2227 return @"REINSTALL";
2228 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2232 case pkgDepCache::ModeInstall:
2233 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2234 return @"REINSTALL";
2235 else*/ switch (state.Status) {
2237 return @"DOWNGRADE";
2243 return @"NEW_INSTALL";
2256 - (NSString *) name {
2257 return name_.empty() ? id_ : name_;
2260 - (UIImage *) icon {
2261 NSString *section = [self simpleSection];
2265 if ([icon_ hasPrefix:@"file:///"])
2266 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2267 if (icon == nil) if (section != nil)
2268 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2269 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2270 if ([dicon hasPrefix:@"file:///"])
2271 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2273 icon = [UIImage applicationImageNamed:@"unknown.png"];
2277 - (NSString *) homepage {
2281 - (NSString *) depiction {
2285 - (Address *) sponsor {
2286 if (sponsor$_ == nil) {
2287 if (sponsor_.empty())
2289 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2293 - (Address *) author {
2294 if (author$_ == nil) {
2295 if (author_.empty())
2297 author$_ = [[Address addressWithString:author_] retain];
2301 - (NSString *) support {
2302 return support_ != nil ? support_ : [[self source] supportForPackage:id_];
2305 - (NSArray *) files {
2306 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2307 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2310 fin.open([path UTF8String]);
2315 while (std::getline(fin, line))
2316 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2321 - (NSArray *) relationships {
2322 return relationships_;
2325 - (NSArray *) warnings {
2326 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2327 const char *name(iterator_.Name());
2329 size_t length(strlen(name));
2330 if (length < 2) invalid:
2331 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2332 else for (size_t i(0); i != length; ++i)
2334 /* XXX: technically this is not allowed */
2335 (name[i] < 'A' || name[i] > 'Z') &&
2336 (name[i] < 'a' || name[i] > 'z') &&
2337 (name[i] < '0' || name[i] > '9') &&
2338 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2341 if (strcmp(name, "cydia") != 0) {
2343 bool _private = false;
2346 bool repository = [[self section] isEqualToString:@"Repositories"];
2348 if (NSArray *files = [self files])
2349 for (NSString *file in files)
2350 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2352 else if (!_private && [file isEqualToString:@"/private"])
2354 else if (!stash && [file isEqualToString:@"/var/stash"])
2357 /* XXX: this is not sensitive enough. only some folders are valid. */
2358 if (cydia && !repository)
2359 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2361 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2363 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2366 return [warnings count] == 0 ? nil : warnings;
2369 - (NSArray *) applications {
2370 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2372 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2374 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2375 if (NSArray *files = [self files])
2376 for (NSString *file in files)
2377 if (application_r(file)) {
2378 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2379 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2380 if ([id isEqualToString:me])
2383 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2385 display = application_r[1];
2387 NSString *bundle([file stringByDeletingLastPathComponent]);
2388 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2389 if (icon == nil || [icon length] == 0)
2391 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2393 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2394 [applications addObject:application];
2396 [application addObject:id];
2397 [application addObject:display];
2398 [application addObject:url];
2401 return [applications count] == 0 ? nil : applications;
2404 - (Source *) source {
2406 @synchronized (database_) {
2407 if ([database_ era] != era_ || file_.end())
2410 source_ = [database_ getSource:file_.File()];
2422 - (NSString *) role {
2426 - (BOOL) matches:(NSString *)text {
2432 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2433 if (range.location != NSNotFound)
2436 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2437 if (range.location != NSNotFound)
2440 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2441 if (range.location != NSNotFound)
2447 - (bool) hasSupportingRole {
2450 if ([role_ isEqualToString:@"enduser"])
2452 if ([Role_ isEqualToString:@"User"])
2454 if ([role_ isEqualToString:@"hacker"])
2456 if ([Role_ isEqualToString:@"Hacker"])
2458 if ([role_ isEqualToString:@"developer"])
2460 if ([Role_ isEqualToString:@"Developer"])
2465 - (BOOL) hasTag:(NSString *)tag {
2466 return tags_ == nil ? NO : [tags_ containsObject:tag];
2469 - (NSString *) primaryPurpose {
2470 for (NSString *tag in tags_)
2471 if ([tag hasPrefix:@"purpose::"])
2472 return [tag substringFromIndex:9];
2476 - (NSArray *) purposes {
2477 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2478 for (NSString *tag in tags_)
2479 if ([tag hasPrefix:@"purpose::"])
2480 [purposes addObject:[tag substringFromIndex:9]];
2481 return [purposes count] == 0 ? nil : purposes;
2484 - (bool) isCommercial {
2485 return [self hasTag:@"cydia::commercial"];
2488 - (uint32_t) compareByPrefix {
2491 CYString &name(name_.empty() ? id_ : name_);
2492 if (name.size() <= offset)
2494 size_t size(name.size() - offset);
2498 memcpy(data, name.data() + offset, 4);
2500 memcpy(data, name.data() + offset, size);
2501 memset(data + size, 0, 4 - size);
2509 /* XXX: ntohl may be more honest */
2510 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2513 - (uint32_t) compareBySection:(NSArray *)sections {
2514 NSString *section([self section]);
2515 for (size_t i(0), e([sections count]); i != e; ++i) {
2516 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2520 return _not(uint32_t);
2523 - (uint32_t) compareForChanges {
2528 uint32_t timestamp : 30;
2529 uint32_t ignored : 1;
2530 uint32_t upgradable : 1;
2534 bool upgradable([self upgradableAndEssential:YES]);
2535 value.bits.upgradable = upgradable ? 1 : 0;
2538 value.bits.timestamp = 0;
2539 value.bits.ignored = [self ignored] ? 0 : 1;
2540 value.bits.upgradable = 1;
2542 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2543 value.bits.ignored = 0;
2544 value.bits.upgradable = 0;
2547 return _not(uint32_t) - value.key;
2551 pkgProblemResolver *resolver = [database_ resolver];
2552 resolver->Clear(iterator_);
2553 resolver->Protect(iterator_);
2557 pkgProblemResolver *resolver = [database_ resolver];
2558 resolver->Clear(iterator_);
2559 resolver->Protect(iterator_);
2560 pkgCacheFile &cache([database_ cache]);
2561 cache->MarkInstall(iterator_, false);
2562 pkgDepCache::StateCache &state((*cache)[iterator_]);
2563 if (!state.Install())
2564 cache->SetReInstall(iterator_, true);
2568 pkgProblemResolver *resolver = [database_ resolver];
2569 resolver->Clear(iterator_);
2570 resolver->Protect(iterator_);
2571 resolver->Remove(iterator_);
2572 [database_ cache]->MarkDelete(iterator_, true);
2575 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2576 _profile(Package$isUnfilteredAndSearchedForBy)
2579 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2580 value &= [self unfiltered];
2583 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2584 value &= [self matches:search];
2591 - (bool) isInstalledAndVisible:(NSNumber *)number {
2592 return (![number boolValue] || [self visible]) && [self installed] != nil;
2595 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2596 NSString *section = [self section];
2600 [self installed] == nil && (
2602 section == nil && [name length] == 0 ||
2603 [name isEqualToString:section]
2607 - (bool) isVisibleInSource:(Source *)source {
2608 return [self source] == source && [self visible];
2613 /* Section Class {{{ */
2614 @interface Section : NSObject {
2619 NSString *localized_;
2622 - (NSComparisonResult) compareByLocalized:(Section *)section;
2623 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2624 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2625 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2626 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2627 - (NSString *) name;
2634 - (void) addToCount;
2636 - (void) setCount:(size_t)count;
2637 - (NSString *) localized;
2641 @implementation Section
2645 if (localized_ != nil)
2646 [localized_ release];
2650 - (NSComparisonResult) compareByLocalized:(Section *)section {
2651 NSString *lhs(localized_);
2652 NSString *rhs([section localized]);
2654 /*if ([lhs length] != 0 && [rhs length] != 0) {
2655 unichar lhc = [lhs characterAtIndex:0];
2656 unichar rhc = [rhs characterAtIndex:0];
2658 if (isalpha(lhc) && !isalpha(rhc))
2659 return NSOrderedAscending;
2660 else if (!isalpha(lhc) && isalpha(rhc))
2661 return NSOrderedDescending;
2664 return [lhs compare:rhs options:LaxCompareOptions_];
2667 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2668 if ((self = [self initWithName:name localize:NO]) != nil) {
2669 if (localized != nil)
2670 localized_ = [localized retain];
2674 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2675 return [self initWithName:name row:0 localize:localize];
2678 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2679 if ((self = [super init]) != nil) {
2680 name_ = [name retain];
2684 localized_ = [LocalizeSection(name_) retain];
2688 /* XXX: localize the index thingees */
2689 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2690 if ((self = [super init]) != nil) {
2691 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2697 - (NSString *) name {
2717 - (void) addToCount {
2721 - (void) setCount:(size_t)count {
2725 - (NSString *) localized {
2733 static NSArray *Finishes_;
2735 /* Database Implementation {{{ */
2736 @implementation Database
2738 + (Database *) sharedInstance {
2739 static Database *instance;
2740 if (instance == nil)
2741 instance = [[Database alloc] init];
2751 NSRecycleZone(zone_);
2752 // XXX: malloc_destroy_zone(zone_);
2753 apr_pool_destroy(pool_);
2757 - (void) _readCydia:(NSNumber *)fd { _pooled
2758 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2759 std::istream is(&ib);
2762 static Pcre finish_r("^finish:([^:]*)$");
2764 while (std::getline(is, line)) {
2765 const char *data(line.c_str());
2766 size_t size = line.size();
2767 lprintf("C:%s\n", data);
2769 if (finish_r(data, size)) {
2770 NSString *finish = finish_r[1];
2771 int index = [Finishes_ indexOfObject:finish];
2772 if (index != INT_MAX && index > Finish_)
2780 - (void) _readStatus:(NSNumber *)fd { _pooled
2781 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2782 std::istream is(&ib);
2785 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2786 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2788 while (std::getline(is, line)) {
2789 const char *data(line.c_str());
2790 size_t size = line.size();
2791 lprintf("S:%s\n", data);
2793 if (conffile_r(data, size)) {
2794 [delegate_ setConfigurationData:conffile_r[1]];
2795 } else if (strncmp(data, "status: ", 8) == 0) {
2796 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2797 [delegate_ setProgressTitle:string];
2798 } else if (pmstatus_r(data, size)) {
2799 std::string type([pmstatus_r[1] UTF8String]);
2800 NSString *id = pmstatus_r[2];
2802 float percent([pmstatus_r[3] floatValue]);
2803 [delegate_ setProgressPercent:(percent / 100)];
2805 NSString *string = pmstatus_r[4];
2807 if (type == "pmerror")
2808 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2809 withObject:[NSArray arrayWithObjects:string, id, nil]
2812 else if (type == "pmstatus") {
2813 [delegate_ setProgressTitle:string];
2814 } else if (type == "pmconffile")
2815 [delegate_ setConfigurationData:string];
2816 else _assert(false);
2817 } else _assert(false);
2823 - (void) _readOutput:(NSNumber *)fd { _pooled
2824 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2825 std::istream is(&ib);
2828 while (std::getline(is, line)) {
2829 lprintf("O:%s\n", line.c_str());
2830 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2840 - (Package *) packageWithName:(NSString *)name {
2841 if (static_cast<pkgDepCache *>(cache_) == NULL)
2843 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2844 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2847 - (Database *) init {
2848 if ((self = [super init]) != nil) {
2855 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2856 apr_pool_create(&pool_, NULL);
2858 sources_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];
2859 packages_ = [[NSMutableArray alloc] init];
2863 _assert(pipe(fds) != -1);
2866 _config->Set("APT::Keep-Fds::", cydiafd_);
2867 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
2870 detachNewThreadSelector:@selector(_readCydia:)
2872 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2875 _assert(pipe(fds) != -1);
2879 detachNewThreadSelector:@selector(_readStatus:)
2881 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2884 _assert(pipe(fds) != -1);
2885 _assert(dup2(fds[0], 0) != -1);
2886 _assert(close(fds[0]) != -1);
2888 input_ = fdopen(fds[1], "a");
2890 _assert(pipe(fds) != -1);
2891 _assert(dup2(fds[1], 1) != -1);
2892 _assert(close(fds[1]) != -1);
2895 detachNewThreadSelector:@selector(_readOutput:)
2897 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2902 - (pkgCacheFile &) cache {
2906 - (pkgDepCache::Policy *) policy {
2910 - (pkgRecords *) records {
2914 - (pkgProblemResolver *) resolver {
2918 - (pkgAcquire &) fetcher {
2922 - (pkgSourceList &) list {
2926 - (NSArray *) packages {
2930 - (NSArray *) sources {
2931 return [sources_ allValues];
2934 - (NSArray *) issues {
2935 if (cache_->BrokenCount() == 0)
2938 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
2940 for (Package *package in packages_) {
2941 if (![package broken])
2943 pkgCache::PkgIterator pkg([package iterator]);
2945 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
2946 [entry addObject:[package name]];
2947 [issues addObject:entry];
2949 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
2953 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
2954 pkgCache::DepIterator start;
2955 pkgCache::DepIterator end;
2956 dep.GlobOr(start, end); // ++dep
2958 if (!cache_->IsImportantDep(end))
2960 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
2963 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
2964 [entry addObject:failure];
2965 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
2967 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
2968 [failure addObject:[package name]];
2970 pkgCache::PkgIterator target(start.TargetPkg());
2971 if (target->ProvidesList != 0)
2972 [failure addObject:@"?"];
2974 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
2976 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
2977 else if (!cache_[target].CandidateVerIter(cache_).end())
2978 [failure addObject:@"-"];
2979 else if (target->ProvidesList == 0)
2980 [failure addObject:@"!"];
2982 [failure addObject:@"%"];
2986 if (start.TargetVer() != 0)
2987 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
2998 - (void) reloadData { _pooled
2999 @synchronized (self) {
3021 apr_pool_clear(pool_);
3022 NSRecycleZone(zone_);
3024 int chk(creat("/tmp/cydia.chk", 0644));
3029 if (!cache_.Open(progress_, true)) {
3031 if (!_error->PopMessage(error))
3034 lprintf("cache_.Open():[%s]\n", error.c_str());
3036 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3037 [delegate_ repairWithSelector:@selector(configure)];
3038 else if (error == "The package lists or status file could not be parsed or opened.")
3039 [delegate_ repairWithSelector:@selector(update)];
3040 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3041 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3042 // else if (error == "The list of sources could not be read.")
3043 else _assert(false);
3049 unlink("/tmp/cydia.chk");
3051 now_ = [[NSDate date] retain];
3053 policy_ = new pkgDepCache::Policy();
3054 records_ = new pkgRecords(cache_);
3055 resolver_ = new pkgProblemResolver(cache_);
3056 fetcher_ = new pkgAcquire(&status_);
3059 list_ = new pkgSourceList();
3060 _assert(list_->ReadMainList());
3062 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3063 _assert(pkgApplyStatus(cache_));
3065 if (cache_->BrokenCount() != 0) {
3066 _assert(pkgFixBroken(cache_));
3067 _assert(cache_->BrokenCount() == 0);
3068 _assert(pkgMinimizeUpgrade(cache_));
3073 std::string lists(_config->FindDir("Dir::State::lists"));
3075 [sources_ removeAllObjects];
3076 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3077 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3078 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3079 if (debPackagesIndex *packages = dynamic_cast<debPackagesIndex *>(*index))
3081 setObject:[[[Source alloc] initWithMetaIndex:*source] autorelease]
3082 forKey:[NSString stringWithFormat:@"%s%s",
3084 URItoFileName(packages->IndexURI("Packages")).c_str()
3092 /*std::vector<Package *> packages;
3093 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3094 [packages_ release];
3097 [packages_ removeAllObjects];
3101 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3102 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3103 //packages.push_back(package);
3104 [packages_ addObject:package];
3108 /*if (packages.empty())
3109 packages_ = [[NSArray alloc] init];
3111 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3114 [packages_ radixSortUsingSelector:@selector(compareByPrefix) withObject:NULL];
3122 /*if (!packages.empty())
3123 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3124 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3126 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3128 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3130 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3136 - (void) configure {
3137 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3138 system([dpkg UTF8String]);
3146 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3147 _assert(!_error->PendingError());
3150 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3153 public pkgArchiveCleaner
3156 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3161 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3163 while (_error->PopMessage(error))
3164 lprintf("ArchiveCleaner: %s\n", error.c_str());
3169 pkgRecords records(cache_);
3171 lock_ = new FileFd();
3172 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3173 _assert(!_error->PendingError());
3176 // XXX: explain this with an error message
3177 _assert(list.ReadMainList());
3179 manager_ = (_system->CreatePM(cache_));
3180 _assert(manager_->GetArchives(fetcher_, &list, &records));
3181 _assert(!_error->PendingError());
3185 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3187 _assert(list.ReadMainList());
3188 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3189 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3192 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3197 bool failed = false;
3198 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3199 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3202 std::string uri = (*item)->DescURI();
3203 std::string error = (*item)->ErrorText;
3205 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3208 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3209 withObject:[NSArray arrayWithObjects:
3210 [NSString stringWithUTF8String:error.c_str()],
3222 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3224 if (_error->PendingError()) {
3229 if (result == pkgPackageManager::Failed) {
3234 if (result != pkgPackageManager::Completed) {
3239 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3241 _assert(list.ReadMainList());
3242 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3243 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3246 if (![before isEqualToArray:after])
3251 _assert(pkgDistUpgrade(cache_));
3255 [self updateWithStatus:status_];
3258 - (void) updateWithStatus:(Status &)status {
3260 _assert(list.ReadMainList());
3263 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3264 _assert(!_error->PendingError());
3266 pkgAcquire fetcher(&status);
3267 _assert(list.GetIndexes(&fetcher));
3269 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3270 bool failed = false;
3271 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3272 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3273 (*item)->Finished();
3277 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3278 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3279 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3282 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3287 - (void) setDelegate:(id)delegate {
3288 delegate_ = delegate;
3289 status_.setDelegate(delegate);
3290 progress_.setDelegate(delegate);
3293 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3294 if (const char *name = file.FileName())
3295 if (Source *source = [sources_ objectForKey:[NSString stringWithUTF8String:name]])
3303 /* PopUp Windows {{{ */
3304 @interface PopUpView : UIView {
3305 _transient id delegate_;
3306 UITransitionView *transition_;
3311 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3315 @implementation PopUpView
3318 [transition_ setDelegate:nil];
3319 [transition_ release];
3325 [transition_ transition:UITransitionPushFromTop toView:nil];
3328 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3329 if (from != nil && to == nil)
3330 [self removeFromSuperview];
3333 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3334 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3335 delegate_ = delegate;
3337 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3338 [self addSubview:transition_];
3340 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3342 [view addSubview:self];
3344 [transition_ setDelegate:self];
3346 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3347 [transition_ transition:UITransitionNone toView:blank];
3348 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3356 /* Mail Composition {{{ */
3357 @interface MailToView : PopUpView {
3358 MailComposeController *controller_;
3361 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3365 @implementation MailToView
3368 [controller_ release];
3372 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3376 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3377 NSLog(@"did:%@", delivery);
3378 // [UIApp setStatusBarShowsProgress:NO];
3379 if ([controller error]){
3380 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3381 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3382 [mailAlertSheet setBodyText:[controller error]];
3383 [mailAlertSheet popupAlertAnimated:YES];
3387 - (void) showError {
3388 NSLog(@"%@", [controller_ error]);
3389 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3390 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3391 [mailAlertSheet setBodyText:[controller_ error]];
3392 [mailAlertSheet popupAlertAnimated:YES];
3395 - (void) deliverMessage { _pooled
3399 if (![controller_ deliverMessage])
3400 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3403 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3404 if ([controller_ needsDelivery])
3405 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3410 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3411 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3412 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3413 [controller_ setDelegate:self];
3414 [controller_ initializeUI];
3415 [controller_ setupForURL:url];
3417 UIView *view([controller_ view]);
3418 [overlay_ addSubview:view];
3426 /* Confirmation View {{{ */
3427 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3428 if (!iterator.end())
3429 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3430 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3432 pkgCache::PkgIterator package(dep.TargetPkg());
3435 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3442 @protocol ConfirmationViewDelegate
3448 @interface ConfirmationView : BrowserView {
3449 _transient Database *database_;
3450 UIActionSheet *essential_;
3457 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3461 @implementation ConfirmationView
3468 if (essential_ != nil)
3469 [essential_ release];
3475 [book_ popFromSuperviewAnimated:YES];
3478 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3479 NSString *context([sheet context]);
3481 if ([context isEqualToString:@"remove"]) {
3489 [delegate_ confirm];
3496 } else if ([context isEqualToString:@"unable"]) {
3500 [super alertSheet:sheet buttonClicked:button];
3503 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3504 [super webView:sender didClearWindowObject:window forFrame:frame];
3505 [window setValue:changes_ forKey:@"changes"];
3506 [window setValue:issues_ forKey:@"issues"];
3507 [window setValue:sizes_ forKey:@"sizes"];
3510 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3511 if ((self = [super initWithBook:book]) != nil) {
3512 database_ = database;
3514 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3515 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3516 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3517 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3518 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3522 pkgDepCache::Policy *policy([database_ policy]);
3524 pkgCacheFile &cache([database_ cache]);
3525 NSArray *packages = [database_ packages];
3526 for (Package *package in packages) {
3527 pkgCache::PkgIterator iterator = [package iterator];
3528 pkgDepCache::StateCache &state(cache[iterator]);
3530 NSString *name([package name]);
3532 if (state.NewInstall())
3533 [installing addObject:name];
3534 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3535 [reinstalling addObject:name];
3536 else if (state.Upgrade())
3537 [upgrading addObject:name];
3538 else if (state.Downgrade())
3539 [downgrading addObject:name];
3540 else if (state.Delete()) {
3541 if ([package essential])
3543 [removing addObject:name];
3546 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3547 substrate_ |= DepSubstrate(iterator.CurrentVer());
3552 else if (Advanced_ || true) {
3553 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3555 essential_ = [[UIActionSheet alloc]
3556 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3557 buttons:[NSArray arrayWithObjects:
3558 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3559 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3561 defaultButtonIndex:0
3567 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3569 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3571 essential_ = [[UIActionSheet alloc]
3572 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3573 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3574 defaultButtonIndex:0
3579 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3582 changes_ = [[NSArray alloc] initWithObjects:
3590 issues_ = [database_ issues];
3592 issues_ = [issues_ retain];
3594 sizes_ = [[NSArray alloc] initWithObjects:
3595 SizeString([database_ fetcher].FetchNeeded()),
3596 SizeString([database_ fetcher].PartialPresent()),
3597 SizeString([database_ cache]->UsrSize()),
3600 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3604 - (NSString *) backButtonTitle {
3605 return CYLocalize("CONFIRM");
3608 - (NSString *) leftButtonTitle {
3609 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3612 - (id) rightButtonTitle {
3613 return issues_ != nil ? nil : [super rightButtonTitle];
3616 - (id) _rightButtonTitle {
3617 #if AlwaysReload || IgnoreInstall
3618 return [super _rightButtonTitle];
3620 return CYLocalize("CONFIRM");
3624 - (void) _leftButtonClicked {
3629 - (void) _rightButtonClicked {
3631 return [super _rightButtonClicked];
3633 if (essential_ != nil)
3634 [essential_ popupAlertAnimated:YES];
3638 [delegate_ confirm];
3646 /* Progress Data {{{ */
3647 @interface ProgressData : NSObject {
3653 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3660 @implementation ProgressData
3662 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3663 if ((self = [super init]) != nil) {
3664 selector_ = selector;
3684 /* Progress View {{{ */
3685 @interface ProgressView : UIView <
3686 ConfigurationDelegate,
3689 _transient Database *database_;
3691 UIView *background_;
3692 UITransitionView *transition_;
3694 UINavigationBar *navbar_;
3695 UIProgressBar *progress_;
3696 UITextView *output_;
3697 UITextLabel *status_;
3698 UIPushButton *close_;
3701 SHA1SumValue springlist_;
3702 SHA1SumValue notifyconf_;
3703 SHA1SumValue sandplate_;
3706 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3708 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3709 - (void) setContentView:(UIView *)view;
3712 - (void) _retachThread;
3713 - (void) _detachNewThreadData:(ProgressData *)data;
3714 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3720 @protocol ProgressViewDelegate
3721 - (void) progressViewIsComplete:(ProgressView *)sender;
3724 @implementation ProgressView
3727 [transition_ setDelegate:nil];
3728 [navbar_ setDelegate:nil];
3731 if (background_ != nil)
3732 [background_ release];
3733 [transition_ release];
3736 [progress_ release];
3743 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3744 if (bootstrap_ && from == overlay_ && to == view_)
3748 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3749 if ((self = [super initWithFrame:frame]) != nil) {
3750 database_ = database;
3751 delegate_ = delegate;
3753 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3754 [transition_ setDelegate:self];
3756 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3759 [overlay_ setBackgroundColor:[UIColor blackColor]];
3761 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3762 [background_ setBackgroundColor:[UIColor blackColor]];
3763 [self addSubview:background_];
3766 [self addSubview:transition_];
3768 CGSize navsize = [UINavigationBar defaultSize];
3769 CGRect navrect = {{0, 0}, navsize};
3771 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3772 [overlay_ addSubview:navbar_];
3774 [navbar_ setBarStyle:1];
3775 [navbar_ setDelegate:self];
3777 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3778 [navbar_ pushNavigationItem:navitem];
3780 CGRect bounds = [overlay_ bounds];
3781 CGSize prgsize = [UIProgressBar defaultSize];
3784 (bounds.size.width - prgsize.width) / 2,
3785 bounds.size.height - prgsize.height - 20
3788 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3789 [progress_ setStyle:0];
3791 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3793 bounds.size.height - prgsize.height - 50,
3794 bounds.size.width - 20,
3798 [status_ setColor:[UIColor whiteColor]];
3799 [status_ setBackgroundColor:[UIColor clearColor]];
3801 [status_ setCentersHorizontally:YES];
3802 //[status_ setFont:font];
3805 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3807 navrect.size.height + 20,
3808 bounds.size.width - 20,
3809 bounds.size.height - navsize.height - 62 - navrect.size.height
3813 //[output_ setTextFont:@"Courier New"];
3814 [output_ setTextSize:12];
3816 [output_ setTextColor:[UIColor whiteColor]];
3817 [output_ setBackgroundColor:[UIColor clearColor]];
3819 [output_ setMarginTop:0];
3820 [output_ setAllowsRubberBanding:YES];
3821 [output_ setEditable:NO];
3823 [overlay_ addSubview:output_];
3825 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3827 bounds.size.height - prgsize.height - 50,
3828 bounds.size.width - 20,
3832 [close_ setAutosizesToFit:NO];
3833 [close_ setDrawsShadow:YES];
3834 [close_ setStretchBackground:YES];
3835 [close_ setEnabled:YES];
3837 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3838 [close_ setTitleFont:bold];
3840 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3841 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3842 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3846 - (void) setContentView:(UIView *)view {
3847 view_ = [view retain];
3850 - (void) resetView {
3851 [transition_ transition:6 toView:view_];
3854 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3855 NSString *context([sheet context]);
3857 if ([context isEqualToString:@"error"])
3859 else if ([context isEqualToString:@"conffile"]) {
3860 FILE *input = [database_ input];
3864 fprintf(input, "N\n");
3868 fprintf(input, "Y\n");
3879 - (void) closeButtonPushed {
3888 [delegate_ suspendWithAnimation:YES];
3892 system("launchctl stop com.apple.SpringBoard");
3896 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
3905 - (void) _retachThread {
3906 UINavigationItem *item = [navbar_ topItem];
3907 [item setTitle:CYLocalize("COMPLETE")];
3909 [overlay_ addSubview:close_];
3910 [progress_ removeFromSuperview];
3911 [status_ removeFromSuperview];
3913 [delegate_ progressViewIsComplete:self];
3916 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
3917 MMap mmap(file, MMap::ReadOnly);
3919 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3920 if (!(sandplate_ == sha1.Result()))
3925 FileFd file(NotifyConfig_, FileFd::ReadOnly);
3926 MMap mmap(file, MMap::ReadOnly);
3928 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3929 if (!(notifyconf_ == sha1.Result()))
3934 FileFd file(SpringBoard_, FileFd::ReadOnly);
3935 MMap mmap(file, MMap::ReadOnly);
3937 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3938 if (!(springlist_ == sha1.Result()))
3943 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
3944 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
3945 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
3946 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
3947 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
3950 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
3952 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
3953 [cache autorelease];
3955 NSFileManager *manager = [NSFileManager defaultManager];
3956 NSError *error = nil;
3958 id system = [cache objectForKey:@"System"];
3963 if (stat(Cache_, &info) == -1)
3966 [system removeAllObjects];
3968 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
3969 for (NSString *app in apps)
3970 if ([app hasSuffix:@".app"]) {
3971 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
3972 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
3973 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
3975 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
3976 [info setObject:path forKey:@"Path"];
3977 [info setObject:@"System" forKey:@"ApplicationType"];
3978 [system addInfoDictionary:info];
3984 [cache writeToFile:@Cache_ atomically:YES];
3986 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
3988 if (chmod(Cache_, info.st_mode) == -1)
3992 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
3995 notify_post("com.apple.mobile.application_installed");
3997 [delegate_ setStatusBarShowsProgress:NO];
4000 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4001 [[data target] performSelector:[data selector] withObject:[data object]];
4004 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4007 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4008 UINavigationItem *item = [navbar_ topItem];
4009 [item setTitle:title];
4011 [status_ setText:nil];
4012 [output_ setText:@""];
4013 [progress_ setProgress:0];
4015 [close_ removeFromSuperview];
4016 [overlay_ addSubview:progress_];
4017 [overlay_ addSubview:status_];
4019 [delegate_ setStatusBarShowsProgress:YES];
4023 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4024 MMap mmap(file, MMap::ReadOnly);
4026 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4027 sandplate_ = sha1.Result();
4031 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4032 MMap mmap(file, MMap::ReadOnly);
4034 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4035 notifyconf_ = sha1.Result();
4039 FileFd file(SpringBoard_, FileFd::ReadOnly);
4040 MMap mmap(file, MMap::ReadOnly);
4042 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4043 springlist_ = sha1.Result();
4046 [transition_ transition:6 toView:overlay_];
4049 detachNewThreadSelector:@selector(_detachNewThreadData:)
4051 withObject:[[ProgressData alloc]
4052 initWithSelector:selector
4059 - (void) repairWithSelector:(SEL)selector {
4061 detachNewThreadSelector:selector
4064 title:CYLocalize("REPAIRING")
4068 - (void) setConfigurationData:(NSString *)data {
4070 performSelectorOnMainThread:@selector(_setConfigurationData:)
4076 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4077 Package *package = id == nil ? nil : [database_ packageWithName:id];
4079 UIActionSheet *sheet = [[[UIActionSheet alloc]
4080 initWithTitle:(package == nil ? id : [package name])
4081 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4082 defaultButtonIndex:0
4087 [sheet setBodyText:error];
4088 [sheet popupAlertAnimated:YES];
4091 - (void) setProgressTitle:(NSString *)title {
4093 performSelectorOnMainThread:@selector(_setProgressTitle:)
4099 - (void) setProgressPercent:(float)percent {
4101 performSelectorOnMainThread:@selector(_setProgressPercent:)
4102 withObject:[NSNumber numberWithFloat:percent]
4107 - (void) startProgress {
4110 - (void) addProgressOutput:(NSString *)output {
4112 performSelectorOnMainThread:@selector(_addProgressOutput:)
4118 - (bool) isCancelling:(size_t)received {
4122 - (void) _setConfigurationData:(NSString *)data {
4123 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4125 _assert(conffile_r(data));
4127 NSString *ofile = conffile_r[1];
4128 //NSString *nfile = conffile_r[2];
4130 UIActionSheet *sheet = [[[UIActionSheet alloc]
4131 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
4132 buttons:[NSArray arrayWithObjects:
4133 CYLocalize("KEEP_OLD_COPY"),
4134 CYLocalize("ACCEPT_NEW_COPY"),
4135 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
4137 defaultButtonIndex:0
4142 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4143 [sheet popupAlertAnimated:YES];
4146 - (void) _setProgressTitle:(NSString *)title {
4147 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4148 for (size_t i(0), e([words count]); i != e; ++i) {
4149 NSString *word([words objectAtIndex:i]);
4150 if (Package *package = [database_ packageWithName:word])
4151 [words replaceObjectAtIndex:i withObject:[package name]];
4154 [status_ setText:[words componentsJoinedByString:@" "]];
4157 - (void) _setProgressPercent:(NSNumber *)percent {
4158 [progress_ setProgress:[percent floatValue]];
4161 - (void) _addProgressOutput:(NSString *)output {
4162 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4163 CGSize size = [output_ contentSize];
4164 CGRect rect = {{0, size.height}, {size.width, 0}};
4165 [output_ scrollRectToVisible:rect animated:YES];
4168 - (BOOL) isRunning {
4175 /* Package Cell {{{ */
4176 @interface PackageCell : UITableCell {
4179 NSString *description_;
4186 UITextLabel *status_;
4190 - (PackageCell *) init;
4191 - (void) setPackage:(Package *)package;
4193 + (int) heightForPackage:(Package *)package;
4197 @implementation PackageCell
4199 - (void) clearPackage {
4210 if (description_ != nil) {
4211 [description_ release];
4215 if (source_ != nil) {
4220 if (badge_ != nil) {
4230 [self clearPackage];
4237 - (PackageCell *) init {
4238 if ((self = [super init]) != nil) {
4240 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4241 [status_ setBackgroundColor:[UIColor clearColor]];
4242 [status_ setFont:small];
4247 - (void) setPackage:(Package *)package {
4248 [self clearPackage];
4250 Source *source = [package source];
4252 icon_ = [[package icon] retain];
4253 name_ = [[package name] retain];
4254 description_ = [[package shortDescription] retain];
4255 commercial_ = [package isCommercial];
4257 package_ = [package retain];
4259 NSString *label = nil;
4260 bool trusted = false;
4262 if (source != nil) {
4263 label = [source label];
4264 trusted = [source trusted];
4265 } else if ([[package id] isEqualToString:@"firmware"])
4266 label = CYLocalize("APPLE");
4268 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4270 NSString *from(label);
4272 NSString *section = [package simpleSection];
4273 if (section != nil && ![section isEqualToString:label]) {
4274 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4275 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4278 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4279 source_ = [from retain];
4281 if (NSString *purpose = [package primaryPurpose])
4282 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4283 badge_ = [badge_ retain];
4286 if (NSString *mode = [package mode]) {
4287 [badge_ setImage:[UIImage applicationImageNamed:
4288 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4291 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4292 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4293 } else if ([package half]) {
4294 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4295 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4296 [status_ setColor:[UIColor redColor]];
4298 [badge_ setImage:nil];
4299 [status_ setText:nil];
4306 - (void) drawRect:(CGRect)rect {
4310 if (NSString *mode = [package_ mode]) {
4311 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4312 color = remove ? RemovingColor_ : InstallingColor_;
4314 color = [UIColor whiteColor];
4316 [self setBackgroundColor:color];
4320 [super drawRect:rect];
4323 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4325 CGContextRef context(UIGraphicsGetCurrentContext());
4326 [[self backgroundColor] set];
4328 back.size.height -= 1;
4329 CGContextFillRect(context, back);
4332 [super drawBackgroundInRect:rect withFade:fade];
4335 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4338 rect.size = [icon_ size];
4340 rect.size.width /= 2;
4341 rect.size.height /= 2;
4343 rect.origin.x = 25 - rect.size.width / 2;
4344 rect.origin.y = 25 - rect.size.height / 2;
4346 [icon_ drawInRect:rect];
4349 if (badge_ != nil) {
4350 CGSize size = [badge_ size];
4352 [badge_ drawAtPoint:CGPointMake(
4353 36 - size.width / 2,
4354 36 - size.height / 2
4362 UISetColor(commercial_ ? Purple_ : Black_);
4363 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4364 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4367 UISetColor(commercial_ ? Purplish_ : Gray_);
4368 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4370 [super drawContentInRect:rect selected:selected];
4373 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4375 [super setSelected:selected withFade:fade];
4378 + (int) heightForPackage:(Package *)package {
4379 NSString *tagline([package shortDescription]);
4380 int height = tagline == nil || [tagline length] == 0 ? -17 : 0;
4382 if ([package hasMode] || [package half])
4391 /* Section Cell {{{ */
4392 @interface SectionCell : UISimpleTableCell {
4397 _UISwitchSlider *switch_;
4402 - (void) setSection:(Section *)section editing:(BOOL)editing;
4406 @implementation SectionCell
4408 - (void) clearSection {
4409 if (section_ != nil) {
4419 if (count_ != nil) {
4426 [self clearSection];
4433 if ((self = [super init]) != nil) {
4434 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4436 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4437 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4441 - (void) onSwitch:(id)sender {
4442 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4443 if (metadata == nil) {
4444 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4445 [Sections_ setObject:metadata forKey:section_];
4449 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4452 - (void) setSection:(Section *)section editing:(BOOL)editing {
4453 if (editing != editing_) {
4455 [switch_ removeFromSuperview];
4457 [self addSubview:switch_];
4461 [self clearSection];
4463 if (section == nil) {
4464 name_ = [CYLocalize("ALL_PACKAGES") retain];
4467 section_ = [section localized];
4468 if (section_ != nil)
4469 section_ = [section_ retain];
4470 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4471 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4474 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4478 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4479 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4486 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4488 CGSize size = [count_ sizeWithFont:Font14_];
4492 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4494 [super drawContentInRect:rect selected:selected];
4500 /* File Table {{{ */
4501 @interface FileTable : RVPage {
4502 _transient Database *database_;
4505 NSMutableArray *files_;
4509 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4510 - (void) setPackage:(Package *)package;
4514 @implementation FileTable
4517 if (package_ != nil)
4526 - (int) numberOfRowsInTable:(UITable *)table {
4527 return files_ == nil ? 0 : [files_ count];
4530 - (float) table:(UITable *)table heightForRow:(int)row {
4534 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4535 if (reusing == nil) {
4536 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4537 UIFont *font = [UIFont systemFontOfSize:16];
4538 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4540 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4544 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4548 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4549 if ((self = [super initWithBook:book]) != nil) {
4550 database_ = database;
4552 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4554 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4555 [self addSubview:list_];
4557 UITableColumn *column = [[[UITableColumn alloc]
4558 initWithTitle:CYLocalize("NAME")
4560 width:[self frame].size.width
4563 [list_ setDataSource:self];
4564 [list_ setSeparatorStyle:1];
4565 [list_ addTableColumn:column];
4566 [list_ setDelegate:self];
4567 [list_ setReusesTableCells:YES];
4571 - (void) setPackage:(Package *)package {
4572 if (package_ != nil) {
4573 [package_ autorelease];
4582 [files_ removeAllObjects];
4584 if (package != nil) {
4585 package_ = [package retain];
4586 name_ = [[package id] retain];
4588 if (NSArray *files = [package files])
4589 [files_ addObjectsFromArray:files];
4591 if ([files_ count] != 0) {
4592 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4593 [files_ removeObjectAtIndex:0];
4594 [files_ sortUsingSelector:@selector(compareByPath:)];
4596 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4597 [stack addObject:@"/"];
4599 for (int i(0), e([files_ count]); i != e; ++i) {
4600 NSString *file = [files_ objectAtIndex:i];
4601 while (![file hasPrefix:[stack lastObject]])
4602 [stack removeLastObject];
4603 NSString *directory = [stack lastObject];
4604 [stack addObject:[file stringByAppendingString:@"/"]];
4605 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4606 ([stack count] - 2) * 3, "",
4607 [file substringFromIndex:[directory length]]
4616 - (void) resetViewAnimated:(BOOL)animated {
4617 [list_ resetViewAnimated:animated];
4620 - (void) reloadData {
4621 [self setPackage:[database_ packageWithName:name_]];
4622 [self reloadButtons];
4625 - (NSString *) title {
4626 return CYLocalize("INSTALLED_FILES");
4629 - (NSString *) backButtonTitle {
4630 return CYLocalize("FILES");
4635 /* Package View {{{ */
4636 @interface PackageView : BrowserView {
4637 _transient Database *database_;
4641 NSMutableArray *buttons_;
4644 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4645 - (void) setPackage:(Package *)package;
4649 @implementation PackageView
4652 if (package_ != nil)
4661 if ([self retainCount] == 1)
4662 [delegate_ setPackageView:self];
4666 /* XXX: this is not safe at all... localization of /fail/ */
4667 - (void) _clickButtonWithName:(NSString *)name {
4668 if ([name isEqualToString:CYLocalize("CLEAR")])
4669 [delegate_ clearPackage:package_];
4670 else if ([name isEqualToString:CYLocalize("INSTALL")])
4671 [delegate_ installPackage:package_];
4672 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4673 [delegate_ installPackage:package_];
4674 else if ([name isEqualToString:CYLocalize("REMOVE")])
4675 [delegate_ removePackage:package_];
4676 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4677 [delegate_ installPackage:package_];
4678 else _assert(false);
4681 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4682 NSString *context([sheet context]);
4684 if ([context isEqualToString:@"modify"]) {
4685 int count = [buttons_ count];
4686 _assert(count != 0);
4687 _assert(button <= count + 1);
4689 if (count != button - 1)
4690 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4694 [super alertSheet:sheet buttonClicked:button];
4697 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4698 return [super webView:sender didFinishLoadForFrame:frame];
4701 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4702 [super webView:sender didClearWindowObject:window forFrame:frame];
4703 [window setValue:package_ forKey:@"package"];
4706 - (bool) _allowJavaScriptPanel {
4711 - (void) __rightButtonClicked {
4712 int count = [buttons_ count];
4713 _assert(count != 0);
4716 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4718 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4719 [buttons addObjectsFromArray:buttons_];
4720 [buttons addObject:CYLocalize("CANCEL")];
4722 [delegate_ slideUp:[[[UIActionSheet alloc]
4725 defaultButtonIndex:([buttons count] - 1)
4732 - (void) _rightButtonClicked {
4734 [super _rightButtonClicked];
4736 [self __rightButtonClicked];
4740 - (id) _rightButtonTitle {
4741 int count = [buttons_ count];
4742 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4745 - (NSString *) backButtonTitle {
4749 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4750 if ((self = [super initWithBook:book]) != nil) {
4751 database_ = database;
4752 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4753 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4757 - (void) setPackage:(Package *)package {
4758 if (package_ != nil) {
4759 [package_ autorelease];
4768 [buttons_ removeAllObjects];
4770 if (package != nil) {
4771 package_ = [package retain];
4772 name_ = [[package id] retain];
4773 commercial_ = [package isCommercial];
4775 if ([package_ mode] != nil)
4776 [buttons_ addObject:CYLocalize("CLEAR")];
4777 if ([package_ source] == nil);
4778 else if ([package_ upgradableAndEssential:NO])
4779 [buttons_ addObject:CYLocalize("UPGRADE")];
4780 else if ([package_ installed] == nil)
4781 [buttons_ addObject:CYLocalize("INSTALL")];
4783 [buttons_ addObject:CYLocalize("REINSTALL")];
4784 if ([package_ installed] != nil)
4785 [buttons_ addObject:CYLocalize("REMOVE")];
4787 if (special_ != NULL) {
4788 CGRect frame([webview_ frame]);
4789 frame.size.width = 320;
4790 frame.size.height = 0;
4791 [webview_ setFrame:frame];
4793 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4796 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4798 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4800 [self setFinishHook:nil];
4801 [self setPopupHook:nil];
4804 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
4805 [super callFunction:special_];
4809 [self reloadButtons];
4812 - (bool) isLoading {
4813 return commercial_ ? [super isLoading] : false;
4816 - (void) reloadData {
4817 [self setPackage:[database_ packageWithName:name_]];
4822 /* Package Table {{{ */
4823 @interface PackageTable : RVPage {
4824 _transient Database *database_;
4826 NSMutableArray *packages_;
4827 NSMutableArray *sections_;
4828 UISectionList *list_;
4831 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
4833 - (void) setDelegate:(id)delegate;
4835 - (void) reloadData;
4836 - (void) resetCursor;
4838 - (UISectionList *) list;
4840 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4844 @implementation PackageTable
4847 [list_ setDataSource:nil];
4850 [packages_ release];
4851 [sections_ release];
4856 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4857 return [sections_ count];
4860 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4861 return [[sections_ objectAtIndex:section] name];
4864 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4865 return [[sections_ objectAtIndex:section] row];
4868 - (int) numberOfRowsInTable:(UITable *)table {
4869 return [packages_ count];
4872 - (float) table:(UITable *)table heightForRow:(int)row {
4873 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
4876 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4878 reusing = [[[PackageCell alloc] init] autorelease];
4879 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
4883 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
4887 - (void) tableRowSelected:(NSNotification *)notification {
4888 int row = [[notification object] selectedRow];
4892 Package *package = [packages_ objectAtIndex:row];
4893 package = [database_ packageWithName:[package id]];
4894 PackageView *view([delegate_ packageView]);
4895 [view setPackage:package];
4896 [view setDelegate:delegate_];
4897 [book_ pushPage:view];
4900 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
4901 if ((self = [super initWithBook:book]) != nil) {
4902 database_ = database;
4903 title_ = [title retain];
4905 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
4906 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
4908 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
4909 [list_ setDataSource:self];
4911 UITableColumn *column = [[[UITableColumn alloc]
4912 initWithTitle:CYLocalize("NAME")
4914 width:[self frame].size.width
4917 UITable *table = [list_ table];
4918 [table setSeparatorStyle:1];
4919 [table addTableColumn:column];
4920 [table setDelegate:self];
4921 [table setReusesTableCells:YES];
4923 [self addSubview:list_];
4925 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4926 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4930 - (void) setDelegate:(id)delegate {
4931 delegate_ = delegate;
4934 - (bool) hasPackage:(Package *)package {
4938 - (void) reloadData {
4939 NSArray *packages = [database_ packages];
4941 [packages_ removeAllObjects];
4942 [sections_ removeAllObjects];
4944 _profile(PackageTable$reloadData$Filter)
4945 for (Package *package in packages)
4946 if ([self hasPackage:package])
4947 [packages_ addObject:package];
4950 Section *section = nil;
4952 _profile(PackageTable$reloadData$Section)
4953 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
4957 _profile(PackageTable$reloadData$Section$Package)
4958 package = [packages_ objectAtIndex:offset];
4959 index = [package index];
4962 if (section == nil || [section index] != index) {
4963 _profile(PackageTable$reloadData$Section$Allocate)
4964 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
4967 _profile(PackageTable$reloadData$Section$Add)
4968 [sections_ addObject:section];
4972 [section addToCount];
4976 _profile(PackageTable$reloadData$List)
4981 - (NSString *) title {
4985 - (void) resetViewAnimated:(BOOL)animated {
4986 [list_ resetViewAnimated:animated];
4989 - (void) resetCursor {
4990 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
4993 - (UISectionList *) list {
4997 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
4998 [list_ setShouldHideHeaderInShortLists:hide];
5003 /* Filtered Package Table {{{ */
5004 @interface FilteredPackageTable : PackageTable {
5010 - (void) setObject:(id)object;
5012 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5016 @implementation FilteredPackageTable
5024 - (void) setObject:(id)object {
5030 object_ = [object retain];
5033 - (bool) hasPackage:(Package *)package {
5034 _profile(FilteredPackageTable$hasPackage)
5035 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5039 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5040 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5042 object_ = object == nil ? nil : [object retain];
5044 /* XXX: this is an unsafe optimization of doomy hell */
5045 Method method = class_getInstanceMethod([Package class], filter);
5046 _assert(method != NULL);
5047 imp_ = method_getImplementation(method);
5048 _assert(imp_ != NULL);
5057 /* Add Source View {{{ */
5058 @interface AddSourceView : RVPage {
5059 _transient Database *database_;
5062 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5066 @implementation AddSourceView
5068 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5069 if ((self = [super initWithBook:book]) != nil) {
5070 database_ = database;
5076 /* Source Cell {{{ */
5077 @interface SourceCell : UITableCell {
5080 NSString *description_;
5086 - (SourceCell *) initWithSource:(Source *)source;
5090 @implementation SourceCell
5095 [description_ release];
5100 - (SourceCell *) initWithSource:(Source *)source {
5101 if ((self = [super init]) != nil) {
5103 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5105 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5106 icon_ = [icon_ retain];
5108 origin_ = [[source name] retain];
5109 label_ = [[source uri] retain];
5110 description_ = [[source description] retain];
5114 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5116 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5123 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5127 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5131 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5133 [super drawContentInRect:rect selected:selected];
5138 /* Source Table {{{ */
5139 @interface SourceTable : RVPage {
5140 _transient Database *database_;
5141 UISectionList *list_;
5142 NSMutableArray *sources_;
5143 UIActionSheet *alert_;
5147 UIProgressHUD *hud_;
5150 //NSURLConnection *installer_;
5151 NSURLConnection *trivial_bz2_;
5152 NSURLConnection *trivial_gz_;
5153 //NSURLConnection *automatic_;
5158 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5162 @implementation SourceTable
5164 - (void) _deallocConnection:(NSURLConnection *)connection {
5165 if (connection != nil) {
5166 [connection cancel];
5167 //[connection setDelegate:nil];
5168 [connection release];
5173 [[list_ table] setDelegate:nil];
5174 [list_ setDataSource:nil];
5183 //[self _deallocConnection:installer_];
5184 [self _deallocConnection:trivial_gz_];
5185 [self _deallocConnection:trivial_bz2_];
5186 //[self _deallocConnection:automatic_];
5193 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5194 return offset_ == 0 ? 1 : 2;
5197 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5198 switch (section + (offset_ == 0 ? 1 : 0)) {
5199 case 0: return CYLocalize("ENTERED_BY_USER");
5200 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5208 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5209 switch (section + (offset_ == 0 ? 1 : 0)) {
5211 case 1: return offset_;
5219 - (int) numberOfRowsInTable:(UITable *)table {
5220 return [sources_ count];
5223 - (float) table:(UITable *)table heightForRow:(int)row {
5224 Source *source = [sources_ objectAtIndex:row];
5225 return [source description] == nil ? 56 : 73;
5228 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5229 Source *source = [sources_ objectAtIndex:row];
5230 // XXX: weird warning, stupid selectors ;P
5231 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5234 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5238 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5242 - (void) tableRowSelected:(NSNotification*)notification {
5243 UITable *table([list_ table]);
5244 int row([table selectedRow]);
5248 Source *source = [sources_ objectAtIndex:row];
5250 PackageTable *packages = [[[FilteredPackageTable alloc]
5253 title:[source label]
5254 filter:@selector(isVisibleInSource:)
5258 [packages setDelegate:delegate_];
5260 [book_ pushPage:packages];
5263 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5264 Source *source = [sources_ objectAtIndex:row];
5265 return [source record] != nil;
5268 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5269 [[list_ table] setDeleteConfirmationRow:row];
5272 - (void) table:(UITable *)table deleteRow:(int)row {
5273 Source *source = [sources_ objectAtIndex:row];
5274 [Sources_ removeObjectForKey:[source key]];
5275 [delegate_ syncData];
5279 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5282 @"./", @"Distribution",
5283 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5285 [delegate_ syncData];
5288 - (NSString *) getWarning {
5289 NSString *href(href_);
5290 NSRange colon([href rangeOfString:@"://"]);
5291 if (colon.location != NSNotFound)
5292 href = [href substringFromIndex:(colon.location + 3)];
5293 href = [href stringByAddingPercentEscapes];
5294 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5295 href = [href stringByCachingURLWithCurrentCDN];
5297 NSURL *url([NSURL URLWithString:href]);
5299 NSStringEncoding encoding;
5300 NSError *error(nil);
5302 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5303 return [warning length] == 0 ? nil : warning;
5307 - (void) _endConnection:(NSURLConnection *)connection {
5308 NSURLConnection **field = NULL;
5309 if (connection == trivial_bz2_)
5310 field = &trivial_bz2_;
5311 else if (connection == trivial_gz_)
5312 field = &trivial_gz_;
5313 _assert(field != NULL);
5314 [connection release];
5318 trivial_bz2_ == nil &&
5324 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5327 UIActionSheet *sheet = [[[UIActionSheet alloc]
5328 initWithTitle:CYLocalize("SOURCE_WARNING")
5329 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5330 defaultButtonIndex:0
5335 [sheet setNumberOfRows:1];
5337 [sheet setBodyText:warning];
5338 [sheet popupAlertAnimated:YES];
5341 } else if (error_ != nil) {
5342 UIActionSheet *sheet = [[[UIActionSheet alloc]
5343 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5344 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5345 defaultButtonIndex:0
5350 [sheet setBodyText:[error_ localizedDescription]];
5351 [sheet popupAlertAnimated:YES];
5353 UIActionSheet *sheet = [[[UIActionSheet alloc]
5354 initWithTitle:CYLocalize("NOT_REPOSITORY")
5355 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5356 defaultButtonIndex:0
5361 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5362 [sheet popupAlertAnimated:YES];
5365 [delegate_ setStatusBarShowsProgress:NO];
5366 [delegate_ removeProgressHUD:hud_];
5376 if (error_ != nil) {
5383 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5384 switch ([response statusCode]) {
5390 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5391 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5393 error_ = [error retain];
5394 [self _endConnection:connection];
5397 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5398 [self _endConnection:connection];
5401 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5402 NSMutableURLRequest *request = [NSMutableURLRequest
5403 requestWithURL:[NSURL URLWithString:href]
5404 cachePolicy:NSURLRequestUseProtocolCachePolicy
5405 timeoutInterval:20.0
5408 [request setHTTPMethod:method];
5410 if (Machine_ != NULL)
5411 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5412 if (UniqueID_ != nil)
5413 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5416 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5418 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5421 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5422 NSString *context([sheet context]);
5424 if ([context isEqualToString:@"source"]) {
5427 NSString *href = [[sheet textField] text];
5429 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5431 if (![href hasSuffix:@"/"])
5432 href_ = [href stringByAppendingString:@"/"];
5435 href_ = [href_ retain];
5437 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5438 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5439 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5443 hud_ = [[delegate_ addProgressHUD] retain];
5444 [hud_ setText:CYLocalize("VERIFYING_URL")];
5455 } else if ([context isEqualToString:@"trivial"])
5457 else if ([context isEqualToString:@"urlerror"])
5459 else if ([context isEqualToString:@"warning"]) {
5479 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5480 if ((self = [super initWithBook:book]) != nil) {
5481 database_ = database;
5482 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5484 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5485 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5486 [list_ setShouldHideHeaderInShortLists:NO];
5488 [self addSubview:list_];
5489 [list_ setDataSource:self];
5491 UITableColumn *column = [[UITableColumn alloc]
5492 initWithTitle:CYLocalize("NAME")
5494 width:[self frame].size.width
5497 UITable *table = [list_ table];
5498 [table setSeparatorStyle:1];
5499 [table addTableColumn:column];
5500 [table setDelegate:self];
5504 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5505 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5509 - (void) reloadData {
5511 _assert(list.ReadMainList());
5513 [sources_ removeAllObjects];
5514 [sources_ addObjectsFromArray:[database_ sources]];
5516 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5519 int count = [sources_ count];
5520 for (offset_ = 0; offset_ != count; ++offset_) {
5521 Source *source = [sources_ objectAtIndex:offset_];
5522 if ([source record] == nil)
5529 - (void) resetViewAnimated:(BOOL)animated {
5530 [list_ resetViewAnimated:animated];
5533 - (void) _leftButtonClicked {
5534 /*[book_ pushPage:[[[AddSourceView alloc]
5539 UIActionSheet *sheet = [[[UIActionSheet alloc]
5540 initWithTitle:CYLocalize("ENTER_APT_URL")
5541 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5542 defaultButtonIndex:0
5547 [sheet setNumberOfRows:1];
5549 [sheet addTextFieldWithValue:@"http://" label:@""];
5551 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5552 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5553 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5554 [traits setKeyboardType:UIKeyboardTypeURL];
5555 // XXX: UIReturnKeyDone
5556 [traits setReturnKeyType:UIReturnKeyNext];
5558 [sheet popupAlertAnimated:YES];
5561 - (void) _rightButtonClicked {
5562 UITable *table = [list_ table];
5563 BOOL editing = [table isRowDeletionEnabled];
5564 [table enableRowDeletion:!editing animated:YES];
5565 [book_ reloadButtonsForPage:self];
5568 - (NSString *) title {
5569 return CYLocalize("SOURCES");
5572 - (NSString *) leftButtonTitle {
5573 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5576 - (id) rightButtonTitle {
5577 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5580 - (UINavigationButtonStyle) rightButtonStyle {
5581 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5587 /* Installed View {{{ */
5588 @interface InstalledView : RVPage {
5589 _transient Database *database_;
5590 FilteredPackageTable *packages_;
5594 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5598 @implementation InstalledView
5601 [packages_ release];
5605 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5606 if ((self = [super initWithBook:book]) != nil) {
5607 database_ = database;
5609 packages_ = [[FilteredPackageTable alloc]
5613 filter:@selector(isInstalledAndVisible:)
5614 with:[NSNumber numberWithBool:YES]
5617 [self addSubview:packages_];
5619 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5620 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5624 - (void) resetViewAnimated:(BOOL)animated {
5625 [packages_ resetViewAnimated:animated];
5628 - (void) reloadData {
5629 [packages_ reloadData];
5632 - (void) _rightButtonClicked {
5633 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5634 [packages_ reloadData];
5636 [book_ reloadButtonsForPage:self];
5639 - (NSString *) title {
5640 return CYLocalize("INSTALLED");
5643 - (NSString *) backButtonTitle {
5644 return CYLocalize("PACKAGES");
5647 - (id) rightButtonTitle {
5648 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5651 - (UINavigationButtonStyle) rightButtonStyle {
5652 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5655 - (void) setDelegate:(id)delegate {
5656 [super setDelegate:delegate];
5657 [packages_ setDelegate:delegate];
5664 @interface HomeView : BrowserView {
5669 @implementation HomeView
5671 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5672 NSString *context([sheet context]);
5674 if ([context isEqualToString:@"about"])
5677 [super alertSheet:sheet buttonClicked:button];
5680 - (void) _leftButtonClicked {
5681 UIActionSheet *sheet = [[[UIActionSheet alloc]
5682 initWithTitle:CYLocalize("ABOUT_CYDIA")
5683 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5684 defaultButtonIndex:0
5690 @"Copyright (C) 2008-2009\n"
5691 "Jay Freeman (saurik)\n"
5692 "saurik@saurik.com\n"
5693 "http://www.saurik.com/\n"
5696 "http://www.theokorigroup.com/\n"
5698 "College of Creative Studies,\n"
5699 "University of California,\n"
5701 "http://www.ccs.ucsb.edu/"
5704 [sheet popupAlertAnimated:YES];
5707 - (NSString *) leftButtonTitle {
5708 return CYLocalize("ABOUT");
5713 /* Manage View {{{ */
5714 @interface ManageView : BrowserView {
5719 @implementation ManageView
5721 - (NSString *) title {
5722 return CYLocalize("MANAGE");
5725 - (void) _leftButtonClicked {
5726 [delegate_ askForSettings];
5729 - (NSString *) leftButtonTitle {
5730 return CYLocalize("SETTINGS");
5734 - (id) _rightButtonTitle {
5735 return Queuing_ ? CYLocalize("QUEUE") : nil;
5738 - (UINavigationButtonStyle) rightButtonStyle {
5739 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5742 - (void) _rightButtonClicked {
5747 - (bool) isLoading {
5754 #include <BrowserView.m>
5756 /* Cydia Book {{{ */
5757 @interface CYBook : RVBook <
5760 _transient Database *database_;
5761 UINavigationBar *overlay_;
5762 UINavigationBar *underlay_;
5763 UIProgressIndicator *indicator_;
5764 UITextLabel *prompt_;
5765 UIProgressBar *progress_;
5766 UINavigationButton *cancel_;
5770 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5776 @implementation CYBook
5780 [indicator_ release];
5782 [progress_ release];
5787 - (NSString *) getTitleForPage:(RVPage *)page {
5788 return [super getTitleForPage:page];
5796 [UIView beginAnimations:nil context:NULL];
5798 CGRect ovrframe = [overlay_ frame];
5799 ovrframe.origin.y = 0;
5800 [overlay_ setFrame:ovrframe];
5802 CGRect barframe = [navbar_ frame];
5803 barframe.origin.y += ovrframe.size.height;
5804 [navbar_ setFrame:barframe];
5806 CGRect trnframe = [transition_ frame];
5807 trnframe.origin.y += ovrframe.size.height;
5808 trnframe.size.height -= ovrframe.size.height;
5809 [transition_ setFrame:trnframe];
5811 [UIView endAnimations];
5813 [indicator_ startAnimation];
5814 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5815 [progress_ setProgress:0];
5818 [overlay_ addSubview:cancel_];
5821 detachNewThreadSelector:@selector(_update)
5830 [indicator_ stopAnimation];
5832 [UIView beginAnimations:nil context:NULL];
5834 CGRect ovrframe = [overlay_ frame];
5835 ovrframe.origin.y = -ovrframe.size.height;
5836 [overlay_ setFrame:ovrframe];
5838 CGRect barframe = [navbar_ frame];
5839 barframe.origin.y -= ovrframe.size.height;
5840 [navbar_ setFrame:barframe];
5842 CGRect trnframe = [transition_ frame];
5843 trnframe.origin.y -= ovrframe.size.height;
5844 trnframe.size.height += ovrframe.size.height;
5845 [transition_ setFrame:trnframe];
5847 [UIView commitAnimations];
5849 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5852 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
5853 if ((self = [super initWithFrame:frame]) != nil) {
5854 database_ = database;
5856 CGRect ovrrect = [navbar_ bounds];
5857 ovrrect.size.height = [UINavigationBar defaultSize].height;
5858 ovrrect.origin.y = -ovrrect.size.height;
5860 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5861 [self addSubview:overlay_];
5863 ovrrect.origin.y = frame.size.height;
5864 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5865 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
5866 [self addSubview:underlay_];
5868 [overlay_ setBarStyle:1];
5869 [underlay_ setBarStyle:1];
5871 int barstyle = [overlay_ _barStyle:NO];
5872 bool ugly = barstyle == 0;
5874 UIProgressIndicatorStyle style = ugly ?
5875 UIProgressIndicatorStyleMediumBrown :
5876 UIProgressIndicatorStyleMediumWhite;
5878 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
5879 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
5880 CGRect indrect = {{indoffset, indoffset}, indsize};
5882 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
5883 [indicator_ setStyle:style];
5884 [overlay_ addSubview:indicator_];
5886 CGSize prmsize = {215, indsize.height + 4};
5889 indoffset * 2 + indsize.width,
5893 unsigned(ovrrect.size.height - prmsize.height) / 2
5896 UIFont *font = [UIFont systemFontOfSize:15];
5898 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
5900 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
5901 [prompt_ setBackgroundColor:[UIColor clearColor]];
5902 [prompt_ setFont:font];
5904 [overlay_ addSubview:prompt_];
5906 CGSize prgsize = {75, 100};
5909 ovrrect.size.width - prgsize.width - 10,
5910 (ovrrect.size.height - prgsize.height) / 2
5913 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
5914 [progress_ setStyle:0];
5915 [overlay_ addSubview:progress_];
5917 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
5918 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
5920 CGRect frame = [cancel_ frame];
5921 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
5922 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
5923 [cancel_ setFrame:frame];
5925 [cancel_ setBarStyle:barstyle];
5929 - (void) _onCancel {
5931 [cancel_ removeFromSuperview];
5934 - (void) _update { _pooled
5936 status.setDelegate(self);
5938 [database_ updateWithStatus:status];
5941 performSelectorOnMainThread:@selector(_update_)
5947 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
5948 [prompt_ setText:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), error]];
5951 - (void) setProgressTitle:(NSString *)title {
5953 performSelectorOnMainThread:@selector(_setProgressTitle:)
5959 - (void) setProgressPercent:(float)percent {
5961 performSelectorOnMainThread:@selector(_setProgressPercent:)
5962 withObject:[NSNumber numberWithFloat:percent]
5967 - (void) startProgress {
5970 - (void) addProgressOutput:(NSString *)output {
5972 performSelectorOnMainThread:@selector(_addProgressOutput:)
5978 - (bool) isCancelling:(size_t)received {
5982 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5986 - (void) _setProgressTitle:(NSString *)title {
5987 [prompt_ setText:title];
5990 - (void) _setProgressPercent:(NSNumber *)percent {
5991 [progress_ setProgress:[percent floatValue]];
5994 - (void) _addProgressOutput:(NSString *)output {
5999 /* Cydia:// Protocol {{{ */
6000 @interface CydiaURLProtocol : NSURLProtocol {
6005 @implementation CydiaURLProtocol
6007 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6008 NSURL *url([request URL]);
6011 NSString *scheme([[url scheme] lowercaseString]);
6012 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6017 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6021 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6022 id<NSURLProtocolClient> client([self client]);
6024 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6026 NSData *data(UIImagePNGRepresentation(icon));
6028 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6029 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6030 [client URLProtocol:self didLoadData:data];
6031 [client URLProtocolDidFinishLoading:self];
6035 - (void) startLoading {
6036 id<NSURLProtocolClient> client([self client]);
6037 NSURLRequest *request([self request]);
6039 NSURL *url([request URL]);
6040 NSString *href([url absoluteString]);
6042 NSString *path([href substringFromIndex:8]);
6043 NSRange slash([path rangeOfString:@"/"]);
6046 if (slash.location == NSNotFound) {
6050 command = [path substringToIndex:slash.location];
6051 path = [path substringFromIndex:(slash.location + 1)];
6054 Database *database([Database sharedInstance]);
6056 if ([command isEqualToString:@"package-icon"]) {
6059 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6060 Package *package([database packageWithName:path]);
6063 UIImage *icon([package icon]);
6064 [self _returnPNGWithImage:icon forRequest:request];
6065 } else if ([command isEqualToString:@"source-icon"]) {
6068 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6069 NSString *source(Simplify(path));
6070 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6072 icon = [UIImage applicationImageNamed:@"unknown.png"];
6073 [self _returnPNGWithImage:icon forRequest:request];
6074 } else if ([command isEqualToString:@"uikit-image"]) {
6077 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6078 UIImage *icon(_UIImageWithName(path));
6079 [self _returnPNGWithImage:icon forRequest:request];
6080 } else if ([command isEqualToString:@"section-icon"]) {
6083 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6084 NSString *section(Simplify(path));
6085 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6087 icon = [UIImage applicationImageNamed:@"unknown.png"];
6088 [self _returnPNGWithImage:icon forRequest:request];
6090 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6094 - (void) stopLoading {
6100 /* Sections View {{{ */
6101 @interface SectionsView : RVPage {
6102 _transient Database *database_;
6103 NSMutableArray *sections_;
6104 NSMutableArray *filtered_;
6105 UITransitionView *transition_;
6111 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6112 - (void) reloadData;
6117 @implementation SectionsView
6120 [list_ setDataSource:nil];
6121 [list_ setDelegate:nil];
6123 [sections_ release];
6124 [filtered_ release];
6125 [transition_ release];
6127 [accessory_ release];
6131 - (int) numberOfRowsInTable:(UITable *)table {
6132 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6135 - (float) table:(UITable *)table heightForRow:(int)row {
6139 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6141 reusing = [[[SectionCell alloc] init] autorelease];
6142 [(SectionCell *)reusing setSection:(editing_ ?
6143 [sections_ objectAtIndex:row] :
6144 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6145 ) editing:editing_];
6149 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6153 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6157 - (void) tableRowSelected:(NSNotification *)notification {
6158 int row = [[notification object] selectedRow];
6169 title = CYLocalize("ALL_PACKAGES");
6171 section = [filtered_ objectAtIndex:(row - 1)];
6172 name = [section name];
6175 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6178 title = CYLocalize("NO_SECTION");
6182 PackageTable *table = [[[FilteredPackageTable alloc]
6186 filter:@selector(isVisiblyUninstalledInSection:)
6190 [table setDelegate:delegate_];
6192 [book_ pushPage:table];
6195 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6196 if ((self = [super initWithBook:book]) != nil) {
6197 database_ = database;
6199 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6200 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6202 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6203 [self addSubview:transition_];
6205 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6206 [transition_ transition:0 toView:list_];
6208 UITableColumn *column = [[[UITableColumn alloc]
6209 initWithTitle:CYLocalize("NAME")
6211 width:[self frame].size.width
6214 [list_ setDataSource:self];
6215 [list_ setSeparatorStyle:1];
6216 [list_ addTableColumn:column];
6217 [list_ setDelegate:self];
6218 [list_ setReusesTableCells:YES];
6222 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6223 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6227 - (void) reloadData {
6228 NSArray *packages = [database_ packages];
6230 [sections_ removeAllObjects];
6231 [filtered_ removeAllObjects];
6234 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6235 SectionMap sections;
6236 sections.resize(64);
6238 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6242 for (Package *package in packages) {
6243 NSString *name([package section]);
6244 NSString *key(name == nil ? @"" : name);
6249 _profile(SectionsView$reloadData$Section)
6250 section = §ions[key];
6251 if (*section == nil) {
6252 _profile(SectionsView$reloadData$Section$Allocate)
6253 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6258 [*section addToCount];
6260 _profile(SectionsView$reloadData$Filter)
6261 if (![package valid] || [package installed] != nil || ![package visible])
6265 [*section addToRow];
6269 _profile(SectionsView$reloadData$Section)
6270 section = [sections objectForKey:key];
6271 if (section == nil) {
6272 _profile(SectionsView$reloadData$Section$Allocate)
6273 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6274 [sections setObject:section forKey:key];
6279 [section addToCount];
6281 _profile(SectionsView$reloadData$Filter)
6282 if (![package valid] || [package installed] != nil || ![package visible])
6292 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6293 [sections_ addObject:i->second];
6295 [sections_ addObjectsFromArray:[sections allValues]];
6298 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6300 for (Section *section in sections_) {
6301 size_t count([section row]);
6305 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6306 [section setCount:count];
6307 [filtered_ addObject:section];
6314 - (void) resetView {
6316 [self _rightButtonClicked];
6319 - (void) resetViewAnimated:(BOOL)animated {
6320 [list_ resetViewAnimated:animated];
6323 - (void) _rightButtonClicked {
6324 if ((editing_ = !editing_))
6327 [delegate_ updateData];
6328 [book_ reloadTitleForPage:self];
6329 [book_ reloadButtonsForPage:self];
6332 - (NSString *) title {
6333 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6336 - (NSString *) backButtonTitle {
6337 return CYLocalize("SECTIONS");
6340 - (id) rightButtonTitle {
6341 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6344 - (UINavigationButtonStyle) rightButtonStyle {
6345 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6348 - (UIView *) accessoryView {
6354 /* Changes View {{{ */
6355 @interface ChangesView : RVPage {
6356 _transient Database *database_;
6357 NSMutableArray *packages_;
6358 NSMutableArray *sections_;
6359 UISectionList *list_;
6363 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6364 - (void) reloadData;
6368 @implementation ChangesView
6371 [[list_ table] setDelegate:nil];
6372 [list_ setDataSource:nil];
6374 [packages_ release];
6375 [sections_ release];
6380 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6381 return [sections_ count];
6384 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6385 return [[sections_ objectAtIndex:section] name];
6388 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6389 return [[sections_ objectAtIndex:section] row];
6392 - (int) numberOfRowsInTable:(UITable *)table {
6393 return [packages_ count];
6396 - (float) table:(UITable *)table heightForRow:(int)row {
6397 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6400 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6402 reusing = [[[PackageCell alloc] init] autorelease];
6403 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6407 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6411 - (void) tableRowSelected:(NSNotification *)notification {
6412 int row = [[notification object] selectedRow];
6415 Package *package = [packages_ objectAtIndex:row];
6416 PackageView *view([delegate_ packageView]);
6417 [view setDelegate:delegate_];
6418 [view setPackage:package];
6419 [book_ pushPage:view];
6422 - (void) _leftButtonClicked {
6423 [(CYBook *)book_ update];
6424 [self reloadButtons];
6427 - (void) _rightButtonClicked {
6428 [delegate_ distUpgrade];
6431 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6432 if ((self = [super initWithBook:book]) != nil) {
6433 database_ = database;
6435 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6436 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6438 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6439 [self addSubview:list_];
6441 [list_ setShouldHideHeaderInShortLists:NO];
6442 [list_ setDataSource:self];
6443 //[list_ setSectionListStyle:1];
6445 UITableColumn *column = [[[UITableColumn alloc]
6446 initWithTitle:CYLocalize("NAME")
6448 width:[self frame].size.width
6451 UITable *table = [list_ table];
6452 [table setSeparatorStyle:1];
6453 [table addTableColumn:column];
6454 [table setDelegate:self];
6455 [table setReusesTableCells:YES];
6459 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6460 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6464 - (void) reloadData {
6465 NSArray *packages = [database_ packages];
6467 [packages_ removeAllObjects];
6468 [sections_ removeAllObjects];
6471 for (Package *package in packages)
6473 [package installed] == nil && [package valid] && [package visible] ||
6474 [package upgradableAndEssential:YES]
6476 [packages_ addObject:package];
6479 [packages_ radixSortUsingFunction:reinterpret_cast<uint32_t (*)(id, void *)>(&PackageChangesRadix) withArgument:NULL];
6482 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6483 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6484 Section *section = nil;
6488 bool unseens = false;
6490 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6492 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6493 Package *package = [packages_ objectAtIndex:offset];
6495 BOOL uae = [package upgradableAndEssential:YES];
6501 _profile(ChangesView$reloadData$Remember)
6502 seen = [package seen];
6505 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6510 name = CYLocalize("UNKNOWN");
6512 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6516 _profile(ChangesView$reloadData$Allocate)
6517 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6518 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6519 [sections_ addObject:section];
6523 [section addToCount];
6524 } else if ([package ignored])
6525 [ignored addToCount];
6528 [upgradable addToCount];
6533 CFRelease(formatter);
6536 Section *last = [sections_ lastObject];
6537 size_t count = [last count];
6538 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6539 [sections_ removeLastObject];
6542 if ([ignored count] != 0)
6543 [sections_ insertObject:ignored atIndex:0];
6545 [sections_ insertObject:upgradable atIndex:0];
6548 [self reloadButtons];
6551 - (void) resetViewAnimated:(BOOL)animated {
6552 [list_ resetViewAnimated:animated];
6555 - (NSString *) leftButtonTitle {
6556 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6559 - (id) rightButtonTitle {
6560 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6563 - (NSString *) title {
6564 return CYLocalize("CHANGES");
6569 /* Search View {{{ */
6570 @protocol SearchViewDelegate
6571 - (void) showKeyboard:(BOOL)show;
6574 @interface SearchView : RVPage {
6576 UISearchField *field_;
6577 UITransitionView *transition_;
6578 FilteredPackageTable *table_;
6579 UIPreferencesTable *advanced_;
6585 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6586 - (void) reloadData;
6590 @implementation SearchView
6593 [field_ setDelegate:nil];
6595 [accessory_ release];
6597 [transition_ release];
6599 [advanced_ release];
6604 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6608 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6610 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6612 default: _assert(false);
6616 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6620 default: _assert(false);
6624 - (void) _showKeyboard:(BOOL)show {
6625 CGSize keysize = [UIKeyboard defaultSize];
6626 CGRect keydown = [book_ pageBounds];
6627 CGRect keyup = keydown;
6628 keyup.size.height -= keysize.height - ButtonBarHeight_;
6630 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6632 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6633 [animation setSignificantRectFields:8];
6636 [animation setStartFrame:keydown];
6637 [animation setEndFrame:keyup];
6639 [animation setStartFrame:keyup];
6640 [animation setEndFrame:keydown];
6643 UIAnimator *animator = [UIAnimator sharedAnimator];
6646 addAnimations:[NSArray arrayWithObjects:animation, nil]
6647 withDuration:(KeyboardTime_ - delay)
6652 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6654 [delegate_ showKeyboard:show];
6657 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6658 [self _showKeyboard:YES];
6661 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6662 [self _showKeyboard:NO];
6665 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6667 NSString *text([field_ text]);
6668 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6674 - (void) textFieldClearButtonPressed:(UITextField *)field {
6678 - (void) keyboardInputShouldDelete:(id)input {
6682 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6683 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6687 [field_ resignFirstResponder];
6692 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6693 if ((self = [super initWithBook:book]) != nil) {
6694 CGRect pageBounds = [book_ pageBounds];
6696 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6697 [self addSubview:transition_];
6699 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6701 [advanced_ setReusesTableCells:YES];
6702 [advanced_ setDataSource:self];
6703 [advanced_ reloadData];
6705 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6706 CGColor dimmed(space_, 0, 0, 0, 0.5);
6707 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6709 table_ = [[FilteredPackageTable alloc]
6713 filter:@selector(isUnfilteredAndSearchedForBy:)
6717 [table_ setShouldHideHeaderInShortLists:NO];
6718 [transition_ transition:0 toView:table_];
6727 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6734 [self bounds].size.width - area.origin.x - 18;
6736 area.size.height = [UISearchField defaultHeight];
6738 field_ = [[UISearchField alloc] initWithFrame:area];
6740 UIFont *font = [UIFont systemFontOfSize:16];
6741 [field_ setFont:font];
6743 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6744 [field_ setDelegate:self];
6746 [field_ setPaddingTop:5];
6748 UITextInputTraits *traits([field_ textInputTraits]);
6749 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6750 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6751 [traits setReturnKeyType:UIReturnKeySearch];
6753 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6755 accessory_ = [[UIView alloc] initWithFrame:accrect];
6756 [accessory_ addSubview:field_];
6758 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6759 [configure setShowPressFeedback:YES];
6760 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6761 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6762 [accessory_ addSubview:configure];*/
6764 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6765 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6771 LKAnimation *animation = [LKTransition animation];
6772 [animation setType:@"oglFlip"];
6773 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6774 [animation setFillMode:@"extended"];
6775 [animation setTransitionFlags:3];
6776 [animation setDuration:10];
6777 [animation setSpeed:0.35];
6778 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6779 [[transition_ _layer] addAnimation:animation forKey:0];
6780 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6781 flipped_ = !flipped_;
6785 - (void) configurePushed {
6786 [field_ resignFirstResponder];
6790 - (void) resetViewAnimated:(BOOL)animated {
6793 [table_ resetViewAnimated:animated];
6796 - (void) _reloadData {
6799 - (void) reloadData {
6802 [table_ setObject:[field_ text]];
6803 _profile(SearchView$reloadData)
6804 [table_ reloadData];
6807 [table_ resetCursor];
6810 - (UIView *) accessoryView {
6814 - (NSString *) title {
6818 - (NSString *) backButtonTitle {
6819 return CYLocalize("SEARCH");
6822 - (void) setDelegate:(id)delegate {
6823 [table_ setDelegate:delegate];
6824 [super setDelegate:delegate];
6830 @interface SettingsView : RVPage {
6831 _transient Database *database_;
6834 UIPreferencesTable *table_;
6835 _UISwitchSlider *subscribedSwitch_;
6836 _UISwitchSlider *ignoredSwitch_;
6837 UIPreferencesControlTableCell *subscribedCell_;
6838 UIPreferencesControlTableCell *ignoredCell_;
6841 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6845 @implementation SettingsView
6848 [table_ setDataSource:nil];
6851 if (package_ != nil)
6854 [subscribedSwitch_ release];
6855 [ignoredSwitch_ release];
6856 [subscribedCell_ release];
6857 [ignoredCell_ release];
6861 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6862 if (package_ == nil)
6868 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6869 if (package_ == nil)
6876 default: _assert(false);
6882 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
6883 if (package_ == nil)
6890 default: _assert(false);
6896 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6897 if (package_ == nil)
6904 default: _assert(false);
6910 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
6911 if (package_ == nil)
6914 _UISwitchSlider *slider([cell control]);
6915 BOOL value([slider value] != 0);
6916 NSMutableDictionary *metadata([package_ metadata]);
6919 if (NSNumber *number = [metadata objectForKey:key])
6920 before = [number boolValue];
6924 if (value != before) {
6925 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
6927 [delegate_ updateData];
6931 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
6932 [self onSomething:cell withKey:@"IsSubscribed"];
6935 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
6936 [self onSomething:cell withKey:@"IsIgnored"];
6939 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
6940 if (package_ == nil)
6944 case 0: switch (row) {
6946 return subscribedCell_;
6948 return ignoredCell_;
6949 default: _assert(false);
6952 case 1: switch (row) {
6954 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
6955 [cell setShowSelection:NO];
6956 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
6960 default: _assert(false);
6963 default: _assert(false);
6969 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
6970 if ((self = [super initWithBook:book])) {
6971 database_ = database;
6972 name_ = [package retain];
6974 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
6975 [self addSubview:table_];
6977 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
6978 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
6980 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
6981 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
6983 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
6984 [subscribedCell_ setShowSelection:NO];
6985 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
6986 [subscribedCell_ setControl:subscribedSwitch_];
6988 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
6989 [ignoredCell_ setShowSelection:NO];
6990 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
6991 [ignoredCell_ setControl:ignoredSwitch_];
6993 [table_ setDataSource:self];
6998 - (void) resetViewAnimated:(BOOL)animated {
6999 [table_ resetViewAnimated:animated];
7002 - (void) reloadData {
7003 if (package_ != nil)
7004 [package_ autorelease];
7005 package_ = [database_ packageWithName:name_];
7006 if (package_ != nil) {
7008 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7009 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7012 [table_ reloadData];
7015 - (NSString *) title {
7016 return CYLocalize("SETTINGS");
7021 /* Signature View {{{ */
7022 @interface SignatureView : BrowserView {
7023 _transient Database *database_;
7027 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7031 @implementation SignatureView
7038 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7040 [super webView:sender didClearWindowObject:window forFrame:frame];
7043 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7044 if ((self = [super initWithBook:book]) != nil) {
7045 database_ = database;
7046 package_ = [package retain];
7051 - (void) resetViewAnimated:(BOOL)animated {
7054 - (void) reloadData {
7055 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7061 @interface Cydia : UIApplication <
7062 ConfirmationViewDelegate,
7063 ProgressViewDelegate,
7072 UIToolbar *buttonbar_;
7076 NSMutableArray *essential_;
7077 NSMutableArray *broken_;
7079 Database *database_;
7080 ProgressView *progress_;
7084 UIKeyboard *keyboard_;
7085 UIProgressHUD *hud_;
7087 SectionsView *sections_;
7088 ChangesView *changes_;
7089 ManageView *manage_;
7090 SearchView *search_;
7092 PackageView *package_;
7097 @implementation Cydia
7100 if ([broken_ count] != 0) {
7101 int count = [broken_ count];
7103 UIActionSheet *sheet = [[[UIActionSheet alloc]
7104 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
7105 buttons:[NSArray arrayWithObjects:
7106 CYLocalize("FORCIBLY_CLEAR"),
7107 CYLocalize("TEMPORARY_IGNORE"),
7109 defaultButtonIndex:0
7114 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
7115 [sheet popupAlertAnimated:YES];
7116 } else if (!Ignored_ && [essential_ count] != 0) {
7117 int count = [essential_ count];
7119 UIActionSheet *sheet = [[[UIActionSheet alloc]
7120 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
7121 buttons:[NSArray arrayWithObjects:
7122 CYLocalize("UPGRADE_ESSENTIAL"),
7123 CYLocalize("COMPLETE_UPGRADE"),
7124 CYLocalize("TEMPORARY_IGNORE"),
7126 defaultButtonIndex:0
7131 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
7132 [sheet popupAlertAnimated:YES];
7136 - (void) _reloadData {
7139 static bool loaded(false);
7140 UIProgressHUD *hud([self addProgressHUD]);
7141 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7144 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7147 [self removeProgressHUD:hud];
7151 [essential_ removeAllObjects];
7152 [broken_ removeAllObjects];
7154 NSArray *packages = [database_ packages];
7155 for (Package *package in packages) {
7157 [broken_ addObject:package];
7158 if ([package upgradableAndEssential:NO]) {
7159 if ([package essential])
7160 [essential_ addObject:package];
7166 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7167 [buttonbar_ setBadgeValue:badge forButton:3];
7168 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7169 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7170 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7171 [self setApplicationBadge:badge];
7173 [self setApplicationBadgeString:badge];
7175 [buttonbar_ setBadgeValue:nil forButton:3];
7176 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7177 [buttonbar_ setBadgeAnimated:NO forButton:3];
7178 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7179 [self removeApplicationBadge];
7180 else // XXX: maybe use setApplicationBadgeString also?
7181 [self setApplicationIconBadgeNumber:0];
7185 [buttonbar_ setBadgeValue:nil forButton:4];
7189 // XXX: what is this line of code for?
7190 if ([packages count] == 0);
7191 else if (Loaded_ || ManualRefresh) loaded:
7196 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7197 NSTimeInterval interval([update timeIntervalSinceNow]);
7198 if (interval <= 0 && interval > -600)
7206 - (void) _saveConfig {
7209 NSString *error(nil);
7210 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7212 NSError *error(nil);
7213 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7214 NSLog(@"failure to save metadata data: %@", error);
7217 NSLog(@"failure to serialize metadata: %@", error);
7225 - (void) updateData {
7228 /* XXX: this is just stupid */
7229 if (tag_ != 2 && sections_ != nil)
7230 [sections_ reloadData];
7231 if (tag_ != 3 && changes_ != nil)
7232 [changes_ reloadData];
7233 if (tag_ != 5 && search_ != nil)
7234 [search_ reloadData];
7244 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7245 _assert(file != NULL);
7247 NSArray *keys = [Sources_ allKeys];
7249 for (NSString *key in keys) {
7250 NSDictionary *source = [Sources_ objectForKey:key];
7252 fprintf(file, "%s %s %s\n",
7253 [[source objectForKey:@"Type"] UTF8String],
7254 [[source objectForKey:@"URI"] UTF8String],
7255 [[source objectForKey:@"Distribution"] UTF8String]
7264 detachNewThreadSelector:@selector(update_)
7267 title:CYLocalize("UPDATING_SOURCES")
7271 - (void) reloadData {
7272 @synchronized (self) {
7273 if (confirm_ == nil)
7279 pkgProblemResolver *resolver = [database_ resolver];
7281 resolver->InstallProtect();
7282 if (!resolver->Resolve(true))
7286 - (void) popUpBook:(RVBook *)book {
7287 [underlay_ popSubview:book];
7290 - (CGRect) popUpBounds {
7291 return [underlay_ bounds];
7295 [database_ prepare];
7297 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7298 [confirm_ setDelegate:self];
7300 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7301 [page setDelegate:self];
7303 [confirm_ setPage:page];
7304 [self popUpBook:confirm_];
7308 @synchronized (self) {
7313 - (void) clearPackage:(Package *)package {
7314 @synchronized (self) {
7321 - (void) installPackage:(Package *)package {
7322 @synchronized (self) {
7329 - (void) removePackage:(Package *)package {
7330 @synchronized (self) {
7337 - (void) distUpgrade {
7338 @synchronized (self) {
7339 [database_ upgrade];
7345 [self slideUp:[[[UIActionSheet alloc]
7347 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7348 defaultButtonIndex:1
7355 @synchronized (self) {
7358 if (confirm_ != nil) {
7366 [overlay_ removeFromSuperview];
7370 detachNewThreadSelector:@selector(perform)
7373 title:CYLocalize("RUNNING")
7377 - (void) bootstrap_ {
7379 [database_ upgrade];
7380 [database_ prepare];
7381 [database_ perform];
7384 /* XXX: replace and localize */
7385 - (void) bootstrap {
7387 detachNewThreadSelector:@selector(bootstrap_)
7390 title:@"Bootstrap Install"
7394 - (void) progressViewIsComplete:(ProgressView *)progress {
7395 if (confirm_ != nil) {
7396 [underlay_ addSubview:overlay_];
7397 [confirm_ popFromSuperviewAnimated:NO];
7403 - (void) setPage:(RVPage *)page {
7404 [page resetViewAnimated:NO];
7405 [page setDelegate:self];
7406 [book_ setPage:page];
7409 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7410 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7411 [browser loadURL:url];
7415 - (void) _setHomePage {
7416 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7419 - (SectionsView *) sectionsView {
7420 if (sections_ == nil)
7421 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7425 - (void) buttonBarItemTapped:(id)sender {
7426 unsigned tag = [sender tag];
7428 [book_ resetViewAnimated:YES];
7430 } else if (tag_ == 2 && tag != 2)
7431 [[self sectionsView] resetView];
7434 case 1: [self _setHomePage]; break;
7436 case 2: [self setPage:[self sectionsView]]; break;
7437 case 3: [self setPage:changes_]; break;
7438 case 4: [self setPage:manage_]; break;
7439 case 5: [self setPage:search_]; break;
7441 default: _assert(false);
7447 - (void) applicationWillSuspend {
7449 [super applicationWillSuspend];
7452 - (void) askForSettings {
7453 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7455 UIActionSheet *role = [[[UIActionSheet alloc]
7456 initWithTitle:CYLocalize("WHO_ARE_YOU")
7457 buttons:[NSArray arrayWithObjects:
7458 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7459 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7460 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7462 defaultButtonIndex:-1
7467 [role setBodyText:CYLocalize("ROLE_EX")];
7468 [role popupAlertAnimated:YES];
7471 - (void) setPackageView:(PackageView *)view {
7472 if (package_ == nil)
7473 package_ = [view retain];
7476 - (PackageView *) packageView {
7479 if (package_ == nil)
7480 view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7483 view = [package_ autorelease];
7492 [self setStatusBarShowsProgress:NO];
7493 [self removeProgressHUD:hud_];
7498 pid_t pid = ExecFork();
7500 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7501 perror("launchctl stop");
7508 [self askForSettings];
7513 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7515 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7516 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7517 0, 0, screenrect.size.width, screenrect.size.height - 48
7518 ) database:database_];
7520 [book_ setDelegate:self];
7522 [overlay_ addSubview:book_];
7524 NSArray *buttonitems = [NSArray arrayWithObjects:
7525 [NSDictionary dictionaryWithObjectsAndKeys:
7526 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7527 @"home-up.png", kUIButtonBarButtonInfo,
7528 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7529 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7530 self, kUIButtonBarButtonTarget,
7531 @"Cydia", kUIButtonBarButtonTitle,
7532 @"0", kUIButtonBarButtonType,
7535 [NSDictionary dictionaryWithObjectsAndKeys:
7536 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7537 @"install-up.png", kUIButtonBarButtonInfo,
7538 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7539 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7540 self, kUIButtonBarButtonTarget,
7541 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7542 @"0", kUIButtonBarButtonType,
7545 [NSDictionary dictionaryWithObjectsAndKeys:
7546 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7547 @"changes-up.png", kUIButtonBarButtonInfo,
7548 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7549 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7550 self, kUIButtonBarButtonTarget,
7551 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7552 @"0", kUIButtonBarButtonType,
7555 [NSDictionary dictionaryWithObjectsAndKeys:
7556 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7557 @"manage-up.png", kUIButtonBarButtonInfo,
7558 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7559 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7560 self, kUIButtonBarButtonTarget,
7561 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7562 @"0", kUIButtonBarButtonType,
7565 [NSDictionary dictionaryWithObjectsAndKeys:
7566 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7567 @"search-up.png", kUIButtonBarButtonInfo,
7568 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7569 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7570 self, kUIButtonBarButtonTarget,
7571 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7572 @"0", kUIButtonBarButtonType,
7576 buttonbar_ = [[UIToolbar alloc]
7578 withFrame:CGRectMake(
7579 0, screenrect.size.height - ButtonBarHeight_,
7580 screenrect.size.width, ButtonBarHeight_
7582 withItemList:buttonitems
7585 [buttonbar_ setDelegate:self];
7586 [buttonbar_ setBarStyle:1];
7587 [buttonbar_ setButtonBarTrackingMode:2];
7589 int buttons[5] = {1, 2, 3, 4, 5};
7590 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7591 [buttonbar_ showButtonGroup:0 withDuration:0];
7593 for (int i = 0; i != 5; ++i)
7594 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7595 i * 64 + 2, 1, 60, ButtonBarHeight_
7598 [buttonbar_ showSelectionForButton:1];
7599 [overlay_ addSubview:buttonbar_];
7601 [UIKeyboard initImplementationNow];
7602 CGSize keysize = [UIKeyboard defaultSize];
7603 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7604 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7605 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7606 [overlay_ addSubview:keyboard_];
7609 [underlay_ addSubview:overlay_];
7613 [self sectionsView];
7614 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7615 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7617 manage_ = (ManageView *) [[self
7618 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7619 withClass:[ManageView class]
7622 [self setPackageView:[self packageView]];
7629 [self _setHomePage];
7632 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7633 NSString *context([sheet context]);
7635 if ([context isEqualToString:@"missing"])
7637 else if ([context isEqualToString:@"cancel"]) {
7655 @synchronized (self) {
7660 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7664 if (confirm_ != nil) {
7669 } else if ([context isEqualToString:@"fixhalf"]) {
7672 @synchronized (self) {
7673 for (Package *broken in broken_) {
7676 NSString *id = [broken id];
7677 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7678 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7679 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7680 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7689 [broken_ removeAllObjects];
7698 } else if ([context isEqualToString:@"role"]) {
7700 case 1: Role_ = @"User"; break;
7701 case 2: Role_ = @"Hacker"; break;
7702 case 3: Role_ = @"Developer"; break;
7709 bool reset = Settings_ != nil;
7711 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7715 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7725 } else if ([context isEqualToString:@"upgrade"]) {
7728 @synchronized (self) {
7729 for (Package *essential in essential_)
7730 [essential install];
7753 - (void) reorganize { _pooled
7754 system("/usr/libexec/cydia/free.sh");
7755 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7758 - (void) applicationSuspend:(__GSEvent *)event {
7759 if (hud_ == nil && ![progress_ isRunning])
7760 [super applicationSuspend:event];
7763 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7765 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7768 - (void) _setSuspended:(BOOL)value {
7770 [super _setSuspended:value];
7773 - (UIProgressHUD *) addProgressHUD {
7774 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7775 [window_ setUserInteractionEnabled:NO];
7777 [progress_ addSubview:hud];
7781 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7783 [hud removeFromSuperview];
7784 [window_ setUserInteractionEnabled:YES];
7787 - (void) openMailToURL:(NSURL *)url {
7788 // XXX: this makes me sad
7790 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7792 [UIApp openURL:url];// asPanel:YES];
7796 - (void) clearFirstResponder {
7797 if (id responder = [window_ firstResponder])
7798 [responder resignFirstResponder];
7801 - (RVPage *) pageForPackage:(NSString *)name {
7802 if (Package *package = [database_ packageWithName:name]) {
7803 PackageView *view([self packageView]);
7804 [view setPackage:package];
7807 UIActionSheet *sheet = [[[UIActionSheet alloc]
7808 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7809 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
7810 defaultButtonIndex:0
7815 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
7817 [sheet popupAlertAnimated:YES];
7822 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7826 NSString *scheme([[url scheme] lowercaseString]);
7827 if (![scheme isEqualToString:@"cydia"])
7829 NSString *path([url absoluteString]);
7830 if ([path length] < 8)
7832 path = [path substringFromIndex:8];
7833 if (![path hasPrefix:@"/"])
7834 path = [@"/" stringByAppendingString:path];
7836 if ([path isEqualToString:@"/add-source"])
7837 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
7838 else if ([path isEqualToString:@"/storage"])
7839 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
7840 else if ([path isEqualToString:@"/sources"])
7841 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
7842 else if ([path isEqualToString:@"/packages"])
7843 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
7844 else if ([path hasPrefix:@"/url/"])
7845 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
7846 else if ([path hasPrefix:@"/launch/"])
7847 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
7848 else if ([path hasPrefix:@"/package-settings/"])
7849 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
7850 else if ([path hasPrefix:@"/package-signature/"])
7851 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
7852 else if ([path hasPrefix:@"/package/"])
7853 return [self pageForPackage:[path substringFromIndex:9]];
7854 else if ([path hasPrefix:@"/files/"]) {
7855 NSString *name = [path substringFromIndex:7];
7857 if (Package *package = [database_ packageWithName:name]) {
7858 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
7859 [files setPackage:package];
7867 - (void) applicationOpenURL:(NSURL *)url {
7868 [super applicationOpenURL:url];
7870 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
7871 [self setPage:page];
7872 [buttonbar_ showSelectionForButton:tag];
7877 - (void) applicationDidFinishLaunching:(id)unused {
7879 Font12_ = [[UIFont systemFontOfSize:12] retain];
7880 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
7881 Font14_ = [[UIFont systemFontOfSize:14] retain];
7882 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
7883 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
7887 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
7888 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
7890 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
7892 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7893 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
7895 [window_ orderFront:self];
7896 [window_ makeKey:self];
7897 [window_ setHidden:NO];
7899 database_ = [Database sharedInstance];
7900 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
7901 [database_ setDelegate:progress_];
7902 [window_ setContentView:progress_];
7904 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
7905 [progress_ setContentView:underlay_];
7907 [progress_ resetView];
7910 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
7911 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
7912 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
7913 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
7914 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
7915 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
7916 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
7918 [self setIdleTimerDisabled:YES];
7920 hud_ = [[self addProgressHUD] retain];
7921 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
7923 [self setStatusBarShowsProgress:YES];
7926 detachNewThreadSelector:@selector(reorganize)
7934 - (void) showKeyboard:(BOOL)show {
7935 CGSize keysize = [UIKeyboard defaultSize];
7936 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
7937 CGRect keyup = keydown;
7938 keyup.origin.y -= keysize.height;
7940 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
7941 [animation setSignificantRectFields:2];
7944 [animation setStartFrame:keydown];
7945 [animation setEndFrame:keyup];
7946 [keyboard_ activate];
7948 [animation setStartFrame:keyup];
7949 [animation setEndFrame:keydown];
7950 [keyboard_ deactivate];
7953 [[UIAnimator sharedAnimator]
7954 addAnimations:[NSArray arrayWithObjects:animation, nil]
7955 withDuration:KeyboardTime_
7960 - (void) slideUp:(UIActionSheet *)alert {
7962 [alert presentSheetFromButtonBar:buttonbar_];
7964 [alert presentSheetInView:overlay_];
7969 void AddPreferences(NSString *plist) { _pooled
7970 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
7971 _assert(settings != NULL);
7972 NSMutableArray *items = [settings objectForKey:@"items"];
7976 for (NSMutableDictionary *item in items) {
7977 NSString *label = [item objectForKey:@"label"];
7978 if (label != nil && [label isEqualToString:@"Cydia"]) {
7985 for (size_t i(0); i != [items count]; ++i) {
7986 NSDictionary *item([items objectAtIndex:i]);
7987 NSString *label = [item objectForKey:@"label"];
7988 if (label != nil && [label isEqualToString:@"General"]) {
7989 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
7990 @"CydiaSettings", @"bundle",
7991 @"PSLinkCell", @"cell",
7992 [NSNumber numberWithBool:YES], @"hasIcon",
7993 [NSNumber numberWithBool:YES], @"isController",
7995 nil] atIndex:(i + 1)];
8001 _assert([settings writeToFile:plist atomically:YES] == YES);
8006 id Alloc_(id self, SEL selector) {
8007 id object = alloc_(self, selector);
8008 lprintf("[%s]A-%p\n", self->isa->name, object);
8013 id Dealloc_(id self, SEL selector) {
8014 id object = dealloc_(self, selector);
8015 lprintf("[%s]D-%p\n", self->isa->name, object);
8019 Class $WebDefaultUIKitDelegate;
8021 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8023 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8024 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8025 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8026 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8029 int main(int argc, char *argv[]) { _pooled
8032 PackageName = reinterpret_cast<CFStringRef (*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(name))));
8034 /* Library Hacks {{{ */
8035 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8037 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8038 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8039 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8040 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8041 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8044 /* Set Locale {{{ */
8045 Locale_ = CFLocaleCopyCurrent();
8046 Languages_ = [NSLocale preferredLanguages];
8047 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8048 //NSLog(@"%@", [Languages_ description]);
8050 if (Languages_ == nil || [Languages_ count] == 0)
8053 lang = [[Languages_ objectAtIndex:0] UTF8String];
8054 setenv("LANG", lang, true);
8055 //std::setlocale(LC_ALL, lang);
8056 NSLog(@"Setting Language: %s", lang);
8059 // XXX: apr_app_initialize?
8062 /* Parse Arguments {{{ */
8063 bool substrate(false);
8069 for (int argi(1); argi != argc; ++argi)
8070 if (strcmp(argv[argi], "--") == 0) {
8072 argv[argi] = argv[0];
8078 for (int argi(1); argi != arge; ++argi)
8079 if (strcmp(args[argi], "--bootstrap") == 0)
8081 else if (strcmp(args[argi], "--substrate") == 0)
8084 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8089 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8090 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8091 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8092 Sounds_Keyboard_ = [keyboard boolValue];
8095 App_ = [[NSBundle mainBundle] bundlePath];
8096 Home_ = NSHomeDirectory();
8101 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8102 alloc_ = alloc->method_imp;
8103 alloc->method_imp = (IMP) &Alloc_;*/
8105 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8106 dealloc_ = dealloc->method_imp;
8107 dealloc->method_imp = (IMP) &Dealloc_;*/
8112 size = sizeof(maxproc);
8113 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8114 perror("sysctlbyname(\"kern.maxproc\", ?)");
8115 else if (maxproc < 64) {
8117 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8118 perror("sysctlbyname(\"kern.maxproc\", #)");
8121 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8122 char *machine = new char[size];
8123 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8124 perror("sysctlbyname(\"hw.machine\", ?)");
8128 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8130 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8131 Build_ = [system objectForKey:@"ProductBuildVersion"];
8132 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8133 Product_ = [info objectForKey:@"SafariProductVersion"];
8134 Safari_ = [info objectForKey:@"CFBundleVersion"];
8137 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8138 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8140 /* Load Database {{{ */
8142 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8144 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8147 if (Metadata_ == NULL)
8148 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8150 Settings_ = [Metadata_ objectForKey:@"Settings"];
8152 Packages_ = [Metadata_ objectForKey:@"Packages"];
8153 Sections_ = [Metadata_ objectForKey:@"Sections"];
8154 Sources_ = [Metadata_ objectForKey:@"Sources"];
8157 if (Settings_ != nil)
8158 Role_ = [Settings_ objectForKey:@"Role"];
8160 if (Packages_ == nil) {
8161 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8162 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8165 if (Sections_ == nil) {
8166 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8167 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8170 if (Sources_ == nil) {
8171 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8172 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8177 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8180 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8181 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8182 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8183 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8185 if (access("/User", F_OK) != 0) {
8187 system("/usr/libexec/cydia/firmware.sh");
8191 _assert([[NSFileManager defaultManager]
8192 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8193 withIntermediateDirectories:YES
8198 if (access("/tmp/cydia.chk", F_OK) == 0) {
8199 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8200 _assert(errno == ENOENT);
8201 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8202 _assert(errno == ENOENT);
8205 _assert(pkgInitConfig(*_config));
8206 _assert(pkgInitSystem(*_config, _system));
8209 _config->Set("APT::Acquire::Translation", lang);
8210 _config->Set("Acquire::http::Timeout", 15);
8211 _config->Set("Acquire::http::MaxParallel", 4);
8213 /* Color Choices {{{ */
8214 space_ = CGColorSpaceCreateDeviceRGB();
8216 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8217 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8218 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8219 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8220 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8221 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8222 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8223 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8224 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8225 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8226 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8227 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8228 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8229 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8230 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8233 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8234 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8237 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8239 /* UIKit Configuration {{{ */
8240 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8241 if ($GSFontSetUseLegacyFontMetrics != NULL)
8242 $GSFontSetUseLegacyFontMetrics(YES);
8244 UIKeyboardDisableAutomaticAppearance();
8248 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8250 CGColorSpaceRelease(space_);