1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2009 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #import "UICaboodle/UCPlatform.h"
45 #import "UICaboodle/UCLocalize.h"
47 #include <objc/message.h>
48 #include <objc/objc.h>
49 #include <objc/runtime.h>
51 #include <CoreGraphics/CoreGraphics.h>
52 #include <GraphicsServices/GraphicsServices.h>
53 #include <Foundation/Foundation.h>
56 #define DEPLOYMENT_TARGET_MACOSX 1
57 #define CF_BUILDING_CF 1
58 #include <CoreFoundation/CFInternal.h>
61 #include <CoreFoundation/CFPriv.h>
62 #include <CoreFoundation/CFUniChar.h>
64 #import <UIKit/UIKit.h>
66 #include <WebCore/WebCoreThread.h>
67 #import <WebKit/WebDefaultUIKitDelegate.h>
74 #include <ext/stdio_filebuf.h>
76 #include <apt-pkg/acquire.h>
77 #include <apt-pkg/acquire-item.h>
78 #include <apt-pkg/algorithms.h>
79 #include <apt-pkg/cachefile.h>
80 #include <apt-pkg/clean.h>
81 #include <apt-pkg/configuration.h>
82 #include <apt-pkg/debindexfile.h>
83 #include <apt-pkg/debmetaindex.h>
84 #include <apt-pkg/error.h>
85 #include <apt-pkg/init.h>
86 #include <apt-pkg/mmap.h>
87 #include <apt-pkg/pkgrecords.h>
88 #include <apt-pkg/sha1.h>
89 #include <apt-pkg/sourcelist.h>
90 #include <apt-pkg/sptr.h>
91 #include <apt-pkg/strutl.h>
92 #include <apt-pkg/tagfile.h>
94 #include <apr-1/apr_pools.h>
96 #include <sys/types.h>
98 #include <sys/sysctl.h>
99 #include <sys/param.h>
100 #include <sys/mount.h>
106 #include <mach-o/nlist.h>
116 #include <ext/hash_map>
118 #import "UICaboodle/BrowserView.h"
119 #import "UICaboodle/ResetView.h"
121 #import "substrate.h"
128 #define _timestamp ({ \
130 gettimeofday(&tv, NULL); \
131 tv.tv_sec * 1000000 + tv.tv_usec; \
134 typedef std::vector<class ProfileTime *> TimeList;
144 ProfileTime(const char *name) :
148 times_.push_back(this);
151 void AddTime(uint64_t time) {
158 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
170 ProfileTimer(ProfileTime &time) :
177 time_.AddTime(_timestamp - start_);
182 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
184 std::cerr << "========" << std::endl;
187 #define _profile(name) { \
188 static ProfileTime name(#name); \
189 ProfileTimer _ ## name(name);
193 /* Objective-C Handle<> {{{ */
194 template <typename Type_>
196 typedef _H<Type_> This_;
201 _finline void Retain_() {
206 _finline void Clear_() {
212 _finline _H(const This_ &rhs) :
213 value_(rhs.value_ == nil ? nil : [rhs.value_ retain])
217 _finline _H(Type_ *value = NULL, bool mended = false) :
228 _finline operator Type_ *() const {
232 _finline This_ &operator =(Type_ *value) {
233 if (value_ != value) {
244 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
246 void NSLogPoint(const char *fix, const CGPoint &point) {
247 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
250 void NSLogRect(const char *fix, const CGRect &rect) {
251 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
254 /* [NSObject yieldToSelector:(withObject:)] {{{*/
255 @interface NSObject (Cydia)
256 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
257 - (id) yieldToSelector:(SEL)selector;
260 @implementation NSObject (Cydia)
265 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
266 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
267 id object([[context objectAtIndex:1] nonretainedObjectValue]);
268 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
270 /* XXX: deal with exceptions */
271 id value([self performSelector:selector withObject:object]);
273 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
274 [context removeAllObjects];
275 if ([signature methodReturnLength] != 0 && value != nil)
276 [context addObject:value];
281 performSelectorOnMainThread:@selector(doNothing)
287 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
288 /*return [self performSelector:selector withObject:object];*/
290 volatile bool stopped(false);
292 NSMutableArray *context([NSMutableArray arrayWithObjects:
293 [NSValue valueWithPointer:selector],
294 [NSValue valueWithNonretainedObject:object],
295 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
298 NSThread *thread([[[NSThread alloc]
300 selector:@selector(_yieldToContext:)
306 NSRunLoop *loop([NSRunLoop currentRunLoop]);
307 NSDate *future([NSDate distantFuture]);
309 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
311 return [context count] == 0 ? nil : [context objectAtIndex:0];
314 - (id) yieldToSelector:(SEL)selector {
315 return [self yieldToSelector:selector withObject:nil];
321 /* NSForcedOrderingSearch doesn't work on the iPhone */
322 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
323 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
324 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
326 /* iPhoneOS 2.0 Compatibility {{{ */
328 @interface UITextView (iPhoneOS)
329 - (void) setTextSize:(float)size;
332 @implementation UITextView (iPhoneOS)
334 - (void) setTextSize:(float)size {
335 [self setFont:[[self font] fontWithSize:size]];
342 /* Information Dictionaries {{{ */
343 @interface NSMutableArray (Cydia)
344 - (void) addInfoDictionary:(NSDictionary *)info;
347 @implementation NSMutableArray (Cydia)
349 - (void) addInfoDictionary:(NSDictionary *)info {
350 [self addObject:info];
355 @interface NSMutableDictionary (Cydia)
356 - (void) addInfoDictionary:(NSDictionary *)info;
359 @implementation NSMutableDictionary (Cydia)
361 - (void) addInfoDictionary:(NSDictionary *)info {
362 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
367 /* Pop Transitions {{{ */
368 @interface PopTransitionView : UITransitionView {
373 @implementation PopTransitionView
375 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
376 if (from != nil && to == nil)
377 [self removeFromSuperview];
382 @implementation UIView (PopUpView)
384 - (void) popFromSuperviewAnimated:(BOOL)animated {
385 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
388 - (void) popSubview:(UIView *)view {
389 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
390 [transition setDelegate:transition];
391 [self addSubview:transition];
393 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
394 [transition transition:UITransitionNone toView:blank];
395 [transition transition:UITransitionPushFromBottom toView:view];
401 #define lprintf(args...) fprintf(stderr, args)
404 #define TraceLogging (1 && !ForRelease)
405 #define HistogramInsertionSort (0 && !ForRelease)
406 #define ProfileTimes (0 && !ForRelease)
407 #define ForSaurik (0 && !ForRelease)
408 #define LogBrowser (1 && !ForRelease)
409 #define TrackResize (0 && !ForRelease)
410 #define ManualRefresh (1 && !ForRelease)
411 #define ShowInternals (0 && !ForRelease)
412 #define IgnoreInstall (0 && !ForRelease)
413 #define RecycleWebViews 0
414 #define RecyclePackageViews 1
415 #define AlwaysReload (0 && !ForRelease)
419 #define _trace(args...)
424 #define _profile(name) {
427 #define PrintTimes() do {} while (false)
431 typedef uint32_t (*SKRadixFunction)(id, void *);
433 @interface NSMutableArray (Radix)
434 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
435 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
443 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
444 struct RadixItem_ *lhs(swap), *rhs(swap + count);
446 static const size_t width = 32;
447 static const size_t bits = 11;
448 static const size_t slots = 1 << bits;
449 static const size_t passes = (width + (bits - 1)) / bits;
451 size_t *hist(new size_t[slots]);
453 for (size_t pass(0); pass != passes; ++pass) {
454 memset(hist, 0, sizeof(size_t) * slots);
456 for (size_t i(0); i != count; ++i) {
457 uint32_t key(lhs[i].key);
459 key &= _not(uint32_t) >> width - bits;
464 for (size_t i(0); i != slots; ++i) {
465 size_t local(offset);
470 for (size_t i(0); i != count; ++i) {
471 uint32_t key(lhs[i].key);
473 key &= _not(uint32_t) >> width - bits;
474 rhs[hist[key]++] = lhs[i];
477 RadixItem_ *tmp(lhs);
484 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
485 for (size_t i(0); i != count; ++i)
486 [values addObject:[self objectAtIndex:lhs[i].index]];
487 [self setArray:values];
492 @implementation NSMutableArray (Radix)
494 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
495 size_t count([self count]);
500 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
501 [invocation setSelector:selector];
502 [invocation setArgument:&object atIndex:2];
504 /* XXX: this is an unsafe optimization of doomy hell */
505 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
506 _assert(method != NULL);
507 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
508 _assert(imp != NULL);
511 struct RadixItem_ *swap(new RadixItem_[count * 2]);
513 for (size_t i(0); i != count; ++i) {
514 RadixItem_ &item(swap[i]);
517 id object([self objectAtIndex:i]);
520 [invocation setTarget:object];
522 [invocation getReturnValue:&item.key];
524 item.key = imp(object, selector, object);
528 RadixSort_(self, count, swap);
531 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
532 size_t count([self count]);
533 struct RadixItem_ *swap(new RadixItem_[count * 2]);
535 for (size_t i(0); i != count; ++i) {
536 RadixItem_ &item(swap[i]);
539 id object([self objectAtIndex:i]);
540 item.key = function(object, argument);
543 RadixSort_(self, count, swap);
548 /* Insertion Sort {{{ */
550 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
551 const char *ptr = (const char *)list;
553 CFIndex half = count / 2;
554 const char *probe = ptr + elementSize * half;
555 CFComparisonResult cr = comparator(element, probe, context);
556 if (0 == cr) return (probe - (const char *)list) / elementSize;
557 ptr = (cr < 0) ? ptr : probe + elementSize;
558 count = (cr < 0) ? half : (half + (count & 1) - 1);
560 return (ptr - (const char *)list) / elementSize;
563 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
564 const char *ptr = (const char *)list;
566 CFIndex half = count / 2;
567 const char *probe = ptr + elementSize * half;
568 CFComparisonResult cr = comparator(element, probe, context);
569 if (0 == cr) return (probe - (const char *)list) / elementSize;
570 ptr = (cr < 0) ? ptr : probe + elementSize;
571 count = (cr < 0) ? half : (half + (count & 1) - 1);
573 return (ptr - (const char *)list) / elementSize;
576 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
577 if (range.length == 0)
579 const void **values(new const void *[range.length]);
580 CFArrayGetValues(array, range, values);
582 #if HistogramInsertionSort
583 uint32_t total(0), *offsets(new uint32_t[range.length]);
586 for (CFIndex index(1); index != range.length; ++index) {
587 const void *value(values[index]);
588 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
589 CFIndex correct(index);
590 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
593 if (correct != index) {
594 size_t offset(index - correct);
595 #if HistogramInsertionSort
599 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
601 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
602 values[correct] = value;
606 CFArrayReplaceValues(array, range, values, range.length);
609 #if HistogramInsertionSort
610 for (CFIndex index(0); index != range.length; ++index)
611 if (offsets[index] != 0)
612 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
613 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
620 /* Apple Bug Fixes {{{ */
621 @implementation UIWebDocumentView (Cydia)
623 - (void) _setScrollerOffset:(CGPoint)offset {
624 UIScroller *scroller([self _scroller]);
626 CGSize size([scroller contentSize]);
627 CGSize bounds([scroller bounds].size);
630 max.x = size.width - bounds.width;
631 max.y = size.height - bounds.height;
639 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
640 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
642 [scroller setOffset:offset];
648 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
649 size_t length([self length] - state->state);
652 else if (length > count)
654 for (size_t i(0); i != length; ++i)
655 objects[i] = [self item:state->state++];
656 state->itemsPtr = objects;
657 state->mutationsPtr = (unsigned long *) self;
661 @interface NSString (UIKit)
662 - (NSString *) stringByAddingPercentEscapes;
665 /* Cydia NSString Additions {{{ */
666 @interface NSString (Cydia)
667 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
668 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
669 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
670 - (NSComparisonResult) compareByPath:(NSString *)other;
671 - (NSString *) stringByCachingURLWithCurrentCDN;
672 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
675 @implementation NSString (Cydia)
677 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
678 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
681 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
682 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
683 memcpy(data, bytes, length);
684 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
687 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
688 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
691 - (NSComparisonResult) compareByPath:(NSString *)other {
692 NSString *prefix = [self commonPrefixWithString:other options:0];
693 size_t length = [prefix length];
695 NSRange lrange = NSMakeRange(length, [self length] - length);
696 NSRange rrange = NSMakeRange(length, [other length] - length);
698 lrange = [self rangeOfString:@"/" options:0 range:lrange];
699 rrange = [other rangeOfString:@"/" options:0 range:rrange];
701 NSComparisonResult value;
703 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
704 value = NSOrderedSame;
705 else if (lrange.location == NSNotFound)
706 value = NSOrderedAscending;
707 else if (rrange.location == NSNotFound)
708 value = NSOrderedDescending;
710 value = NSOrderedSame;
712 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
713 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
714 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
715 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
717 NSComparisonResult result = [lpath compare:rpath];
718 return result == NSOrderedSame ? value : result;
721 - (NSString *) stringByCachingURLWithCurrentCDN {
723 stringByReplacingOccurrencesOfString:@"://"
724 withString:@"://ne.edgecastcdn.net/8003A4/"
726 /* XXX: this is somewhat inaccurate */
727 range:NSMakeRange(0, 10)
731 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
732 return [(id)CFURLCreateStringByAddingPercentEscapes(
737 kCFStringEncodingUTF8
744 /* C++ NSString Wrapper Cache {{{ */
751 _finline void clear_() {
752 if (cache_ != NULL) {
759 _finline bool empty() const {
763 _finline size_t size() const {
767 _finline char *data() const {
771 _finline void clear() {
776 _finline CYString() :
783 _finline ~CYString() {
787 void operator =(const CYString &rhs) {
791 if (rhs.cache_ == nil)
794 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
797 void set(apr_pool_t *pool, const char *data, size_t size) {
803 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
804 memcpy(temp, data, size);
811 _finline void set(apr_pool_t *pool, const char *data) {
812 set(pool, data, data == NULL ? 0 : strlen(data));
815 _finline void set(apr_pool_t *pool, const std::string &rhs) {
816 set(pool, rhs.data(), rhs.size());
819 bool operator ==(const CYString &rhs) const {
820 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
823 operator CFStringRef() {
824 if (cache_ == NULL) {
827 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
831 _finline operator id() {
832 return (NSString *) static_cast<CFStringRef>(*this);
836 /* C++ NSString Algorithm Adapters {{{ */
838 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
841 struct NSStringMapHash :
842 std::unary_function<NSString *, size_t>
844 _finline size_t operator ()(NSString *value) const {
845 return CFStringHashNSString((CFStringRef) value);
849 struct NSStringMapLess :
850 std::binary_function<NSString *, NSString *, bool>
852 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
853 return [lhs compare:rhs] == NSOrderedAscending;
857 struct NSStringMapEqual :
858 std::binary_function<NSString *, NSString *, bool>
860 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
861 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
862 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
863 //[lhs isEqualToString:rhs];
868 /* Perl-Compatible RegEx {{{ */
878 Pcre(const char *regex) :
883 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
886 lprintf("%d:%s\n", offset, error);
890 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
891 matches_ = new int[(capture_ + 1) * 3];
899 NSString *operator [](size_t match) {
900 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
903 bool operator ()(NSString *data) {
904 // XXX: length is for characters, not for bytes
905 return operator ()([data UTF8String], [data length]);
908 bool operator ()(const char *data, size_t size) {
910 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
914 /* Mime Addresses {{{ */
915 @interface Address : NSObject {
921 - (NSString *) address;
923 - (void) setAddress:(NSString *)address;
925 + (Address *) addressWithString:(NSString *)string;
926 - (Address *) initWithString:(NSString *)string;
929 @implementation Address
938 - (NSString *) name {
942 - (NSString *) address {
946 - (void) setAddress:(NSString *)address {
948 [address_ autorelease];
952 address_ = [address retain];
955 + (Address *) addressWithString:(NSString *)string {
956 return [[[Address alloc] initWithString:string] autorelease];
959 + (NSArray *) _attributeKeys {
960 return [NSArray arrayWithObjects:@"address", @"name", nil];
963 - (NSArray *) attributeKeys {
964 return [[self class] _attributeKeys];
967 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
968 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
971 - (Address *) initWithString:(NSString *)string {
972 if ((self = [super init]) != nil) {
973 const char *data = [string UTF8String];
974 size_t size = [string length];
976 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
978 if (address_r(data, size)) {
979 name_ = [address_r[1] retain];
980 address_ = [address_r[2] retain];
982 name_ = [string retain];
990 /* CoreGraphics Primitives {{{ */
1001 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1004 Set(space, red, green, blue, alpha);
1009 CGColorRelease(color_);
1016 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1018 float color[] = {red, green, blue, alpha};
1019 color_ = CGColorCreate(space, color);
1022 operator CGColorRef() {
1028 /* Random Global Variables {{{ */
1029 static const int PulseInterval_ = 50000;
1030 static const int ButtonBarHeight_ = 48;
1031 static const float KeyboardTime_ = 0.3f;
1033 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1034 #define NotifyConfig_ "/etc/notify.conf"
1036 static bool Queuing_;
1038 static CGColor Blue_;
1039 static CGColor Blueish_;
1040 static CGColor Black_;
1041 static CGColor Off_;
1042 static CGColor White_;
1043 static CGColor Gray_;
1044 static CGColor Green_;
1045 static CGColor Purple_;
1046 static CGColor Purplish_;
1048 static UIColor *InstallingColor_;
1049 static UIColor *RemovingColor_;
1051 static NSString *App_;
1052 static NSString *Home_;
1054 static BOOL Advanced_;
1055 static BOOL Loaded_;
1056 static BOOL Ignored_;
1058 static UIFont *Font12_;
1059 static UIFont *Font12Bold_;
1060 static UIFont *Font14_;
1061 static UIFont *Font18Bold_;
1062 static UIFont *Font22Bold_;
1064 static const char *Machine_ = NULL;
1065 static const NSString *System_ = NULL;
1066 static const NSString *SerialNumber_ = nil;
1067 static const NSString *ChipID_ = nil;
1068 static const NSString *UniqueID_ = nil;
1069 static const NSString *Build_ = nil;
1070 static const NSString *Product_ = nil;
1071 static const NSString *Safari_ = nil;
1073 CFLocaleRef Locale_;
1074 NSArray *Languages_;
1075 CGColorSpaceRef space_;
1080 static NSDictionary *SectionMap_;
1081 static NSMutableDictionary *Metadata_;
1082 static _transient NSMutableDictionary *Settings_;
1083 static _transient NSString *Role_;
1084 static _transient NSMutableDictionary *Packages_;
1085 static _transient NSMutableDictionary *Sections_;
1086 static _transient NSMutableDictionary *Sources_;
1087 static bool Changed_;
1088 static NSDate *now_;
1091 static NSMutableArray *Documents_;
1094 NSString *GetLastUpdate() {
1095 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1098 return UCLocalize("NEVER_OR_UNKNOWN");
1100 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1101 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1103 CFRelease(formatter);
1105 return [(NSString *) formatted autorelease];
1108 /* Display Helpers {{{ */
1109 inline float Interpolate(float begin, float end, float fraction) {
1110 return (end - begin) * fraction + begin;
1113 /* XXX: localize this! */
1114 NSString *SizeString(double size) {
1115 bool negative = size < 0;
1120 while (size > 1024) {
1125 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1127 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1130 static _finline CFStringRef CFCString(const char *value) {
1131 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1134 const char *StripVersion_(const char *version) {
1135 const char *colon(strchr(version, ':'));
1137 version = colon + 1;
1141 CFStringRef StripVersion(const char *version) {
1142 const char *colon(strchr(version, ':'));
1144 version = colon + 1;
1145 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1147 return CFCString(version);
1150 NSString *LocalizeSection(NSString *section) {
1151 static Pcre title_r("^(.*?) \\((.*)\\)$");
1152 if (title_r(section)) {
1153 NSString *parent(title_r[1]);
1154 NSString *child(title_r[2]);
1156 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1157 LocalizeSection(parent),
1158 LocalizeSection(child)
1162 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1165 NSString *Simplify(NSString *title) {
1166 const char *data = [title UTF8String];
1167 size_t size = [title length];
1169 static Pcre square_r("^\\[(.*)\\]$");
1170 if (square_r(data, size))
1171 return Simplify(square_r[1]);
1173 static Pcre paren_r("^\\((.*)\\)$");
1174 if (paren_r(data, size))
1175 return Simplify(paren_r[1]);
1177 static Pcre title_r("^(.*?) \\((.*)\\)$");
1178 if (title_r(data, size))
1179 return Simplify(title_r[1]);
1185 bool isSectionVisible(NSString *section) {
1186 NSDictionary *metadata([Sections_ objectForKey:section]);
1187 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1188 return hidden == nil || ![hidden boolValue];
1192 static NSArray *Finishes_;
1194 /* Delegate Prototypes {{{ */
1198 @interface NSObject (ProgressDelegate)
1201 @implementation NSObject(ProgressDelegate)
1203 - (void) _setProgressError:(NSArray *)args {
1204 [self performSelector:@selector(setProgressError:forPackage:)
1205 withObject:[args objectAtIndex:0]
1206 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1212 @protocol ProgressDelegate
1213 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1214 - (void) setProgressTitle:(NSString *)title;
1215 - (void) setProgressPercent:(float)percent;
1216 - (void) startProgress;
1217 - (void) addProgressOutput:(NSString *)output;
1218 - (bool) isCancelling:(size_t)received;
1221 @protocol ConfigurationDelegate
1222 - (void) repairWithSelector:(SEL)selector;
1223 - (void) setConfigurationData:(NSString *)data;
1228 @protocol CydiaDelegate
1229 - (void) setPackageView:(PackageView *)view;
1230 - (void) clearPackage:(Package *)package;
1231 - (void) installPackage:(Package *)package;
1232 - (void) removePackage:(Package *)package;
1233 - (void) slideUp:(UIActionSheet *)alert;
1234 - (void) distUpgrade;
1235 - (void) updateData;
1237 - (void) askForSettings;
1238 - (UIProgressHUD *) addProgressHUD;
1239 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1240 - (RVPage *) pageForPackage:(NSString *)name;
1241 - (PackageView *) packageView;
1245 /* Status Delegation {{{ */
1247 public pkgAcquireStatus
1250 _transient NSObject<ProgressDelegate> *delegate_;
1258 void setDelegate(id delegate) {
1259 delegate_ = delegate;
1262 virtual bool MediaChange(std::string media, std::string drive) {
1266 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1269 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1270 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1271 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1274 virtual void Done(pkgAcquire::ItemDesc &item) {
1277 virtual void Fail(pkgAcquire::ItemDesc &item) {
1279 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1280 item.Owner->Status == pkgAcquire::Item::StatDone
1284 std::string &error(item.Owner->ErrorText);
1288 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1289 NSArray *fields([description componentsSeparatedByString:@" "]);
1290 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1292 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1293 withObject:[NSArray arrayWithObjects:
1294 [NSString stringWithUTF8String:error.c_str()],
1301 virtual bool Pulse(pkgAcquire *Owner) {
1302 bool value = pkgAcquireStatus::Pulse(Owner);
1305 double(CurrentBytes + CurrentItems) /
1306 double(TotalBytes + TotalItems)
1309 [delegate_ setProgressPercent:percent];
1310 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1313 virtual void Start() {
1314 [delegate_ startProgress];
1317 virtual void Stop() {
1321 /* Progress Delegation {{{ */
1326 _transient id<ProgressDelegate> delegate_;
1330 virtual void Update() {
1331 if (abs(Percent - percent_) > 2) {
1332 NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1336 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1337 [delegate_ setProgressPercent:(Percent / 100)];*/
1347 void setDelegate(id delegate) {
1348 delegate_ = delegate;
1351 virtual void Done() {
1353 //[delegate_ setProgressPercent:1];
1358 /* Database Interface {{{ */
1359 typedef std::map< unsigned long, _H<Source> > SourceMap;
1361 @interface Database : NSObject {
1367 pkgCacheFile cache_;
1368 pkgDepCache::Policy *policy_;
1369 pkgRecords *records_;
1370 pkgProblemResolver *resolver_;
1371 pkgAcquire *fetcher_;
1373 SPtr<pkgPackageManager> manager_;
1374 pkgSourceList *list_;
1377 NSMutableArray *packages_;
1379 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1388 + (Database *) sharedInstance;
1391 - (void) _readCydia:(NSNumber *)fd;
1392 - (void) _readStatus:(NSNumber *)fd;
1393 - (void) _readOutput:(NSNumber *)fd;
1397 - (Package *) packageWithName:(NSString *)name;
1399 - (pkgCacheFile &) cache;
1400 - (pkgDepCache::Policy *) policy;
1401 - (pkgRecords *) records;
1402 - (pkgProblemResolver *) resolver;
1403 - (pkgAcquire &) fetcher;
1404 - (pkgSourceList &) list;
1405 - (NSArray *) packages;
1406 - (NSArray *) sources;
1407 - (void) reloadData;
1415 - (void) setVisible;
1417 - (NSString *) updateWithStatus:(Status &)status;
1419 - (void) setDelegate:(id)delegate;
1420 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1424 /* Source Class {{{ */
1425 @interface Source : NSObject {
1426 CYString depiction_;
1427 CYString description_;
1433 CYString distribution_;
1438 NSString *authority_;
1440 CYString defaultIcon_;
1442 NSDictionary *record_;
1446 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1448 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1450 - (NSString *) depictionForPackage:(NSString *)package;
1451 - (NSString *) supportForPackage:(NSString *)package;
1453 - (NSDictionary *) record;
1457 - (NSString *) distribution;
1458 - (NSString *) type;
1460 - (NSString *) host;
1462 - (NSString *) name;
1463 - (NSString *) description;
1464 - (NSString *) label;
1465 - (NSString *) origin;
1466 - (NSString *) version;
1468 - (NSString *) defaultIcon;
1472 @implementation Source
1476 distribution_.clear();
1479 description_.clear();
1485 defaultIcon_.clear();
1487 if (record_ != nil) {
1497 if (authority_ != nil) {
1498 [authority_ release];
1508 + (NSArray *) _attributeKeys {
1509 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1512 - (NSArray *) attributeKeys {
1513 return [[self class] _attributeKeys];
1516 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1517 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1520 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1523 trusted_ = index->IsTrusted();
1525 uri_.set(pool, index->GetURI());
1526 distribution_.set(pool, index->GetDist());
1527 type_.set(pool, index->GetType());
1529 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1530 if (dindex != NULL) {
1532 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1535 pkgTagFile tags(&fd);
1537 pkgTagSection section;
1544 {"default-icon", &defaultIcon_},
1545 {"depiction", &depiction_},
1546 {"description", &description_},
1548 {"origin", &origin_},
1549 {"support", &support_},
1550 {"version", &version_},
1553 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1554 const char *start, *end;
1556 if (section.Find(names[i].name_, start, end)) {
1557 CYString &value(*names[i].value_);
1558 value.set(pool, start, end - start);
1564 record_ = [Sources_ objectForKey:[self key]];
1566 record_ = [record_ retain];
1568 NSURL *url([NSURL URLWithString:uri_]);
1572 host_ = [[host_ lowercaseString] retain];
1575 authority_ = [host_ retain];
1577 authority_ = [url path];
1580 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1581 if ((self = [super init]) != nil) {
1582 [self setMetaIndex:index inPool:pool];
1586 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1587 NSDictionary *lhr = [self record];
1588 NSDictionary *rhr = [source record];
1591 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1593 NSString *lhs = [self name];
1594 NSString *rhs = [source name];
1596 if ([lhs length] != 0 && [rhs length] != 0) {
1597 unichar lhc = [lhs characterAtIndex:0];
1598 unichar rhc = [rhs characterAtIndex:0];
1600 if (isalpha(lhc) && !isalpha(rhc))
1601 return NSOrderedAscending;
1602 else if (!isalpha(lhc) && isalpha(rhc))
1603 return NSOrderedDescending;
1606 return [lhs compare:rhs options:LaxCompareOptions_];
1609 - (NSString *) depictionForPackage:(NSString *)package {
1610 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1613 - (NSString *) supportForPackage:(NSString *)package {
1614 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1617 - (NSDictionary *) record {
1625 - (NSString *) uri {
1629 - (NSString *) distribution {
1630 return distribution_;
1633 - (NSString *) type {
1637 - (NSString *) key {
1638 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1641 - (NSString *) host {
1645 - (NSString *) name {
1646 return origin_.empty() ? authority_ : origin_;
1649 - (NSString *) description {
1650 return description_;
1653 - (NSString *) label {
1654 return label_.empty() ? authority_ : label_;
1657 - (NSString *) origin {
1661 - (NSString *) version {
1665 - (NSString *) defaultIcon {
1666 return defaultIcon_;
1671 /* Relationship Class {{{ */
1672 @interface Relationship : NSObject {
1677 - (NSString *) type;
1679 - (NSString *) name;
1683 @implementation Relationship
1691 - (NSString *) type {
1699 - (NSString *) name {
1706 /* Package Class {{{ */
1707 @interface Package : NSObject {
1711 pkgCache::VerIterator version_;
1712 pkgCache::PkgIterator iterator_;
1713 _transient Database *database_;
1714 pkgCache::VerFileIterator file_;
1721 NSString *section$_;
1727 CYString installed_;
1733 CYString depiction_;
1744 NSMutableArray *tags_;
1747 NSArray *relationships_;
1749 NSMutableDictionary *metadata_;
1750 _transient NSDate *firstSeen_;
1751 _transient NSDate *lastSeen_;
1755 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1756 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1758 - (pkgCache::PkgIterator) iterator;
1761 - (NSString *) section;
1762 - (NSString *) simpleSection;
1764 - (NSString *) longSection;
1765 - (NSString *) shortSection;
1769 - (Address *) maintainer;
1771 - (NSString *) longDescription;
1772 - (NSString *) shortDescription;
1775 - (NSMutableDictionary *) metadata;
1777 - (BOOL) subscribed;
1780 - (NSString *) latest;
1781 - (NSString *) installed;
1782 - (BOOL) uninstalled;
1785 - (BOOL) upgradableAndEssential:(BOOL)essential;
1788 - (BOOL) unfiltered;
1792 - (BOOL) halfConfigured;
1793 - (BOOL) halfInstalled;
1795 - (NSString *) mode;
1797 - (void) setVisible;
1800 - (NSString *) name;
1802 - (NSString *) homepage;
1803 - (NSString *) depiction;
1804 - (Address *) author;
1806 - (NSString *) support;
1808 - (NSArray *) files;
1809 - (NSArray *) relationships;
1810 - (NSArray *) warnings;
1811 - (NSArray *) applications;
1813 - (Source *) source;
1814 - (NSString *) role;
1816 - (BOOL) matches:(NSString *)text;
1818 - (bool) hasSupportingRole;
1819 - (BOOL) hasTag:(NSString *)tag;
1820 - (NSString *) primaryPurpose;
1821 - (NSArray *) purposes;
1822 - (bool) isCommercial;
1824 - (CYString &) cyname;
1826 - (uint32_t) compareBySection:(NSArray *)sections;
1828 - (uint32_t) compareForChanges;
1833 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1834 - (bool) isInstalledAndVisible:(NSNumber *)number;
1835 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1836 - (bool) isVisibleInSource:(Source *)source;
1840 uint32_t PackageChangesRadix(Package *self, void *) {
1845 uint32_t timestamp : 30;
1846 uint32_t ignored : 1;
1847 uint32_t upgradable : 1;
1851 bool upgradable([self upgradableAndEssential:YES]);
1852 value.bits.upgradable = upgradable ? 1 : 0;
1855 value.bits.timestamp = 0;
1856 value.bits.ignored = [self ignored] ? 0 : 1;
1857 value.bits.upgradable = 1;
1859 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1860 value.bits.ignored = 0;
1861 value.bits.upgradable = 0;
1864 return _not(uint32_t) - value.key;
1867 _finline static void Stifle(uint8_t &value) {
1870 uint32_t PackagePrefixRadix(Package *self, void *context) {
1871 size_t offset(reinterpret_cast<size_t>(context));
1872 CYString &name([self cyname]);
1874 size_t size(name.size());
1877 char *text(name.data());
1880 if (!isdigit(text[0]))
1884 while (size != digits && isdigit(text[digits]))
1894 if (offset == 0 && zeros != 0) {
1895 memset(data, '0', zeros);
1896 memcpy(data + zeros, text, 4 - zeros);
1898 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1899 if (size <= offset - zeros)
1902 text += offset - zeros;
1903 size -= offset - zeros;
1906 memcpy(data, text, 4);
1908 memcpy(data, text, size);
1909 memset(data + size, 0, 4 - size);
1912 for (size_t i(0); i != 4; ++i)
1913 if (isalpha(data[i]))
1918 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1920 /* XXX: ntohl may be more honest */
1921 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1924 CYString &(*PackageName)(Package *self, SEL sel);
1926 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1927 _profile(PackageNameCompare)
1928 CYString &lhi(PackageName(lhs, @selector(cyname)));
1929 CYString &rhi(PackageName(rhs, @selector(cyname)));
1930 CFStringRef lhn(lhi), rhn(rhi);
1932 _profile(PackageNameCompare$NumbersLast)
1933 if (!lhi.empty() && !rhi.empty()) {
1934 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1935 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1936 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1937 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1938 return lha ? NSOrderedAscending : NSOrderedDescending;
1942 CFIndex length = CFStringGetLength(lhn);
1944 _profile(PackageNameCompare$Compare)
1945 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1950 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1951 return PackageNameCompare(*lhs, *rhs, context);
1954 struct PackageNameOrdering :
1955 std::binary_function<Package *, Package *, bool>
1957 _finline bool operator ()(Package *lhs, Package *rhs) const {
1958 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1962 @implementation Package
1964 - (NSString *) description {
1965 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1971 if (section$_ != nil)
1972 [section$_ release];
1977 if (sponsor$_ != nil)
1978 [sponsor$_ release];
1979 if (author$_ != nil)
1986 if (relationships_ != nil)
1987 [relationships_ release];
1988 if (metadata_ != nil)
1989 [metadata_ release];
1994 + (NSString *) webScriptNameForSelector:(SEL)selector {
1995 if (selector == @selector(hasTag:))
2001 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2002 return [self webScriptNameForSelector:selector] == nil;
2005 + (NSArray *) _attributeKeys {
2006 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];
2009 - (NSArray *) attributeKeys {
2010 return [[self class] _attributeKeys];
2013 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2014 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2024 _profile(Package$parse)
2025 pkgRecords::Parser *parser;
2027 _profile(Package$parse$Lookup)
2028 parser = &[database_ records]->Lookup(file_);
2033 _profile(Package$parse$Find)
2039 {"depiction", &depiction_},
2040 {"homepage", &homepage_},
2041 {"website", &website},
2043 {"support", &support_},
2044 {"sponsor", &sponsor_},
2045 {"author", &author_},
2048 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2049 const char *start, *end;
2051 if (parser->Find(names[i].name_, start, end)) {
2052 CYString &value(*names[i].value_);
2053 _profile(Package$parse$Value)
2054 value.set(pool_, start, end - start);
2060 _profile(Package$parse$Tagline)
2061 const char *start, *end;
2062 if (parser->ShortDesc(start, end)) {
2063 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2066 while (stop != start && stop[-1] == '\r')
2068 tagline_.set(pool_, start, stop - start);
2072 _profile(Package$parse$Retain)
2073 if (homepage_.empty())
2074 homepage_ = website;
2075 if (homepage_ == depiction_)
2081 - (void) setVisible {
2082 visible_ = required_ && [self hasSupportingRole] && [self unfiltered];
2085 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2086 if ((self = [super init]) != nil) {
2087 _profile(Package$initWithVersion)
2088 @synchronized (database) {
2089 era_ = [database era];
2093 iterator_ = version.ParentPkg();
2094 database_ = database;
2096 _profile(Package$initWithVersion$Latest)
2097 latest_ = (NSString *) StripVersion(version_.VerStr());
2100 pkgCache::VerIterator current;
2101 _profile(Package$initWithVersion$Versions)
2102 current = iterator_.CurrentVer();
2104 installed_.set(pool_, StripVersion_(current.VerStr()));
2106 if (!version_.end())
2107 file_ = version_.FileList();
2109 pkgCache &cache([database_ cache]);
2110 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2114 _profile(Package$initWithVersion$Name)
2115 id_.set(pool_, iterator_.Name());
2116 name_.set(pool, iterator_.Display());
2120 _profile(Package$initWithVersion$Source)
2121 source_ = [database_ getSource:file_.File()];
2130 _profile(Package$initWithVersion$Tags)
2131 pkgCache::TagIterator tag(iterator_.TagList());
2133 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2135 const char *name(tag.Name());
2136 [tags_ addObject:(NSString *)CFCString(name)];
2137 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2138 role_ = (NSString *) CFCString(name + 6);
2139 if (required_ && strncmp(name, "require::", 9) == 0 && (
2144 } while (!tag.end());
2148 bool changed(false);
2149 NSString *key([id_ lowercaseString]);
2151 _profile(Package$initWithVersion$Metadata)
2152 metadata_ = [Packages_ objectForKey:key];
2154 if (metadata_ == nil) {
2157 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2158 firstSeen_, @"FirstSeen",
2159 latest_, @"LastVersion",
2164 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2165 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2167 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2168 subscribed_ = [subscribed boolValue];
2170 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2172 if (firstSeen_ == nil) {
2173 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2174 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2178 if (version == nil) {
2179 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2182 if (![version isEqualToString:latest_]) {
2183 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2185 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2190 metadata_ = [metadata_ retain];
2193 [Packages_ setObject:metadata_ forKey:key];
2198 _profile(Package$initWithVersion$Section)
2199 section_.set(pool_, iterator_.Section());
2202 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2204 } _end } return self;
2207 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2208 @synchronized ([Database class]) {
2209 pkgCache::VerIterator version;
2211 _profile(Package$packageWithIterator$GetCandidateVer)
2212 version = [database policy]->GetCandidateVer(iterator);
2218 return [[[Package alloc]
2219 initWithVersion:version
2226 - (pkgCache::PkgIterator) iterator {
2230 - (NSString *) section {
2231 if (section$_ == nil) {
2232 if (section_.empty())
2235 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2236 NSString *name(section_);
2239 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2240 if (NSString *rename = [value objectForKey:@"Rename"]) {
2245 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2249 - (NSString *) simpleSection {
2250 if (NSString *section = [self section])
2251 return Simplify(section);
2256 - (NSString *) longSection {
2257 return LocalizeSection([self section]);
2260 - (NSString *) shortSection {
2261 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2264 - (NSString *) uri {
2267 pkgIndexFile *index;
2268 pkgCache::PkgFileIterator file(file_.File());
2269 if (![database_ list].FindIndex(file, index))
2271 return [NSString stringWithUTF8String:iterator_->Path];
2272 //return [NSString stringWithUTF8String:file.Site()];
2273 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2277 - (Address *) maintainer {
2280 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2281 const std::string &maintainer(parser->Maintainer());
2282 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2286 return version_.end() ? 0 : version_->InstalledSize;
2289 - (NSString *) longDescription {
2292 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2293 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2295 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2296 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2297 if ([lines count] < 2)
2300 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2301 for (size_t i(1), e([lines count]); i != e; ++i) {
2302 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2303 [trimmed addObject:trim];
2306 return [trimmed componentsJoinedByString:@"\n"];
2309 - (NSString *) shortDescription {
2314 _profile(Package$index)
2315 CFStringRef name((CFStringRef) [self name]);
2316 if (CFStringGetLength(name) == 0)
2318 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2319 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2321 return toupper(character);
2325 - (NSMutableDictionary *) metadata {
2330 if (subscribed_ && lastSeen_ != nil)
2335 - (BOOL) subscribed {
2340 NSDictionary *metadata([self metadata]);
2341 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2342 return [ignored boolValue];
2347 - (NSString *) latest {
2351 - (NSString *) installed {
2355 - (BOOL) uninstalled {
2356 return installed_.empty();
2360 return !version_.end();
2363 - (BOOL) upgradableAndEssential:(BOOL)essential {
2364 _profile(Package$upgradableAndEssential)
2365 pkgCache::VerIterator current(iterator_.CurrentVer());
2367 return essential && essential_ && visible_;
2369 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2373 - (BOOL) essential {
2378 return [database_ cache][iterator_].InstBroken();
2381 - (BOOL) unfiltered {
2382 NSString *section([self section]);
2383 return section == nil || isSectionVisible(section);
2391 unsigned char current(iterator_->CurrentState);
2392 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2395 - (BOOL) halfConfigured {
2396 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2399 - (BOOL) halfInstalled {
2400 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2404 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2405 return state.Mode != pkgDepCache::ModeKeep;
2408 - (NSString *) mode {
2409 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2411 switch (state.Mode) {
2412 case pkgDepCache::ModeDelete:
2413 if ((state.iFlags & pkgDepCache::Purge) != 0)
2417 case pkgDepCache::ModeKeep:
2418 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2419 return @"REINSTALL";
2420 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2424 case pkgDepCache::ModeInstall:
2425 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2426 return @"REINSTALL";
2427 else*/ switch (state.Status) {
2429 return @"DOWNGRADE";
2435 return @"NEW_INSTALL";
2448 - (NSString *) name {
2449 return name_.empty() ? id_ : name_;
2452 - (UIImage *) icon {
2453 NSString *section = [self simpleSection];
2457 if ([icon_ hasPrefix:@"file:///"])
2458 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2459 if (icon == nil) if (section != nil)
2460 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2461 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2462 if ([dicon hasPrefix:@"file:///"])
2463 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2465 icon = [UIImage applicationImageNamed:@"unknown.png"];
2469 - (NSString *) homepage {
2473 - (NSString *) depiction {
2474 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2477 - (Address *) sponsor {
2478 if (sponsor$_ == nil) {
2479 if (sponsor_.empty())
2481 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2485 - (Address *) author {
2486 if (author$_ == nil) {
2487 if (author_.empty())
2489 author$_ = [[Address addressWithString:author_] retain];
2493 - (NSString *) support {
2494 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2497 - (NSArray *) files {
2498 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2499 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2502 fin.open([path UTF8String]);
2507 while (std::getline(fin, line))
2508 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2513 - (NSArray *) relationships {
2514 return relationships_;
2517 - (NSArray *) warnings {
2518 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2519 const char *name(iterator_.Name());
2521 size_t length(strlen(name));
2522 if (length < 2) invalid:
2523 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2524 else for (size_t i(0); i != length; ++i)
2526 /* XXX: technically this is not allowed */
2527 (name[i] < 'A' || name[i] > 'Z') &&
2528 (name[i] < 'a' || name[i] > 'z') &&
2529 (name[i] < '0' || name[i] > '9') &&
2530 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2533 if (strcmp(name, "cydia") != 0) {
2536 bool _private = false;
2539 bool repository = [[self section] isEqualToString:@"Repositories"];
2541 if (NSArray *files = [self files])
2542 for (NSString *file in files)
2543 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2545 else if (!user && [file isEqualToString:@"/User"])
2547 else if (!_private && [file isEqualToString:@"/private"])
2549 else if (!stash && [file isEqualToString:@"/var/stash"])
2552 /* XXX: this is not sensitive enough. only some folders are valid. */
2553 if (cydia && !repository)
2554 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2556 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2558 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2560 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2563 return [warnings count] == 0 ? nil : warnings;
2566 - (NSArray *) applications {
2567 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2569 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2571 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2572 if (NSArray *files = [self files])
2573 for (NSString *file in files)
2574 if (application_r(file)) {
2575 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2576 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2577 if ([id isEqualToString:me])
2580 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2582 display = application_r[1];
2584 NSString *bundle([file stringByDeletingLastPathComponent]);
2585 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2586 if (icon == nil || [icon length] == 0)
2588 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2590 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2591 [applications addObject:application];
2593 [application addObject:id];
2594 [application addObject:display];
2595 [application addObject:url];
2598 return [applications count] == 0 ? nil : applications;
2601 - (Source *) source {
2603 @synchronized (database_) {
2604 if ([database_ era] != era_ || file_.end())
2607 source_ = [database_ getSource:file_.File()];
2619 - (NSString *) role {
2623 - (BOOL) matches:(NSString *)text {
2629 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2630 if (range.location != NSNotFound)
2633 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2634 if (range.location != NSNotFound)
2637 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2638 if (range.location != NSNotFound)
2644 - (bool) hasSupportingRole {
2647 if ([role_ isEqualToString:@"enduser"])
2649 if ([Role_ isEqualToString:@"User"])
2651 if ([role_ isEqualToString:@"hacker"])
2653 if ([Role_ isEqualToString:@"Hacker"])
2655 if ([role_ isEqualToString:@"developer"])
2657 if ([Role_ isEqualToString:@"Developer"])
2662 - (BOOL) hasTag:(NSString *)tag {
2663 return tags_ == nil ? NO : [tags_ containsObject:tag];
2666 - (NSString *) primaryPurpose {
2667 for (NSString *tag in tags_)
2668 if ([tag hasPrefix:@"purpose::"])
2669 return [tag substringFromIndex:9];
2673 - (NSArray *) purposes {
2674 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2675 for (NSString *tag in tags_)
2676 if ([tag hasPrefix:@"purpose::"])
2677 [purposes addObject:[tag substringFromIndex:9]];
2678 return [purposes count] == 0 ? nil : purposes;
2681 - (bool) isCommercial {
2682 return [self hasTag:@"cydia::commercial"];
2685 - (CYString &) cyname {
2686 return name_.empty() ? id_ : name_;
2689 - (uint32_t) compareBySection:(NSArray *)sections {
2690 NSString *section([self section]);
2691 for (size_t i(0), e([sections count]); i != e; ++i) {
2692 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2696 return _not(uint32_t);
2699 - (uint32_t) compareForChanges {
2704 uint32_t timestamp : 30;
2705 uint32_t ignored : 1;
2706 uint32_t upgradable : 1;
2710 bool upgradable([self upgradableAndEssential:YES]);
2711 value.bits.upgradable = upgradable ? 1 : 0;
2714 value.bits.timestamp = 0;
2715 value.bits.ignored = [self ignored] ? 0 : 1;
2716 value.bits.upgradable = 1;
2718 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2719 value.bits.ignored = 0;
2720 value.bits.upgradable = 0;
2723 return _not(uint32_t) - value.key;
2727 pkgProblemResolver *resolver = [database_ resolver];
2728 resolver->Clear(iterator_);
2729 resolver->Protect(iterator_);
2733 pkgProblemResolver *resolver = [database_ resolver];
2734 resolver->Clear(iterator_);
2735 resolver->Protect(iterator_);
2736 pkgCacheFile &cache([database_ cache]);
2737 cache->MarkInstall(iterator_, false);
2738 pkgDepCache::StateCache &state((*cache)[iterator_]);
2739 if (!state.Install())
2740 cache->SetReInstall(iterator_, true);
2744 pkgProblemResolver *resolver = [database_ resolver];
2745 resolver->Clear(iterator_);
2746 resolver->Protect(iterator_);
2747 resolver->Remove(iterator_);
2748 [database_ cache]->MarkDelete(iterator_, true);
2751 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2752 _profile(Package$isUnfilteredAndSearchedForBy)
2755 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2756 value &= [self unfiltered];
2759 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2760 value &= [self matches:search];
2767 - (bool) isInstalledAndVisible:(NSNumber *)number {
2768 return (![number boolValue] || [self visible]) && ![self uninstalled];
2771 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2772 NSString *section = [self section];
2776 [self uninstalled] && (
2778 section == nil && [name length] == 0 ||
2779 [name isEqualToString:section]
2783 - (bool) isVisibleInSource:(Source *)source {
2784 return [self source] == source && [self visible];
2789 /* Section Class {{{ */
2790 @interface Section : NSObject {
2795 NSString *localized_;
2798 - (NSComparisonResult) compareByLocalized:(Section *)section;
2799 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2800 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2801 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2802 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2803 - (NSString *) name;
2810 - (void) addToCount;
2812 - (void) setCount:(size_t)count;
2813 - (NSString *) localized;
2817 @implementation Section
2821 if (localized_ != nil)
2822 [localized_ release];
2826 - (NSComparisonResult) compareByLocalized:(Section *)section {
2827 NSString *lhs(localized_);
2828 NSString *rhs([section localized]);
2830 /*if ([lhs length] != 0 && [rhs length] != 0) {
2831 unichar lhc = [lhs characterAtIndex:0];
2832 unichar rhc = [rhs characterAtIndex:0];
2834 if (isalpha(lhc) && !isalpha(rhc))
2835 return NSOrderedAscending;
2836 else if (!isalpha(lhc) && isalpha(rhc))
2837 return NSOrderedDescending;
2840 return [lhs compare:rhs options:LaxCompareOptions_];
2843 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2844 if ((self = [self initWithName:name localize:NO]) != nil) {
2845 if (localized != nil)
2846 localized_ = [localized retain];
2850 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2851 return [self initWithName:name row:0 localize:localize];
2854 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2855 if ((self = [super init]) != nil) {
2856 name_ = [name retain];
2860 localized_ = [LocalizeSection(name_) retain];
2864 /* XXX: localize the index thingees */
2865 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2866 if ((self = [super init]) != nil) {
2867 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2873 - (NSString *) name {
2893 - (void) addToCount {
2897 - (void) setCount:(size_t)count {
2901 - (NSString *) localized {
2908 /* Database Implementation {{{ */
2909 @implementation Database
2911 + (Database *) sharedInstance {
2912 static Database *instance;
2913 if (instance == nil)
2914 instance = [[Database alloc] init];
2924 NSRecycleZone(zone_);
2925 // XXX: malloc_destroy_zone(zone_);
2926 apr_pool_destroy(pool_);
2930 - (void) _readCydia:(NSNumber *)fd { _pooled
2931 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2932 std::istream is(&ib);
2935 static Pcre finish_r("^finish:([^:]*)$");
2937 while (std::getline(is, line)) {
2938 const char *data(line.c_str());
2939 size_t size = line.size();
2940 lprintf("C:%s\n", data);
2942 if (finish_r(data, size)) {
2943 NSString *finish = finish_r[1];
2944 int index = [Finishes_ indexOfObject:finish];
2945 if (index != INT_MAX && index > Finish_)
2953 - (void) _readStatus:(NSNumber *)fd { _pooled
2954 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2955 std::istream is(&ib);
2958 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2959 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2961 while (std::getline(is, line)) {
2962 const char *data(line.c_str());
2963 size_t size = line.size();
2964 lprintf("S:%s\n", data);
2966 if (conffile_r(data, size)) {
2967 [delegate_ setConfigurationData:conffile_r[1]];
2968 } else if (strncmp(data, "status: ", 8) == 0) {
2969 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2970 [delegate_ setProgressTitle:string];
2971 } else if (pmstatus_r(data, size)) {
2972 std::string type([pmstatus_r[1] UTF8String]);
2973 NSString *id = pmstatus_r[2];
2975 float percent([pmstatus_r[3] floatValue]);
2976 [delegate_ setProgressPercent:(percent / 100)];
2978 NSString *string = pmstatus_r[4];
2980 if (type == "pmerror")
2981 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2982 withObject:[NSArray arrayWithObjects:string, id, nil]
2985 else if (type == "pmstatus") {
2986 [delegate_ setProgressTitle:string];
2987 } else if (type == "pmconffile")
2988 [delegate_ setConfigurationData:string];
2989 else _assert(false);
2990 } else _assert(false);
2996 - (void) _readOutput:(NSNumber *)fd { _pooled
2997 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2998 std::istream is(&ib);
3001 while (std::getline(is, line)) {
3002 lprintf("O:%s\n", line.c_str());
3003 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3013 - (Package *) packageWithName:(NSString *)name {
3014 @synchronized ([Database class]) {
3015 if (static_cast<pkgDepCache *>(cache_) == NULL)
3017 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3018 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3021 - (Database *) init {
3022 if ((self = [super init]) != nil) {
3029 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3030 apr_pool_create(&pool_, NULL);
3032 packages_ = [[NSMutableArray alloc] init];
3036 _assert(pipe(fds) != -1);
3039 _config->Set("APT::Keep-Fds::", cydiafd_);
3040 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3043 detachNewThreadSelector:@selector(_readCydia:)
3045 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3048 _assert(pipe(fds) != -1);
3052 detachNewThreadSelector:@selector(_readStatus:)
3054 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3057 _assert(pipe(fds) != -1);
3058 _assert(dup2(fds[0], 0) != -1);
3059 _assert(close(fds[0]) != -1);
3061 input_ = fdopen(fds[1], "a");
3063 _assert(pipe(fds) != -1);
3064 _assert(dup2(fds[1], 1) != -1);
3065 _assert(close(fds[1]) != -1);
3068 detachNewThreadSelector:@selector(_readOutput:)
3070 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3075 - (pkgCacheFile &) cache {
3079 - (pkgDepCache::Policy *) policy {
3083 - (pkgRecords *) records {
3087 - (pkgProblemResolver *) resolver {
3091 - (pkgAcquire &) fetcher {
3095 - (pkgSourceList &) list {
3099 - (NSArray *) packages {
3103 - (NSArray *) sources {
3104 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3105 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3106 [sources addObject:i->second];
3110 - (NSArray *) issues {
3111 if (cache_->BrokenCount() == 0)
3114 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3116 for (Package *package in packages_) {
3117 if (![package broken])
3119 pkgCache::PkgIterator pkg([package iterator]);
3121 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3122 [entry addObject:[package name]];
3123 [issues addObject:entry];
3125 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3129 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3130 pkgCache::DepIterator start;
3131 pkgCache::DepIterator end;
3132 dep.GlobOr(start, end); // ++dep
3134 if (!cache_->IsImportantDep(end))
3136 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3139 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3140 [entry addObject:failure];
3141 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3143 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3144 if (Package *package = [self packageWithName:name])
3145 name = [package name];
3146 [failure addObject:name];
3148 pkgCache::PkgIterator target(start.TargetPkg());
3149 if (target->ProvidesList != 0)
3150 [failure addObject:@"?"];
3152 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3154 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3155 else if (!cache_[target].CandidateVerIter(cache_).end())
3156 [failure addObject:@"-"];
3157 else if (target->ProvidesList == 0)
3158 [failure addObject:@"!"];
3160 [failure addObject:@"%"];
3164 if (start.TargetVer() != 0)
3165 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3176 - (void) reloadData { _pooled
3177 @synchronized ([Database class]) {
3179 @synchronized (self) {
3183 [packages_ removeAllObjects];
3209 apr_pool_clear(pool_);
3210 NSRecycleZone(zone_);
3212 int chk(creat("/tmp/cydia.chk", 0644));
3217 if (!cache_.Open(progress_, true)) {
3219 if (!_error->PopMessage(error))
3222 lprintf("cache_.Open():[%s]\n", error.c_str());
3224 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3225 [delegate_ repairWithSelector:@selector(configure)];
3226 else if (error == "The package lists or status file could not be parsed or opened.")
3227 [delegate_ repairWithSelector:@selector(update)];
3228 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3229 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3230 // else if (error == "The list of sources could not be read.")
3231 else _assert(false);
3237 unlink("/tmp/cydia.chk");
3239 now_ = [[NSDate date] retain];
3241 policy_ = new pkgDepCache::Policy();
3242 records_ = new pkgRecords(cache_);
3243 resolver_ = new pkgProblemResolver(cache_);
3244 fetcher_ = new pkgAcquire(&status_);
3247 list_ = new pkgSourceList();
3248 _assert(list_->ReadMainList());
3250 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3251 _assert(pkgApplyStatus(cache_));
3253 if (cache_->BrokenCount() != 0) {
3254 _assert(pkgFixBroken(cache_));
3255 _assert(cache_->BrokenCount() == 0);
3256 _assert(pkgMinimizeUpgrade(cache_));
3261 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3262 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3263 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3264 // XXX: this could be more intelligent
3265 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3266 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3268 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3275 /*std::vector<Package *> packages;
3276 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3277 [packages_ release];
3282 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3283 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3284 //packages.push_back(package);
3285 [packages_ addObject:package];
3289 /*if (packages.empty())
3290 packages_ = [[NSArray alloc] init];
3292 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3295 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3296 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3297 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3305 /*if (!packages.empty())
3306 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3307 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3309 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3311 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3313 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3319 - (void) configure {
3320 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3321 system([dpkg UTF8String]);
3329 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3330 _assert(!_error->PendingError());
3333 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3336 public pkgArchiveCleaner
3339 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3344 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3346 while (_error->PopMessage(error))
3347 lprintf("ArchiveCleaner: %s\n", error.c_str());
3352 fetcher_->Shutdown();
3354 pkgRecords records(cache_);
3356 lock_ = new FileFd();
3357 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3358 _assert(!_error->PendingError());
3361 // XXX: explain this with an error message
3362 _assert(list.ReadMainList());
3364 manager_ = (_system->CreatePM(cache_));
3365 _assert(manager_->GetArchives(fetcher_, &list, &records));
3366 _assert(!_error->PendingError());
3370 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3372 _assert(list.ReadMainList());
3373 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3374 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3377 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3382 bool failed = false;
3383 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3384 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3386 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3389 std::string uri = (*item)->DescURI();
3390 std::string error = (*item)->ErrorText;
3392 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3395 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3396 withObject:[NSArray arrayWithObjects:
3397 [NSString stringWithUTF8String:error.c_str()],
3409 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3411 if (_error->PendingError()) {
3416 if (result == pkgPackageManager::Failed) {
3421 if (result != pkgPackageManager::Completed) {
3426 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3428 _assert(list.ReadMainList());
3429 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3430 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3433 if (![before isEqualToArray:after])
3438 _assert(pkgDistUpgrade(cache_));
3442 [self updateWithStatus:status_];
3445 - (void) setVisible {
3446 for (Package *package in packages_)
3447 [package setVisible];
3450 - (NSString *) updateWithStatus:(Status &)status {
3452 _assert(list.ReadMainList());
3455 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3457 if (_error->PendingError()) error: {
3459 if (!_error->PopMessage(error))
3462 return [NSString stringWithUTF8String:error.c_str()];
3465 if (!ListUpdate(status, list, PulseInterval_))
3468 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3474 - (void) setDelegate:(id)delegate {
3475 delegate_ = delegate;
3476 status_.setDelegate(delegate);
3477 progress_.setDelegate(delegate);
3480 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3481 SourceMap::const_iterator i(sources_.find(file->ID));
3482 return i == sources_.end() ? nil : i->second;
3488 /* PopUp Windows {{{ */
3489 @interface PopUpView : UIView {
3490 _transient id delegate_;
3491 UITransitionView *transition_;
3496 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3500 @implementation PopUpView
3503 [transition_ setDelegate:nil];
3504 [transition_ release];
3510 [transition_ transition:UITransitionPushFromTop toView:nil];
3513 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3514 if (from != nil && to == nil)
3515 [self removeFromSuperview];
3518 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3519 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3520 delegate_ = delegate;
3522 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3523 [self addSubview:transition_];
3525 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3527 [view addSubview:self];
3529 [transition_ setDelegate:self];
3531 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3532 [transition_ transition:UITransitionNone toView:blank];
3533 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3540 /* Confirmation View {{{ */
3541 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3542 if (!iterator.end())
3543 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3544 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3546 pkgCache::PkgIterator package(dep.TargetPkg());
3549 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3556 /* Web Scripting {{{ */
3557 @interface CydiaObject : NSObject {
3561 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3564 @implementation CydiaObject
3567 [indirect_ release];
3571 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3572 if ((self = [super init]) != nil) {
3573 indirect_ = [indirect retain];
3577 + (NSArray *) _attributeKeys {
3578 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3581 - (NSArray *) attributeKeys {
3582 return [[self class] _attributeKeys];
3585 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3586 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3589 - (NSString *) device {
3590 return [[UIDevice currentDevice] uniqueIdentifier];
3593 #if 0 // XXX: implement!
3594 - (NSString *) mac {
3595 if (![indirect_ promptForSensitive:@"Mac Address"])
3599 - (NSString *) serial {
3600 if (![indirect_ promptForSensitive:@"Serial #"])
3604 - (NSString *) firewire {
3605 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3609 - (NSString *) imei {
3610 if (![indirect_ promptForSensitive:@"IMEI"])
3615 + (NSString *) webScriptNameForSelector:(SEL)selector {
3616 if (selector == @selector(close))
3618 else if (selector == @selector(getPackageById:))
3619 return @"getPackageById";
3620 else if (selector == @selector(setAutoPopup:))
3621 return @"setAutoPopup";
3622 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3623 return @"setButtonImage";
3624 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3625 return @"setButtonTitle";
3626 else if (selector == @selector(setFinishHook:))
3627 return @"setFinishHook";
3628 else if (selector == @selector(setPopupHook:))
3629 return @"setPopupHook";
3630 else if (selector == @selector(setSpecial:))
3631 return @"setSpecial";
3632 else if (selector == @selector(setViewportWidth:))
3633 return @"setViewportWidth";
3634 else if (selector == @selector(supports:))
3636 else if (selector == @selector(stringWithFormat:arguments:))
3638 else if (selector == @selector(localizedStringForKey:value:table:))
3640 else if (selector == @selector(du:))
3642 else if (selector == @selector(statfs:))
3648 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3649 return [self webScriptNameForSelector:selector] == nil;
3652 - (BOOL) supports:(NSString *)feature {
3653 return [feature isEqualToString:@"window.open"];
3656 - (Package *) getPackageById:(NSString *)id {
3657 Package *package([[Database sharedInstance] packageWithName:id]);
3662 - (NSArray *) statfs:(NSString *)path {
3665 if (path == nil || statfs([path UTF8String], &stat) == -1)
3668 return [NSArray arrayWithObjects:
3669 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3670 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3671 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3675 - (NSNumber *) du:(NSString *)path {
3676 NSNumber *value(nil);
3679 _assert(pipe(fds) != -1);
3681 pid_t pid(ExecFork());
3683 _assert(dup2(fds[1], 1) != -1);
3684 _assert(close(fds[0]) != -1);
3685 _assert(close(fds[1]) != -1);
3686 /* XXX: this should probably not use du */
3687 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3692 _assert(close(fds[1]) != -1);
3694 if (FILE *du = fdopen(fds[0], "r")) {
3696 while (fgets(line, sizeof(line), du) != NULL) {
3697 size_t length(strlen(line));
3698 while (length != 0 && line[length - 1] == '\n')
3699 line[--length] = '\0';
3700 if (char *tab = strchr(line, '\t')) {
3702 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3707 } else _assert(close(fds[0]));
3711 if (waitpid(pid, &status, 0) == -1)
3714 else _assert(false);
3723 - (void) setAutoPopup:(BOOL)popup {
3724 [indirect_ setAutoPopup:popup];
3727 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3728 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3731 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3732 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3735 - (void) setSpecial:(id)function {
3736 [indirect_ setSpecial:function];
3739 - (void) setFinishHook:(id)function {
3740 [indirect_ setFinishHook:function];
3743 - (void) setPopupHook:(id)function {
3744 [indirect_ setPopupHook:function];
3747 - (void) setViewportWidth:(float)width {
3748 [indirect_ setViewportWidth:width];
3751 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3752 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3753 unsigned count([arguments count]);
3755 for (unsigned i(0); i != count; ++i)
3756 values[i] = [arguments objectAtIndex:i];
3757 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3760 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3761 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3763 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3765 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3771 @interface CydiaBrowserView : BrowserView {
3772 CydiaObject *cydia_;
3777 @implementation CydiaBrowserView
3784 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3785 [super webView:sender didClearWindowObject:window forFrame:frame];
3786 [window setValue:cydia_ forKey:@"cydia"];
3789 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3790 if (System_ != NULL)
3791 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3792 if (Machine_ != NULL)
3793 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3794 if (UniqueID_ != nil)
3795 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
3797 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3800 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3801 NSMutableURLRequest *copy = [request mutableCopy];
3802 [self _setMoreHeaders:copy];
3806 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3807 if ((self = [super initWithBook:book forWidth:width ofClass:[CydiaBrowserView class]]) != nil) {
3808 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3810 WebView *webview([webview_ webView]);
3812 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3813 NSString *application = package == nil ? @"Cydia" : [NSString
3814 stringWithFormat:@"Cydia/%@",
3818 if (Product_ != nil)
3819 application = [NSString stringWithFormat:@"%@ Version/%@", application, Product_];
3821 application = [NSString stringWithFormat:@"%@ Mobile/%@", application, Build_];
3823 application = [NSString stringWithFormat:@"%@ Safari/%@", application, Safari_];
3825 [webview setApplicationNameForUserAgent:application];
3831 @protocol ConfirmationViewDelegate
3837 @interface ConfirmationView : CydiaBrowserView {
3838 _transient Database *database_;
3839 UIActionSheet *essential_;
3846 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3850 @implementation ConfirmationView
3857 if (essential_ != nil)
3858 [essential_ release];
3864 [book_ popFromSuperviewAnimated:YES];
3867 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3868 NSString *context([sheet context]);
3870 if ([context isEqualToString:@"remove"]) {
3878 [delegate_ confirm];
3885 } else if ([context isEqualToString:@"unable"]) {
3889 [super alertSheet:sheet buttonClicked:button];
3892 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3893 [super webView:sender didClearWindowObject:window forFrame:frame];
3894 [window setValue:changes_ forKey:@"changes"];
3895 [window setValue:issues_ forKey:@"issues"];
3896 [window setValue:sizes_ forKey:@"sizes"];
3899 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3900 if ((self = [super initWithBook:book]) != nil) {
3901 database_ = database;
3903 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3904 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3905 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3906 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3907 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3911 pkgDepCache::Policy *policy([database_ policy]);
3913 pkgCacheFile &cache([database_ cache]);
3914 NSArray *packages = [database_ packages];
3915 for (Package *package in packages) {
3916 pkgCache::PkgIterator iterator = [package iterator];
3917 pkgDepCache::StateCache &state(cache[iterator]);
3919 NSString *name([package name]);
3921 if (state.NewInstall())
3922 [installing addObject:name];
3923 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3924 [reinstalling addObject:name];
3925 else if (state.Upgrade())
3926 [upgrading addObject:name];
3927 else if (state.Downgrade())
3928 [downgrading addObject:name];
3929 else if (state.Delete()) {
3930 if ([package essential])
3932 [removing addObject:name];
3935 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3936 substrate_ |= DepSubstrate(iterator.CurrentVer());
3941 else if (Advanced_ || true) {
3942 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
3944 essential_ = [[UIActionSheet alloc]
3945 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
3946 buttons:[NSArray arrayWithObjects:
3947 [NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")],
3948 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
3950 defaultButtonIndex:0
3956 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3958 [essential_ setBodyText:UCLocalize("REMOVING_ESSENTIALS_EX")];
3960 essential_ = [[UIActionSheet alloc]
3961 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
3962 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
3963 defaultButtonIndex:0
3968 [essential_ setBodyText:UCLocalize("UNABLE_TO_COMPLY_EX")];
3971 changes_ = [[NSArray alloc] initWithObjects:
3979 issues_ = [database_ issues];
3981 issues_ = [issues_ retain];
3983 sizes_ = [[NSArray alloc] initWithObjects:
3984 SizeString([database_ fetcher].FetchNeeded()),
3985 SizeString([database_ fetcher].PartialPresent()),
3986 SizeString([database_ cache]->UsrSize()),
3989 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3993 - (NSString *) backButtonTitle {
3994 return UCLocalize("CONFIRM");
3997 - (NSString *) leftButtonTitle {
3998 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
4001 - (id) rightButtonTitle {
4002 return issues_ != nil ? nil : [super rightButtonTitle];
4005 - (id) _rightButtonTitle {
4006 #if AlwaysReload || IgnoreInstall
4007 return [super _rightButtonTitle];
4009 return UCLocalize("CONFIRM");
4013 - (void) _leftButtonClicked {
4018 - (void) _rightButtonClicked {
4020 return [super _rightButtonClicked];
4022 if (essential_ != nil)
4023 [essential_ popupAlertAnimated:YES];
4027 [delegate_ confirm];
4035 /* Progress Data {{{ */
4036 @interface ProgressData : NSObject {
4042 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4049 @implementation ProgressData
4051 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4052 if ((self = [super init]) != nil) {
4053 selector_ = selector;
4073 /* Progress View {{{ */
4074 @interface ProgressView : UIView <
4075 ConfigurationDelegate,
4078 _transient Database *database_;
4080 UIView *background_;
4081 UITransitionView *transition_;
4083 UINavigationBar *navbar_;
4084 UIProgressBar *progress_;
4085 UITextView *output_;
4086 UITextLabel *status_;
4087 UIPushButton *close_;
4090 SHA1SumValue springlist_;
4091 SHA1SumValue notifyconf_;
4092 SHA1SumValue sandplate_;
4095 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
4097 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4098 - (void) setContentView:(UIView *)view;
4101 - (void) _retachThread;
4102 - (void) _detachNewThreadData:(ProgressData *)data;
4103 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4109 @protocol ProgressViewDelegate
4110 - (void) progressViewIsComplete:(ProgressView *)sender;
4113 @implementation ProgressView
4116 [transition_ setDelegate:nil];
4117 [navbar_ setDelegate:nil];
4120 if (background_ != nil)
4121 [background_ release];
4122 [transition_ release];
4125 [progress_ release];
4132 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
4133 if (bootstrap_ && from == overlay_ && to == view_)
4137 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4138 if ((self = [super initWithFrame:frame]) != nil) {
4139 database_ = database;
4140 delegate_ = delegate;
4142 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4143 [transition_ setDelegate:self];
4145 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4148 [overlay_ setBackgroundColor:[UIColor blackColor]];
4150 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4151 [background_ setBackgroundColor:[UIColor blackColor]];
4152 [self addSubview:background_];
4155 [self addSubview:transition_];
4157 CGSize navsize = [UINavigationBar defaultSize];
4158 CGRect navrect = {{0, 0}, navsize};
4160 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4161 [overlay_ addSubview:navbar_];
4163 [navbar_ setBarStyle:1];
4164 [navbar_ setDelegate:self];
4166 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4167 [navbar_ pushNavigationItem:navitem];
4169 CGRect bounds = [overlay_ bounds];
4170 CGSize prgsize = [UIProgressBar defaultSize];
4173 (bounds.size.width - prgsize.width) / 2,
4174 bounds.size.height - prgsize.height - 20
4177 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4178 [progress_ setStyle:0];
4180 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4182 bounds.size.height - prgsize.height - 50,
4183 bounds.size.width - 20,
4187 [status_ setColor:[UIColor whiteColor]];
4188 [status_ setBackgroundColor:[UIColor clearColor]];
4190 [status_ setCentersHorizontally:YES];
4191 //[status_ setFont:font];
4194 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4196 navrect.size.height + 20,
4197 bounds.size.width - 20,
4198 bounds.size.height - navsize.height - 62 - navrect.size.height
4202 //[output_ setTextFont:@"Courier New"];
4203 [output_ setTextSize:12];
4205 [output_ setTextColor:[UIColor whiteColor]];
4206 [output_ setBackgroundColor:[UIColor clearColor]];
4208 [output_ setMarginTop:0];
4209 [output_ setAllowsRubberBanding:YES];
4210 [output_ setEditable:NO];
4212 [overlay_ addSubview:output_];
4214 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4216 bounds.size.height - prgsize.height - 50,
4217 bounds.size.width - 20,
4221 [close_ setAutosizesToFit:NO];
4222 [close_ setDrawsShadow:YES];
4223 [close_ setStretchBackground:YES];
4224 [close_ setEnabled:YES];
4226 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4227 [close_ setTitleFont:bold];
4229 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4230 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4231 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4235 - (void) setContentView:(UIView *)view {
4236 view_ = [view retain];
4239 - (void) resetView {
4240 [transition_ transition:6 toView:view_];
4243 - (void) _checkError {
4244 if (_error->PendingError()) {
4246 if (!_error->PopMessage(error))
4249 UIActionSheet *sheet = [[[UIActionSheet alloc]
4250 initWithTitle:UCLocalize("ERROR")
4251 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4252 defaultButtonIndex:0
4257 [sheet setBodyText:[NSString stringWithUTF8String:error.c_str()]];
4258 [sheet popupAlertAnimated:YES];
4263 [delegate_ progressViewIsComplete:self];
4267 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4270 MMap mmap(file, MMap::ReadOnly);
4272 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4273 if (!(notifyconf_ == sha1.Result()))
4280 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4283 MMap mmap(file, MMap::ReadOnly);
4285 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4286 if (!(springlist_ == sha1.Result()))
4292 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4293 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4294 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4295 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4296 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4299 #define ListCache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4300 #define IconCache_ "/User/Library/Caches/com.apple.springboard-imagecache-icons.plist"
4304 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ListCache_]) {
4305 [cache autorelease];
4307 NSFileManager *manager = [NSFileManager defaultManager];
4308 NSError *error = nil;
4310 id system = [cache objectForKey:@"System"];
4315 if (stat(ListCache_, &info) == -1)
4318 [system removeAllObjects];
4320 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4321 for (NSString *app in apps)
4322 if ([app hasSuffix:@".app"]) {
4323 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4324 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4325 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4327 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4328 [info setObject:path forKey:@"Path"];
4329 [info setObject:@"System" forKey:@"ApplicationType"];
4330 [system addInfoDictionary:info];
4336 [cache writeToFile:@ListCache_ atomically:YES];
4338 if (chown(ListCache_, info.st_uid, info.st_gid) == -1)
4340 if (chmod(ListCache_, info.st_mode) == -1)
4344 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4347 notify_post("com.apple.mobile.application_installed");
4349 [delegate_ setStatusBarShowsProgress:NO];
4352 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4353 NSString *context([sheet context]);
4355 if ([context isEqualToString:@"error"])
4357 else if ([context isEqualToString:@"_error"]) {
4360 } else if ([context isEqualToString:@"conffile"]) {
4361 FILE *input = [database_ input];
4365 fprintf(input, "N\n");
4369 fprintf(input, "Y\n");
4380 - (void) closeButtonPushed {
4389 [delegate_ suspendWithAnimation:YES];
4393 system("launchctl stop com.apple.SpringBoard");
4397 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4406 - (void) _retachThread {
4407 UINavigationItem *item = [navbar_ topItem];
4408 [item setTitle:UCLocalize("COMPLETE")];
4410 [overlay_ addSubview:close_];
4411 [progress_ removeFromSuperview];
4412 [status_ removeFromSuperview];
4417 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4418 [[data target] performSelector:[data selector] withObject:[data object]];
4421 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4424 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4425 UINavigationItem *item = [navbar_ topItem];
4426 [item setTitle:title];
4428 [status_ setText:nil];
4429 [output_ setText:@""];
4430 [progress_ setProgress:0];
4432 [close_ removeFromSuperview];
4433 [overlay_ addSubview:progress_];
4434 [overlay_ addSubview:status_];
4436 [delegate_ setStatusBarShowsProgress:YES];
4441 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4444 MMap mmap(file, MMap::ReadOnly);
4446 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4447 notifyconf_ = sha1.Result();
4453 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4456 MMap mmap(file, MMap::ReadOnly);
4458 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4459 springlist_ = sha1.Result();
4463 [transition_ transition:6 toView:overlay_];
4466 detachNewThreadSelector:@selector(_detachNewThreadData:)
4468 withObject:[[ProgressData alloc]
4469 initWithSelector:selector
4476 - (void) repairWithSelector:(SEL)selector {
4478 detachNewThreadSelector:selector
4481 title:UCLocalize("REPAIRING")
4485 - (void) setConfigurationData:(NSString *)data {
4487 performSelectorOnMainThread:@selector(_setConfigurationData:)
4493 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4494 Package *package = id == nil ? nil : [database_ packageWithName:id];
4496 UIActionSheet *sheet = [[[UIActionSheet alloc]
4497 initWithTitle:(package == nil ? id : [package name])
4498 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4499 defaultButtonIndex:0
4504 [sheet setBodyText:error];
4505 [sheet popupAlertAnimated:YES];
4508 - (void) setProgressTitle:(NSString *)title {
4510 performSelectorOnMainThread:@selector(_setProgressTitle:)
4516 - (void) setProgressPercent:(float)percent {
4518 performSelectorOnMainThread:@selector(_setProgressPercent:)
4519 withObject:[NSNumber numberWithFloat:percent]
4524 - (void) startProgress {
4527 - (void) addProgressOutput:(NSString *)output {
4529 performSelectorOnMainThread:@selector(_addProgressOutput:)
4535 - (bool) isCancelling:(size_t)received {
4539 - (void) _setConfigurationData:(NSString *)data {
4540 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4542 _assert(conffile_r(data));
4544 NSString *ofile = conffile_r[1];
4545 //NSString *nfile = conffile_r[2];
4547 UIActionSheet *sheet = [[[UIActionSheet alloc]
4548 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4549 buttons:[NSArray arrayWithObjects:
4550 UCLocalize("KEEP_OLD_COPY"),
4551 UCLocalize("ACCEPT_NEW_COPY"),
4552 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4554 defaultButtonIndex:0
4559 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4560 [sheet popupAlertAnimated:YES];
4563 - (void) _setProgressTitle:(NSString *)title {
4564 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4565 for (size_t i(0), e([words count]); i != e; ++i) {
4566 NSString *word([words objectAtIndex:i]);
4567 if (Package *package = [database_ packageWithName:word])
4568 [words replaceObjectAtIndex:i withObject:[package name]];
4571 [status_ setText:[words componentsJoinedByString:@" "]];
4574 - (void) _setProgressPercent:(NSNumber *)percent {
4575 [progress_ setProgress:[percent floatValue]];
4578 - (void) _addProgressOutput:(NSString *)output {
4579 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4580 CGSize size = [output_ contentSize];
4581 CGRect rect = {{0, size.height}, {size.width, 0}};
4582 [output_ scrollRectToVisible:rect animated:YES];
4585 - (BOOL) isRunning {
4592 /* Package Cell {{{ */
4593 @interface ContentView : UIView {
4594 _transient id delegate_;
4599 @interface PackageCell : UITableViewCell {
4602 NSString *description_;
4608 ContentView *content_;
4613 - (PackageCell *) init;
4614 - (void) setPackage:(Package *)package;
4616 + (int) heightForPackage:(Package *)package;
4617 - (void) drawContentRect:(CGRect)rect;
4621 @implementation ContentView
4623 - (id) initWithFrame:(CGRect)frame {
4624 if ((self = [super initWithFrame:frame]) != nil) {
4628 - (void) setDelegate:(id)delegate {
4629 delegate_ = delegate;
4632 - (void) drawRect:(CGRect)rect {
4633 [super drawRect:rect];
4634 [delegate_ drawContentRect:rect];
4639 @implementation PackageCell
4641 - (void) clearPackage {
4652 if (description_ != nil) {
4653 [description_ release];
4657 if (source_ != nil) {
4662 if (badge_ != nil) {
4672 [self clearPackage];
4679 return faded_ ? [self selectionPercent] : fade_;
4682 - (PackageCell *) init {
4683 CGRect frame(CGRectMake(0, 0, 320, 74));
4684 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4685 UIView *content([self contentView]);
4686 CGRect bounds([content bounds]);
4687 content_ = [[ContentView alloc] initWithFrame:bounds];
4688 [content_ setDelegate:self];
4689 [content_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
4690 [content_ setOpaque:YES];
4691 [content addSubview:content_];
4692 if ([self respondsToSelector:@selector(selectionPercent)])
4697 - (void) _setBackgroundColor {
4699 if (NSString *mode = [package_ mode]) {
4700 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4701 color = remove ? RemovingColor_ : InstallingColor_;
4703 color = [UIColor whiteColor];
4705 [content_ setBackgroundColor:color];
4706 [self setNeedsDisplay];
4709 - (void) setPackage:(Package *)package {
4710 [self clearPackage];
4713 Source *source = [package source];
4715 icon_ = [[package icon] retain];
4716 name_ = [[package name] retain];
4717 description_ = [[package shortDescription] retain];
4718 commercial_ = [package isCommercial];
4720 package_ = [package retain];
4722 NSString *label = nil;
4723 bool trusted = false;
4725 if (source != nil) {
4726 label = [source label];
4727 trusted = [source trusted];
4728 } else if ([[package id] isEqualToString:@"firmware"])
4729 label = UCLocalize("APPLE");
4731 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4733 NSString *from(label);
4735 NSString *section = [package simpleSection];
4736 if (section != nil && ![section isEqualToString:label]) {
4737 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4738 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4741 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4742 source_ = [from retain];
4744 if (NSString *purpose = [package primaryPurpose])
4745 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4746 badge_ = [badge_ retain];
4748 [self _setBackgroundColor];
4749 [content_ setNeedsDisplay];
4752 - (void) drawContentRect:(CGRect)rect {
4753 bool selected([self isSelected]);
4756 CGContextRef context(UIGraphicsGetCurrentContext());
4757 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4758 CGContextFillRect(context, rect);
4763 rect.size = [icon_ size];
4765 rect.size.width /= 2;
4766 rect.size.height /= 2;
4768 rect.origin.x = 25 - rect.size.width / 2;
4769 rect.origin.y = 25 - rect.size.height / 2;
4771 [icon_ drawInRect:rect];
4774 if (badge_ != nil) {
4775 CGSize size = [badge_ size];
4777 [badge_ drawAtPoint:CGPointMake(
4778 36 - size.width / 2,
4779 36 - size.height / 2
4787 UISetColor(commercial_ ? Purple_ : Black_);
4788 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4789 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4792 UISetColor(commercial_ ? Purplish_ : Gray_);
4793 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4796 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4797 //[self _setBackgroundColor];
4798 [super setSelected:selected animated:fade];
4799 [content_ setNeedsDisplay];
4802 + (int) heightForPackage:(Package *)package {
4808 /* Section Cell {{{ */
4809 @interface SectionCell : UISimpleTableCell {
4814 _UISwitchSlider *switch_;
4819 - (void) setSection:(Section *)section editing:(BOOL)editing;
4823 @implementation SectionCell
4825 - (void) clearSection {
4826 if (section_ != nil) {
4836 if (count_ != nil) {
4843 [self clearSection];
4850 if ((self = [super init]) != nil) {
4851 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4853 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4854 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventTouchUpInside];
4858 - (void) onSwitch:(id)sender {
4859 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4860 if (metadata == nil) {
4861 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4862 [Sections_ setObject:metadata forKey:section_];
4866 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4869 - (void) setSection:(Section *)section editing:(BOOL)editing {
4870 if (editing != editing_) {
4872 [switch_ removeFromSuperview];
4874 [self addSubview:switch_];
4878 [self clearSection];
4880 if (section == nil) {
4881 name_ = [UCLocalize("ALL_PACKAGES") retain];
4884 section_ = [section localized];
4885 if (section_ != nil)
4886 section_ = [section_ retain];
4887 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4888 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4891 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4895 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4896 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4903 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4905 CGSize size = [count_ sizeWithFont:Font14_];
4909 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4911 [super drawContentInRect:rect selected:selected];
4917 /* File Table {{{ */
4918 @interface FileTable : RVPage {
4919 _transient Database *database_;
4922 NSMutableArray *files_;
4926 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4927 - (void) setPackage:(Package *)package;
4931 @implementation FileTable
4934 if (package_ != nil)
4943 - (int) numberOfRowsInTable:(UITable *)table {
4944 return files_ == nil ? 0 : [files_ count];
4947 - (float) table:(UITable *)table heightForRow:(int)row {
4951 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4952 if (reusing == nil) {
4953 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4954 UIFont *font = [UIFont systemFontOfSize:16];
4955 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4957 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4961 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4965 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4966 if ((self = [super initWithBook:book]) != nil) {
4967 database_ = database;
4969 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4971 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4972 [self addSubview:list_];
4974 UITableColumn *column = [[[UITableColumn alloc]
4975 initWithTitle:UCLocalize("NAME")
4977 width:[self frame].size.width
4980 [list_ setDataSource:self];
4981 [list_ setSeparatorStyle:1];
4982 [list_ addTableColumn:column];
4983 [list_ setDelegate:self];
4984 [list_ setReusesTableCells:YES];
4988 - (void) setPackage:(Package *)package {
4989 if (package_ != nil) {
4990 [package_ autorelease];
4999 [files_ removeAllObjects];
5001 if (package != nil) {
5002 package_ = [package retain];
5003 name_ = [[package id] retain];
5005 if (NSArray *files = [package files])
5006 [files_ addObjectsFromArray:files];
5008 if ([files_ count] != 0) {
5009 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5010 [files_ removeObjectAtIndex:0];
5011 [files_ sortUsingSelector:@selector(compareByPath:)];
5013 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5014 [stack addObject:@"/"];
5016 for (int i(0), e([files_ count]); i != e; ++i) {
5017 NSString *file = [files_ objectAtIndex:i];
5018 while (![file hasPrefix:[stack lastObject]])
5019 [stack removeLastObject];
5020 NSString *directory = [stack lastObject];
5021 [stack addObject:[file stringByAppendingString:@"/"]];
5022 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5023 ([stack count] - 2) * 3, "",
5024 [file substringFromIndex:[directory length]]
5033 - (void) resetViewAnimated:(BOOL)animated {
5034 [list_ resetViewAnimated:animated];
5037 - (void) reloadData {
5038 [self setPackage:[database_ packageWithName:name_]];
5039 [self reloadButtons];
5042 - (NSString *) title {
5043 return UCLocalize("INSTALLED_FILES");
5046 - (NSString *) backButtonTitle {
5047 return UCLocalize("FILES");
5052 /* Package View {{{ */
5053 @interface PackageView : CydiaBrowserView {
5054 _transient Database *database_;
5058 NSMutableArray *buttons_;
5061 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5062 - (void) setPackage:(Package *)package;
5066 @implementation PackageView
5069 if (package_ != nil)
5078 if ([self retainCount] == 1)
5079 [delegate_ setPackageView:self];
5083 /* XXX: this is not safe at all... localization of /fail/ */
5084 - (void) _clickButtonWithName:(NSString *)name {
5085 if ([name isEqualToString:UCLocalize("CLEAR")])
5086 [delegate_ clearPackage:package_];
5087 else if ([name isEqualToString:UCLocalize("INSTALL")])
5088 [delegate_ installPackage:package_];
5089 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5090 [delegate_ installPackage:package_];
5091 else if ([name isEqualToString:UCLocalize("REMOVE")])
5092 [delegate_ removePackage:package_];
5093 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5094 [delegate_ installPackage:package_];
5095 else _assert(false);
5098 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5099 NSString *context([sheet context]);
5101 if ([context isEqualToString:@"modify"]) {
5102 int count = [buttons_ count];
5103 _assert(count != 0);
5104 _assert(button <= count + 1);
5106 if (count != button - 1)
5107 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
5111 [super alertSheet:sheet buttonClicked:button];
5114 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5115 return [super webView:sender didFinishLoadForFrame:frame];
5118 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5119 [super webView:sender didClearWindowObject:window forFrame:frame];
5120 [window setValue:package_ forKey:@"package"];
5123 - (bool) _allowJavaScriptPanel {
5128 - (void) __rightButtonClicked {
5129 int count = [buttons_ count];
5130 _assert(count != 0);
5133 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5135 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
5136 [buttons addObjectsFromArray:buttons_];
5137 [buttons addObject:UCLocalize("CANCEL")];
5139 [delegate_ slideUp:[[[UIActionSheet alloc]
5142 defaultButtonIndex:([buttons count] - 1)
5149 - (void) _rightButtonClicked {
5151 [super _rightButtonClicked];
5153 [self __rightButtonClicked];
5157 - (id) _rightButtonTitle {
5158 int count = [buttons_ count];
5159 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5162 - (NSString *) backButtonTitle {
5166 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5167 if ((self = [super initWithBook:book]) != nil) {
5168 database_ = database;
5169 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5170 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5174 - (void) setPackage:(Package *)package {
5175 if (package_ != nil) {
5176 [package_ autorelease];
5185 [buttons_ removeAllObjects];
5187 if (package != nil) {
5190 package_ = [package retain];
5191 name_ = [[package id] retain];
5192 commercial_ = [package isCommercial];
5194 if ([package_ mode] != nil)
5195 [buttons_ addObject:UCLocalize("CLEAR")];
5196 if ([package_ source] == nil);
5197 else if ([package_ upgradableAndEssential:NO])
5198 [buttons_ addObject:UCLocalize("UPGRADE")];
5199 else if ([package_ uninstalled])
5200 [buttons_ addObject:UCLocalize("INSTALL")];
5202 [buttons_ addObject:UCLocalize("REINSTALL")];
5203 if (![package_ uninstalled])
5204 [buttons_ addObject:UCLocalize("REMOVE")];
5206 if (special_ != NULL) {
5207 CGRect frame([webview_ frame]);
5208 frame.size.width = 320;
5209 frame.size.height = 0;
5210 [webview_ setFrame:frame];
5212 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5215 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5217 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5219 [self setFinishHook:nil];
5220 [self setPopupHook:nil];
5223 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5224 [super callFunction:special_];
5228 [self reloadButtons];
5231 - (bool) isLoading {
5232 return commercial_ ? [super isLoading] : false;
5235 - (void) reloadData {
5236 [self setPackage:[database_ packageWithName:name_]];
5241 /* Package Table {{{ */
5242 @interface PackageTable : RVPage {
5243 _transient Database *database_;
5245 NSMutableArray *packages_;
5246 NSMutableArray *sections_;
5248 NSMutableArray *index_;
5249 NSMutableDictionary *indices_;
5252 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5254 - (void) setDelegate:(id)delegate;
5256 - (void) reloadData;
5257 - (void) resetCursor;
5259 - (UITableView *) list;
5261 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5265 @implementation PackageTable
5268 [list_ setDataSource:nil];
5271 [packages_ release];
5272 [sections_ release];
5279 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5280 NSInteger count([sections_ count]);
5281 return count == 0 ? 1 : count;
5284 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5285 if ([sections_ count] == 0)
5287 return [[sections_ objectAtIndex:section] name];
5290 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5291 if ([sections_ count] == 0)
5293 return [[sections_ objectAtIndex:section] count];
5296 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5297 Section *section([sections_ objectAtIndex:[path section]]);
5298 NSInteger row([path row]);
5299 Package *package([packages_ objectAtIndex:([section row] + row)]);
5303 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5304 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5306 cell = [[[PackageCell alloc] init] autorelease];
5307 [cell setPackage:[self packageAtIndexPath:path]];
5311 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5313 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5316 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5317 Package *package([self packageAtIndexPath:path]);
5318 package = [database_ packageWithName:[package id]];
5319 PackageView *view([delegate_ packageView]);
5320 [view setPackage:package];
5321 [view setDelegate:delegate_];
5322 [book_ pushPage:view];
5326 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5327 return [packages_ count] > 20 ? index_ : nil;
5330 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5334 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5335 if ((self = [super initWithBook:book]) != nil) {
5336 database_ = database;
5337 title_ = [title retain];
5339 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5340 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5342 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5343 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5345 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5346 [list_ setDataSource:self];
5347 [list_ setDelegate:self];
5349 [self addSubview:list_];
5351 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5352 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5356 - (void) setDelegate:(id)delegate {
5357 delegate_ = delegate;
5360 - (bool) hasPackage:(Package *)package {
5364 - (void) reloadData {
5365 NSArray *packages = [database_ packages];
5367 [packages_ removeAllObjects];
5368 [sections_ removeAllObjects];
5370 _profile(PackageTable$reloadData$Filter)
5371 for (Package *package in packages)
5372 if ([self hasPackage:package])
5373 [packages_ addObject:package];
5376 [index_ removeAllObjects];
5377 [indices_ removeAllObjects];
5379 Section *section = nil;
5381 _profile(PackageTable$reloadData$Section)
5382 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5386 _profile(PackageTable$reloadData$Section$Package)
5387 package = [packages_ objectAtIndex:offset];
5388 index = [package index];
5391 if (section == nil || [section index] != index) {
5392 _profile(PackageTable$reloadData$Section$Allocate)
5393 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5396 [index_ addObject:[section name]];
5397 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5399 _profile(PackageTable$reloadData$Section$Add)
5400 [sections_ addObject:section];
5404 [section addToCount];
5408 _profile(PackageTable$reloadData$List)
5413 - (NSString *) title {
5417 - (void) resetViewAnimated:(BOOL)animated {
5418 [list_ resetViewAnimated:animated];
5421 - (void) resetCursor {
5422 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5425 - (UITableView *) list {
5429 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5430 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5435 /* Filtered Package Table {{{ */
5436 @interface FilteredPackageTable : PackageTable {
5442 - (void) setObject:(id)object;
5444 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5448 @implementation FilteredPackageTable
5456 - (void) setObject:(id)object {
5462 object_ = [object retain];
5465 - (bool) hasPackage:(Package *)package {
5466 _profile(FilteredPackageTable$hasPackage)
5467 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5471 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5472 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5474 object_ = object == nil ? nil : [object retain];
5476 /* XXX: this is an unsafe optimization of doomy hell */
5477 Method method = class_getInstanceMethod([Package class], filter);
5478 _assert(method != NULL);
5479 imp_ = method_getImplementation(method);
5480 _assert(imp_ != NULL);
5489 /* Add Source View {{{ */
5490 @interface AddSourceView : RVPage {
5491 _transient Database *database_;
5494 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5498 @implementation AddSourceView
5500 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5501 if ((self = [super initWithBook:book]) != nil) {
5502 database_ = database;
5508 /* Source Cell {{{ */
5509 @interface SourceCell : UITableCell {
5512 NSString *description_;
5518 - (SourceCell *) initWithSource:(Source *)source;
5522 @implementation SourceCell
5527 [description_ release];
5532 - (SourceCell *) initWithSource:(Source *)source {
5533 if ((self = [super init]) != nil) {
5535 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5537 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5538 icon_ = [icon_ retain];
5540 origin_ = [[source name] retain];
5541 label_ = [[source uri] retain];
5542 description_ = [[source description] retain];
5546 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5548 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5555 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5559 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5563 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5565 [super drawContentInRect:rect selected:selected];
5570 /* Source Table {{{ */
5571 @interface SourceTable : RVPage {
5572 _transient Database *database_;
5573 UISectionList *list_;
5574 NSMutableArray *sources_;
5575 UIActionSheet *alert_;
5579 UIProgressHUD *hud_;
5582 //NSURLConnection *installer_;
5583 NSURLConnection *trivial_bz2_;
5584 NSURLConnection *trivial_gz_;
5585 //NSURLConnection *automatic_;
5590 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5594 @implementation SourceTable
5596 - (void) _deallocConnection:(NSURLConnection *)connection {
5597 if (connection != nil) {
5598 [connection cancel];
5599 //[connection setDelegate:nil];
5600 [connection release];
5605 [[list_ table] setDelegate:nil];
5606 [list_ setDataSource:nil];
5615 //[self _deallocConnection:installer_];
5616 [self _deallocConnection:trivial_gz_];
5617 [self _deallocConnection:trivial_bz2_];
5618 //[self _deallocConnection:automatic_];
5625 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5626 return offset_ == 0 ? 1 : 2;
5629 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5630 switch (section + (offset_ == 0 ? 1 : 0)) {
5631 case 0: return UCLocalize("ENTERED_BY_USER");
5632 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5640 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5641 switch (section + (offset_ == 0 ? 1 : 0)) {
5643 case 1: return offset_;
5651 - (int) numberOfRowsInTable:(UITable *)table {
5652 return [sources_ count];
5655 - (float) table:(UITable *)table heightForRow:(int)row {
5656 Source *source = [sources_ objectAtIndex:row];
5657 return [source description] == nil ? 56 : 73;
5660 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5661 Source *source = [sources_ objectAtIndex:row];
5662 // XXX: weird warning, stupid selectors ;P
5663 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5666 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5670 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5674 - (void) tableRowSelected:(NSNotification*)notification {
5675 UITable *table([list_ table]);
5676 int row([table selectedRow]);
5680 Source *source = [sources_ objectAtIndex:row];
5682 PackageTable *packages = [[[FilteredPackageTable alloc]
5685 title:[source label]
5686 filter:@selector(isVisibleInSource:)
5690 [packages setDelegate:delegate_];
5692 [book_ pushPage:packages];
5695 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5696 Source *source = [sources_ objectAtIndex:row];
5697 return [source record] != nil;
5700 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5701 [[list_ table] setDeleteConfirmationRow:row];
5704 - (void) table:(UITable *)table deleteRow:(int)row {
5705 Source *source = [sources_ objectAtIndex:row];
5706 [Sources_ removeObjectForKey:[source key]];
5707 [delegate_ syncData];
5711 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5714 @"./", @"Distribution",
5715 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5717 [delegate_ syncData];
5720 - (NSString *) getWarning {
5721 NSString *href(href_);
5722 NSRange colon([href rangeOfString:@"://"]);
5723 if (colon.location != NSNotFound)
5724 href = [href substringFromIndex:(colon.location + 3)];
5725 href = [href stringByAddingPercentEscapes];
5726 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5727 href = [href stringByCachingURLWithCurrentCDN];
5729 NSURL *url([NSURL URLWithString:href]);
5731 NSStringEncoding encoding;
5732 NSError *error(nil);
5734 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5735 return [warning length] == 0 ? nil : warning;
5739 - (void) _endConnection:(NSURLConnection *)connection {
5740 NSURLConnection **field = NULL;
5741 if (connection == trivial_bz2_)
5742 field = &trivial_bz2_;
5743 else if (connection == trivial_gz_)
5744 field = &trivial_gz_;
5745 _assert(field != NULL);
5746 [connection release];
5750 trivial_bz2_ == nil &&
5756 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5759 UIActionSheet *sheet = [[[UIActionSheet alloc]
5760 initWithTitle:UCLocalize("SOURCE_WARNING")
5761 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5762 defaultButtonIndex:0
5767 [sheet setNumberOfRows:1];
5769 [sheet setBodyText:warning];
5770 [sheet popupAlertAnimated:YES];
5773 } else if (error_ != nil) {
5774 UIActionSheet *sheet = [[[UIActionSheet alloc]
5775 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5776 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5777 defaultButtonIndex:0
5782 [sheet setBodyText:[error_ localizedDescription]];
5783 [sheet popupAlertAnimated:YES];
5785 UIActionSheet *sheet = [[[UIActionSheet alloc]
5786 initWithTitle:UCLocalize("NOT_REPOSITORY")
5787 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5788 defaultButtonIndex:0
5793 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5794 [sheet popupAlertAnimated:YES];
5797 [delegate_ setStatusBarShowsProgress:NO];
5798 [delegate_ removeProgressHUD:hud_];
5808 if (error_ != nil) {
5815 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5816 switch ([response statusCode]) {
5822 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5823 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5825 error_ = [error retain];
5826 [self _endConnection:connection];
5829 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5830 [self _endConnection:connection];
5833 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5834 NSMutableURLRequest *request = [NSMutableURLRequest
5835 requestWithURL:[NSURL URLWithString:href]
5836 cachePolicy:NSURLRequestUseProtocolCachePolicy
5837 timeoutInterval:20.0
5840 [request setHTTPMethod:method];
5842 if (Machine_ != NULL)
5843 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5844 if (UniqueID_ != nil)
5845 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5848 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5850 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5853 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5854 NSString *context([sheet context]);
5856 if ([context isEqualToString:@"source"]) {
5859 NSString *href = [[sheet textField] text];
5861 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5863 if (![href hasSuffix:@"/"])
5864 href_ = [href stringByAppendingString:@"/"];
5867 href_ = [href_ retain];
5869 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
5870 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5871 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5872 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5876 hud_ = [[delegate_ addProgressHUD] retain];
5877 [hud_ setText:UCLocalize("VERIFYING_URL")];
5888 } else if ([context isEqualToString:@"trivial"])
5890 else if ([context isEqualToString:@"urlerror"])
5892 else if ([context isEqualToString:@"warning"]) {
5912 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5913 if ((self = [super initWithBook:book]) != nil) {
5914 database_ = database;
5915 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5917 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5918 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5919 [list_ setShouldHideHeaderInShortLists:NO];
5921 [self addSubview:list_];
5922 [list_ setDataSource:self];
5924 UITableColumn *column = [[UITableColumn alloc]
5925 initWithTitle:UCLocalize("NAME")
5927 width:[self frame].size.width
5930 UITable *table = [list_ table];
5931 [table setSeparatorStyle:1];
5932 [table addTableColumn:column];
5933 [table setDelegate:self];
5937 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5938 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5942 - (void) reloadData {
5944 _assert(list.ReadMainList());
5946 [sources_ removeAllObjects];
5947 [sources_ addObjectsFromArray:[database_ sources]];
5949 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5952 int count = [sources_ count];
5953 for (offset_ = 0; offset_ != count; ++offset_) {
5954 Source *source = [sources_ objectAtIndex:offset_];
5955 if ([source record] == nil)
5962 - (void) resetViewAnimated:(BOOL)animated {
5963 [list_ resetViewAnimated:animated];
5966 - (void) _leftButtonClicked {
5967 /*[book_ pushPage:[[[AddSourceView alloc]
5972 UIActionSheet *sheet = [[[UIActionSheet alloc]
5973 initWithTitle:UCLocalize("ENTER_APT_URL")
5974 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
5975 defaultButtonIndex:0
5980 [sheet setNumberOfRows:1];
5982 [sheet addTextFieldWithValue:@"http://" label:@""];
5984 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5985 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5986 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5987 [traits setKeyboardType:UIKeyboardTypeURL];
5988 // XXX: UIReturnKeyDone
5989 [traits setReturnKeyType:UIReturnKeyNext];
5991 [sheet popupAlertAnimated:YES];
5994 - (void) _rightButtonClicked {
5995 UITable *table = [list_ table];
5996 BOOL editing = [table isRowDeletionEnabled];
5997 [table enableRowDeletion:!editing animated:YES];
5998 [book_ reloadButtonsForPage:self];
6001 - (NSString *) title {
6002 return UCLocalize("SOURCES");
6005 - (NSString *) leftButtonTitle {
6006 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
6009 - (id) rightButtonTitle {
6010 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
6013 - (UINavigationButtonStyle) rightButtonStyle {
6014 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6020 /* Installed View {{{ */
6021 @interface InstalledView : RVPage {
6022 _transient Database *database_;
6023 FilteredPackageTable *packages_;
6027 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6031 @implementation InstalledView
6034 [packages_ release];
6038 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6039 if ((self = [super initWithBook:book]) != nil) {
6040 database_ = database;
6042 packages_ = [[FilteredPackageTable alloc]
6046 filter:@selector(isInstalledAndVisible:)
6047 with:[NSNumber numberWithBool:YES]
6050 [self addSubview:packages_];
6052 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6053 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6057 - (void) resetViewAnimated:(BOOL)animated {
6058 [packages_ resetViewAnimated:animated];
6061 - (void) reloadData {
6062 [packages_ reloadData];
6065 - (void) _rightButtonClicked {
6066 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6067 [packages_ reloadData];
6069 [book_ reloadButtonsForPage:self];
6072 - (NSString *) title {
6073 return UCLocalize("INSTALLED");
6076 - (NSString *) backButtonTitle {
6077 return UCLocalize("PACKAGES");
6080 - (id) rightButtonTitle {
6081 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6084 - (UINavigationButtonStyle) rightButtonStyle {
6085 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6088 - (void) setDelegate:(id)delegate {
6089 [super setDelegate:delegate];
6090 [packages_ setDelegate:delegate];
6097 @interface HomeView : CydiaBrowserView {
6102 @implementation HomeView
6104 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6105 NSString *context([sheet context]);
6107 if ([context isEqualToString:@"about"])
6110 [super alertSheet:sheet buttonClicked:button];
6113 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6114 [super _setMoreHeaders:request];
6116 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6119 - (void) _leftButtonClicked {
6120 UIActionSheet *sheet = [[[UIActionSheet alloc]
6121 initWithTitle:UCLocalize("ABOUT_CYDIA")
6122 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6123 defaultButtonIndex:0
6129 @"Copyright (C) 2008-2009\n"
6130 "Jay Freeman (saurik)\n"
6131 "saurik@saurik.com\n"
6132 "http://www.saurik.com/\n"
6135 "http://www.theokorigroup.com/\n"
6137 "College of Creative Studies,\n"
6138 "University of California,\n"
6140 "http://www.ccs.ucsb.edu/"
6143 [sheet popupAlertAnimated:YES];
6146 - (NSString *) leftButtonTitle {
6147 return UCLocalize("ABOUT");
6152 /* Manage View {{{ */
6153 @interface ManageView : CydiaBrowserView {
6158 @implementation ManageView
6160 - (NSString *) title {
6161 return UCLocalize("MANAGE");
6164 - (void) _leftButtonClicked {
6165 [delegate_ askForSettings];
6168 - (NSString *) leftButtonTitle {
6169 return UCLocalize("SETTINGS");
6173 - (id) _rightButtonTitle {
6174 return Queuing_ ? UCLocalize("QUEUE") : nil;
6177 - (UINavigationButtonStyle) rightButtonStyle {
6178 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6181 - (void) _rightButtonClicked {
6186 - (bool) isLoading {
6193 /* Cydia Book {{{ */
6194 @interface CYBook : RVBook <
6197 _transient Database *database_;
6198 UINavigationBar *overlay_;
6199 UINavigationBar *underlay_;
6200 UIProgressIndicator *indicator_;
6201 UITextLabel *prompt_;
6202 UIProgressBar *progress_;
6203 UINavigationButton *cancel_;
6207 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6213 @implementation CYBook
6217 [indicator_ release];
6219 [progress_ release];
6224 - (NSString *) getTitleForPage:(RVPage *)page {
6225 return [super getTitleForPage:page];
6233 [UIView beginAnimations:nil context:NULL];
6235 CGRect ovrframe = [overlay_ frame];
6236 ovrframe.origin.y = 0;
6237 [overlay_ setFrame:ovrframe];
6239 CGRect barframe = [navbar_ frame];
6240 barframe.origin.y += ovrframe.size.height;
6241 [navbar_ setFrame:barframe];
6243 CGRect trnframe = [transition_ frame];
6244 trnframe.origin.y += ovrframe.size.height;
6245 trnframe.size.height -= ovrframe.size.height;
6246 [transition_ setFrame:trnframe];
6248 [UIView endAnimations];
6250 [indicator_ startAnimation];
6251 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6252 [progress_ setProgress:0];
6255 [overlay_ addSubview:cancel_];
6258 detachNewThreadSelector:@selector(_update)
6264 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6265 NSString *context([sheet context]);
6267 if ([context isEqualToString:@"refresh"])
6271 - (void) _update_:(NSString *)error {
6274 [indicator_ stopAnimation];
6276 [UIView beginAnimations:nil context:NULL];
6278 CGRect ovrframe = [overlay_ frame];
6279 ovrframe.origin.y = -ovrframe.size.height;
6280 [overlay_ setFrame:ovrframe];
6282 CGRect barframe = [navbar_ frame];
6283 barframe.origin.y -= ovrframe.size.height;
6284 [navbar_ setFrame:barframe];
6286 CGRect trnframe = [transition_ frame];
6287 trnframe.origin.y -= ovrframe.size.height;
6288 trnframe.size.height += ovrframe.size.height;
6289 [transition_ setFrame:trnframe];
6291 [UIView commitAnimations];
6294 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6296 UIActionSheet *sheet = [[[UIActionSheet alloc]
6297 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6298 buttons:[NSArray arrayWithObjects:
6301 defaultButtonIndex:0
6306 [sheet setBodyText:error];
6307 [sheet popupAlertAnimated:YES];
6309 [self reloadButtons];
6313 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6314 if ((self = [super initWithFrame:frame]) != nil) {
6315 database_ = database;
6317 CGRect ovrrect = [navbar_ bounds];
6318 ovrrect.size.height = [UINavigationBar defaultSize].height;
6319 ovrrect.origin.y = -ovrrect.size.height;
6321 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6322 [self addSubview:overlay_];
6324 ovrrect.origin.y = frame.size.height;
6325 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6326 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6327 [self addSubview:underlay_];
6329 [overlay_ setBarStyle:1];
6330 [underlay_ setBarStyle:1];
6332 int barstyle = [overlay_ _barStyle:NO];
6333 bool ugly = barstyle == 0;
6335 UIProgressIndicatorStyle style = ugly ?
6336 UIProgressIndicatorStyleMediumBrown :
6337 UIProgressIndicatorStyleMediumWhite;
6339 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
6340 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6341 CGRect indrect = {{indoffset, indoffset}, indsize};
6343 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6344 [indicator_ setStyle:style];
6345 [overlay_ addSubview:indicator_];
6347 CGSize prmsize = {215, indsize.height + 4};
6350 indoffset * 2 + indsize.width,
6354 unsigned(ovrrect.size.height - prmsize.height) / 2
6357 UIFont *font = [UIFont systemFontOfSize:15];
6359 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6361 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6362 [prompt_ setBackgroundColor:[UIColor clearColor]];
6363 [prompt_ setFont:font];
6365 [overlay_ addSubview:prompt_];
6367 CGSize prgsize = {75, 100};
6370 ovrrect.size.width - prgsize.width - 10,
6371 (ovrrect.size.height - prgsize.height) / 2
6374 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6375 [progress_ setStyle:0];
6376 [overlay_ addSubview:progress_];
6378 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6379 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6381 CGRect frame = [cancel_ frame];
6382 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6383 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6384 [cancel_ setFrame:frame];
6386 [cancel_ setBarStyle:barstyle];
6390 - (void) _onCancel {
6392 [cancel_ removeFromSuperview];
6395 - (void) _update { _pooled
6397 status.setDelegate(self);
6399 NSString *error([database_ updateWithStatus:status]);
6402 performSelectorOnMainThread:@selector(_update_:)
6408 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6409 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6412 - (void) setProgressTitle:(NSString *)title {
6414 performSelectorOnMainThread:@selector(_setProgressTitle:)
6420 - (void) setProgressPercent:(float)percent {
6422 performSelectorOnMainThread:@selector(_setProgressPercent:)
6423 withObject:[NSNumber numberWithFloat:percent]
6428 - (void) startProgress {
6431 - (void) addProgressOutput:(NSString *)output {
6433 performSelectorOnMainThread:@selector(_addProgressOutput:)
6439 - (bool) isCancelling:(size_t)received {
6443 - (void) _setProgressTitle:(NSString *)title {
6444 [prompt_ setText:title];
6447 - (void) _setProgressPercent:(NSNumber *)percent {
6448 [progress_ setProgress:[percent floatValue]];
6451 - (void) _addProgressOutput:(NSString *)output {
6456 /* Cydia:// Protocol {{{ */
6457 @interface CydiaURLProtocol : NSURLProtocol {
6462 @implementation CydiaURLProtocol
6464 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6465 NSURL *url([request URL]);
6468 NSString *scheme([[url scheme] lowercaseString]);
6469 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6474 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6478 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6479 id<NSURLProtocolClient> client([self client]);
6481 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6483 NSData *data(UIImagePNGRepresentation(icon));
6485 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6486 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6487 [client URLProtocol:self didLoadData:data];
6488 [client URLProtocolDidFinishLoading:self];
6492 - (void) startLoading {
6493 id<NSURLProtocolClient> client([self client]);
6494 NSURLRequest *request([self request]);
6496 NSURL *url([request URL]);
6497 NSString *href([url absoluteString]);
6499 NSString *path([href substringFromIndex:8]);
6500 NSRange slash([path rangeOfString:@"/"]);
6503 if (slash.location == NSNotFound) {
6507 command = [path substringToIndex:slash.location];
6508 path = [path substringFromIndex:(slash.location + 1)];
6511 Database *database([Database sharedInstance]);
6513 if ([command isEqualToString:@"package-icon"]) {
6516 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6517 Package *package([database packageWithName:path]);
6520 UIImage *icon([package icon]);
6521 [self _returnPNGWithImage:icon forRequest:request];
6522 } else if ([command isEqualToString:@"source-icon"]) {
6525 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6526 NSString *source(Simplify(path));
6527 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6529 icon = [UIImage applicationImageNamed:@"unknown.png"];
6530 [self _returnPNGWithImage:icon forRequest:request];
6531 } else if ([command isEqualToString:@"uikit-image"]) {
6534 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6535 UIImage *icon(_UIImageWithName(path));
6536 [self _returnPNGWithImage:icon forRequest:request];
6537 } else if ([command isEqualToString:@"section-icon"]) {
6540 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6541 NSString *section(Simplify(path));
6542 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6544 icon = [UIImage applicationImageNamed:@"unknown.png"];
6545 [self _returnPNGWithImage:icon forRequest:request];
6547 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6551 - (void) stopLoading {
6557 /* Sections View {{{ */
6558 @interface SectionsView : RVPage {
6559 _transient Database *database_;
6560 NSMutableArray *sections_;
6561 NSMutableArray *filtered_;
6562 UITransitionView *transition_;
6568 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6569 - (void) reloadData;
6574 @implementation SectionsView
6577 [list_ setDataSource:nil];
6578 [list_ setDelegate:nil];
6580 [sections_ release];
6581 [filtered_ release];
6582 [transition_ release];
6584 [accessory_ release];
6588 - (int) numberOfRowsInTable:(UITable *)table {
6589 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6592 - (float) table:(UITable *)table heightForRow:(int)row {
6596 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6598 reusing = [[[SectionCell alloc] init] autorelease];
6599 [(SectionCell *)reusing setSection:(editing_ ?
6600 [sections_ objectAtIndex:row] :
6601 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6602 ) editing:editing_];
6606 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6610 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6614 - (void) tableRowSelected:(NSNotification *)notification {
6615 int row = [[notification object] selectedRow];
6626 title = UCLocalize("ALL_PACKAGES");
6628 section = [filtered_ objectAtIndex:(row - 1)];
6629 name = [section name];
6632 name = [NSString stringWithString:name];
6633 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6636 title = UCLocalize("NO_SECTION");
6640 PackageTable *table = [[[FilteredPackageTable alloc]
6644 filter:@selector(isVisiblyUninstalledInSection:)
6648 [table setDelegate:delegate_];
6650 [book_ pushPage:table];
6653 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6654 if ((self = [super initWithBook:book]) != nil) {
6655 database_ = database;
6657 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6658 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6660 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6661 [self addSubview:transition_];
6663 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6664 [transition_ transition:0 toView:list_];
6666 UITableColumn *column = [[[UITableColumn alloc]
6667 initWithTitle:UCLocalize("NAME")
6669 width:[self frame].size.width
6672 [list_ setDataSource:self];
6673 [list_ setSeparatorStyle:1];
6674 [list_ addTableColumn:column];
6675 [list_ setDelegate:self];
6676 [list_ setReusesTableCells:YES];
6680 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6681 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6685 - (void) reloadData {
6686 NSArray *packages = [database_ packages];
6688 [sections_ removeAllObjects];
6689 [filtered_ removeAllObjects];
6692 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6693 SectionMap sections;
6694 sections.resize(64);
6696 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6700 for (Package *package in packages) {
6701 NSString *name([package section]);
6702 NSString *key(name == nil ? @"" : name);
6707 _profile(SectionsView$reloadData$Section)
6708 section = §ions[key];
6709 if (*section == nil) {
6710 _profile(SectionsView$reloadData$Section$Allocate)
6711 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6716 [*section addToCount];
6718 _profile(SectionsView$reloadData$Filter)
6719 if (![package valid] || ![package uninstalled] || ![package visible])
6723 [*section addToRow];
6727 _profile(SectionsView$reloadData$Section)
6728 section = [sections objectForKey:key];
6729 if (section == nil) {
6730 _profile(SectionsView$reloadData$Section$Allocate)
6731 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6732 [sections setObject:section forKey:key];
6737 [section addToCount];
6739 _profile(SectionsView$reloadData$Filter)
6740 if (![package valid] || ![package uninstalled] || ![package visible])
6750 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6751 [sections_ addObject:i->second];
6753 [sections_ addObjectsFromArray:[sections allValues]];
6756 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6758 for (Section *section in sections_) {
6759 size_t count([section row]);
6763 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6764 [section setCount:count];
6765 [filtered_ addObject:section];
6772 - (void) resetView {
6774 [self _rightButtonClicked];
6777 - (void) resetViewAnimated:(BOOL)animated {
6778 [list_ resetViewAnimated:animated];
6781 - (void) _rightButtonClicked {
6782 if ((editing_ = !editing_))
6785 [delegate_ updateData];
6786 [book_ reloadTitleForPage:self];
6787 [book_ reloadButtonsForPage:self];
6790 - (NSString *) title {
6791 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("INSTALL_BY_SECTION");
6794 - (NSString *) backButtonTitle {
6795 return UCLocalize("SECTIONS");
6798 - (id) rightButtonTitle {
6799 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6802 - (UINavigationButtonStyle) rightButtonStyle {
6803 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6806 - (UIView *) accessoryView {
6812 /* Changes View {{{ */
6813 @interface ChangesView : RVPage {
6814 _transient Database *database_;
6815 NSMutableArray *packages_;
6816 NSMutableArray *sections_;
6821 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6822 - (void) reloadData;
6826 @implementation ChangesView
6829 [list_ setDelegate:nil];
6830 [list_ setDataSource:nil];
6832 [packages_ release];
6833 [sections_ release];
6838 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6839 NSInteger count([sections_ count]);
6840 return count == 0 ? 1 : count;
6843 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6844 if ([sections_ count] == 0)
6846 return [[sections_ objectAtIndex:section] name];
6849 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6850 if ([sections_ count] == 0)
6852 return [[sections_ objectAtIndex:section] count];
6855 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6856 Section *section([sections_ objectAtIndex:[path section]]);
6857 NSInteger row([path row]);
6858 return [packages_ objectAtIndex:([section row] + row)];
6861 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6862 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6864 cell = [[[PackageCell alloc] init] autorelease];
6865 [cell setPackage:[self packageAtIndexPath:path]];
6869 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6871 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6874 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6875 Package *package([self packageAtIndexPath:path]);
6876 PackageView *view([delegate_ packageView]);
6877 [view setDelegate:delegate_];
6878 [view setPackage:package];
6879 [book_ pushPage:view];
6883 - (void) _leftButtonClicked {
6884 [(CYBook *)book_ update];
6885 [self reloadButtons];
6888 - (void) _rightButtonClicked {
6889 [delegate_ distUpgrade];
6892 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6893 if ((self = [super initWithBook:book]) != nil) {
6894 database_ = database;
6896 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6897 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6899 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
6900 [self addSubview:list_];
6902 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
6903 [list_ setDataSource:self];
6904 [list_ setDelegate:self];
6905 //[list_ setSectionListStyle:1];
6909 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6910 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6914 - (void) reloadData {
6915 NSArray *packages = [database_ packages];
6917 [packages_ removeAllObjects];
6918 [sections_ removeAllObjects];
6921 for (Package *package in packages)
6923 [package uninstalled] && [package valid] && [package visible] ||
6924 [package upgradableAndEssential:YES]
6926 [packages_ addObject:package];
6929 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6932 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6933 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6934 Section *section = nil;
6938 bool unseens = false;
6940 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6942 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6943 Package *package = [packages_ objectAtIndex:offset];
6945 BOOL uae = [package upgradableAndEssential:YES];
6951 _profile(ChangesView$reloadData$Remember)
6952 seen = [package seen];
6955 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6960 name = UCLocalize("UNKNOWN");
6962 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6966 _profile(ChangesView$reloadData$Allocate)
6967 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
6968 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6969 [sections_ addObject:section];
6973 [section addToCount];
6974 } else if ([package ignored])
6975 [ignored addToCount];
6978 [upgradable addToCount];
6983 CFRelease(formatter);
6986 Section *last = [sections_ lastObject];
6987 size_t count = [last count];
6988 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6989 [sections_ removeLastObject];
6992 if ([ignored count] != 0)
6993 [sections_ insertObject:ignored atIndex:0];
6995 [sections_ insertObject:upgradable atIndex:0];
6998 [self reloadButtons];
7001 - (void) resetViewAnimated:(BOOL)animated {
7002 [list_ resetViewAnimated:animated];
7005 - (NSString *) leftButtonTitle {
7006 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
7009 - (id) rightButtonTitle {
7010 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
7013 - (NSString *) title {
7014 return UCLocalize("CHANGES");
7019 /* Search View {{{ */
7020 @protocol SearchViewDelegate
7021 - (void) showKeyboard:(BOOL)show;
7024 @interface SearchView : RVPage {
7026 UISearchField *field_;
7027 UITransitionView *transition_;
7028 FilteredPackageTable *table_;
7029 UIPreferencesTable *advanced_;
7035 - (id) initWithBook:(RVBook *)book database:(Database *)database;
7036 - (void) reloadData;
7040 @implementation SearchView
7043 [field_ setDelegate:nil];
7045 [accessory_ release];
7047 [transition_ release];
7049 [advanced_ release];
7054 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7058 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7060 case 0: return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("ADVANCED_SEARCH"), UCLocalize("COMING_SOON")];
7062 default: _assert(false);
7066 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7070 default: _assert(false);
7074 - (void) _showKeyboard:(BOOL)show {
7075 CGSize keysize = [UIKeyboard defaultSize];
7076 CGRect keydown = [book_ pageBounds];
7077 CGRect keyup = keydown;
7078 keyup.size.height -= keysize.height - ButtonBarHeight_;
7080 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7082 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7083 [animation setSignificantRectFields:8];
7086 [animation setStartFrame:keydown];
7087 [animation setEndFrame:keyup];
7089 [animation setStartFrame:keyup];
7090 [animation setEndFrame:keydown];
7093 UIAnimator *animator = [UIAnimator sharedAnimator];
7096 addAnimations:[NSArray arrayWithObjects:animation, nil]
7097 withDuration:(KeyboardTime_ - delay)
7102 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7104 [delegate_ showKeyboard:show];
7107 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7108 [self _showKeyboard:YES];
7111 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7112 [self _showKeyboard:NO];
7115 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7117 NSString *text([field_ text]);
7118 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7124 - (void) textFieldClearButtonPressed:(UITextField *)field {
7128 - (void) keyboardInputShouldDelete:(id)input {
7132 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7133 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7137 [field_ resignFirstResponder];
7142 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7143 if ((self = [super initWithBook:book]) != nil) {
7144 CGRect pageBounds = [book_ pageBounds];
7146 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
7147 [self addSubview:transition_];
7149 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
7151 [advanced_ setReusesTableCells:YES];
7152 [advanced_ setDataSource:self];
7153 [advanced_ reloadData];
7155 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
7156 CGColor dimmed(space_, 0, 0, 0, 0.5);
7157 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
7159 table_ = [[FilteredPackageTable alloc]
7163 filter:@selector(isUnfilteredAndSearchedForBy:)
7167 [table_ setShouldHideHeaderInShortLists:NO];
7168 [transition_ transition:0 toView:table_];
7177 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
7184 [self bounds].size.width - area.origin.x - 18;
7186 area.size.height = [UISearchField defaultHeight];
7188 field_ = [[UISearchField alloc] initWithFrame:area];
7190 UIFont *font = [UIFont systemFontOfSize:16];
7191 [field_ setFont:font];
7193 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7194 [field_ setDelegate:self];
7196 [field_ setPaddingTop:5];
7198 UITextInputTraits *traits([field_ textInputTraits]);
7199 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7200 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7201 [traits setReturnKeyType:UIReturnKeySearch];
7203 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7205 accessory_ = [[UIView alloc] initWithFrame:accrect];
7206 [accessory_ addSubview:field_];
7208 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
7209 [configure setShowPressFeedback:YES];
7210 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
7211 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
7212 [accessory_ addSubview:configure];*/
7214 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7215 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7221 LKAnimation *animation = [LKTransition animation];
7222 [animation setType:@"oglFlip"];
7223 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
7224 [animation setFillMode:@"extended"];
7225 [animation setTransitionFlags:3];
7226 [animation setDuration:10];
7227 [animation setSpeed:0.35];
7228 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
7229 [[transition_ _layer] addAnimation:animation forKey:0];
7230 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
7231 flipped_ = !flipped_;
7235 - (void) configurePushed {
7236 [field_ resignFirstResponder];
7240 - (void) resetViewAnimated:(BOOL)animated {
7243 [table_ resetViewAnimated:animated];
7246 - (void) _reloadData {
7249 - (void) reloadData {
7252 [table_ setObject:[field_ text]];
7253 _profile(SearchView$reloadData)
7254 [table_ reloadData];
7257 [table_ resetCursor];
7260 - (UIView *) accessoryView {
7264 - (NSString *) title {
7268 - (NSString *) backButtonTitle {
7269 return UCLocalize("SEARCH");
7272 - (void) setDelegate:(id)delegate {
7273 [table_ setDelegate:delegate];
7274 [super setDelegate:delegate];
7279 /* Settings View {{{ */
7280 @interface SettingsView : RVPage {
7281 _transient Database *database_;
7284 UIPreferencesTable *table_;
7285 _UISwitchSlider *subscribedSwitch_;
7286 _UISwitchSlider *ignoredSwitch_;
7287 UIPreferencesControlTableCell *subscribedCell_;
7288 UIPreferencesControlTableCell *ignoredCell_;
7291 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7295 @implementation SettingsView
7298 [table_ setDataSource:nil];
7301 if (package_ != nil)
7304 [subscribedSwitch_ release];
7305 [ignoredSwitch_ release];
7306 [subscribedCell_ release];
7307 [ignoredCell_ release];
7311 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7312 if (package_ == nil)
7318 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7319 if (package_ == nil)
7326 default: _assert(false);
7332 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7333 if (package_ == nil)
7340 default: _assert(false);
7346 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7347 if (package_ == nil)
7354 default: _assert(false);
7360 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7361 if (package_ == nil)
7364 _UISwitchSlider *slider([cell control]);
7365 BOOL value([slider value] != 0);
7366 NSMutableDictionary *metadata([package_ metadata]);
7369 if (NSNumber *number = [metadata objectForKey:key])
7370 before = [number boolValue];
7374 if (value != before) {
7375 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7377 [delegate_ updateData];
7381 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7382 [self onSomething:cell withKey:@"IsSubscribed"];
7385 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7386 [self onSomething:cell withKey:@"IsIgnored"];
7389 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7390 if (package_ == nil)
7394 case 0: switch (row) {
7396 return subscribedCell_;
7398 return ignoredCell_;
7399 default: _assert(false);
7402 case 1: switch (row) {
7404 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7405 [cell setShowSelection:NO];
7406 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7410 default: _assert(false);
7413 default: _assert(false);
7419 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7420 if ((self = [super initWithBook:book])) {
7421 database_ = database;
7422 name_ = [package retain];
7424 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7425 [self addSubview:table_];
7427 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7428 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7430 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7431 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7433 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7434 [subscribedCell_ setShowSelection:NO];
7435 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7436 [subscribedCell_ setControl:subscribedSwitch_];
7438 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7439 [ignoredCell_ setShowSelection:NO];
7440 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7441 [ignoredCell_ setControl:ignoredSwitch_];
7443 [table_ setDataSource:self];
7448 - (void) resetViewAnimated:(BOOL)animated {
7449 [table_ resetViewAnimated:animated];
7452 - (void) reloadData {
7453 if (package_ != nil)
7454 [package_ autorelease];
7455 package_ = [database_ packageWithName:name_];
7456 if (package_ != nil) {
7458 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7459 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7462 [table_ reloadData];
7465 - (NSString *) title {
7466 return UCLocalize("SETTINGS");
7472 /* Signature View {{{ */
7473 @interface SignatureView : CydiaBrowserView {
7474 _transient Database *database_;
7478 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7482 @implementation SignatureView
7489 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7491 [super webView:sender didClearWindowObject:window forFrame:frame];
7494 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7495 if ((self = [super initWithBook:book]) != nil) {
7496 database_ = database;
7497 package_ = [package retain];
7502 - (void) resetViewAnimated:(BOOL)animated {
7505 - (void) reloadData {
7506 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7512 @interface Cydia : UIApplication <
7513 ConfirmationViewDelegate,
7514 ProgressViewDelegate,
7523 UIToolbar *buttonbar_;
7527 NSMutableArray *essential_;
7528 NSMutableArray *broken_;
7530 Database *database_;
7531 ProgressView *progress_;
7535 UIKeyboard *keyboard_;
7536 UIProgressHUD *hud_;
7538 SectionsView *sections_;
7539 ChangesView *changes_;
7540 ManageView *manage_;
7541 SearchView *search_;
7543 #if RecyclePackageViews
7544 NSMutableArray *details_;
7550 @implementation Cydia
7553 if ([broken_ count] != 0) {
7554 int count = [broken_ count];
7556 UIActionSheet *sheet = [[[UIActionSheet alloc]
7557 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7558 buttons:[NSArray arrayWithObjects:
7559 UCLocalize("FORCIBLY_CLEAR"),
7560 UCLocalize("TEMPORARY_IGNORE"),
7562 defaultButtonIndex:0
7567 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7568 [sheet popupAlertAnimated:YES];
7569 } else if (!Ignored_ && [essential_ count] != 0) {
7570 int count = [essential_ count];
7572 UIActionSheet *sheet = [[[UIActionSheet alloc]
7573 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7574 buttons:[NSArray arrayWithObjects:
7575 UCLocalize("UPGRADE_ESSENTIAL"),
7576 UCLocalize("COMPLETE_UPGRADE"),
7577 UCLocalize("TEMPORARY_IGNORE"),
7579 defaultButtonIndex:0
7584 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7585 [sheet popupAlertAnimated:YES];
7589 - (void) _saveConfig {
7592 NSString *error(nil);
7593 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7595 NSError *error(nil);
7596 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7597 NSLog(@"failure to save metadata data: %@", error);
7600 NSLog(@"failure to serialize metadata: %@", error);
7608 - (void) _updateData {
7611 /* XXX: this is just stupid */
7612 if (tag_ != 2 && sections_ != nil)
7613 [sections_ reloadData];
7614 if (tag_ != 3 && changes_ != nil)
7615 [changes_ reloadData];
7616 if (tag_ != 5 && search_ != nil)
7617 [search_ reloadData];
7622 - (void) _reloadData {
7625 static bool loaded(false);
7626 UIProgressHUD *hud([self addProgressHUD]);
7627 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7630 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7633 [self removeProgressHUD:hud];
7637 [essential_ removeAllObjects];
7638 [broken_ removeAllObjects];
7640 NSArray *packages = [database_ packages];
7641 for (Package *package in packages) {
7643 [broken_ addObject:package];
7644 if ([package upgradableAndEssential:NO]) {
7645 if ([package essential])
7646 [essential_ addObject:package];
7652 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7653 [buttonbar_ setBadgeValue:badge forButton:3];
7654 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7655 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7656 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7657 [self setApplicationBadge:badge];
7659 [self setApplicationBadgeString:badge];
7661 [buttonbar_ setBadgeValue:nil forButton:3];
7662 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7663 [buttonbar_ setBadgeAnimated:NO forButton:3];
7664 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7665 [self removeApplicationBadge];
7666 else // XXX: maybe use setApplicationBadgeString also?
7667 [self setApplicationIconBadgeNumber:0];
7671 [buttonbar_ setBadgeValue:nil forButton:4];
7675 // XXX: what is this line of code for?
7676 if ([packages count] == 0);
7677 else if (Loaded_ || ManualRefresh) loaded:
7682 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7683 NSTimeInterval interval([update timeIntervalSinceNow]);
7684 if (interval <= 0 && interval > -600)
7692 - (void) updateData {
7693 [database_ setVisible];
7702 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7703 _assert(file != NULL);
7705 NSArray *keys = [Sources_ allKeys];
7707 for (NSString *key in keys) {
7708 NSDictionary *source = [Sources_ objectForKey:key];
7710 fprintf(file, "%s %s %s\n",
7711 [[source objectForKey:@"Type"] UTF8String],
7712 [[source objectForKey:@"URI"] UTF8String],
7713 [[source objectForKey:@"Distribution"] UTF8String]
7722 detachNewThreadSelector:@selector(update_)
7725 title:UCLocalize("UPDATING_SOURCES")
7729 - (void) reloadData {
7730 @synchronized (self) {
7731 if (confirm_ == nil)
7737 pkgProblemResolver *resolver = [database_ resolver];
7739 resolver->InstallProtect();
7740 if (!resolver->Resolve(true))
7744 - (void) popUpBook:(RVBook *)book {
7745 [underlay_ popSubview:book];
7748 - (CGRect) popUpBounds {
7749 return [underlay_ bounds];
7753 [database_ prepare];
7755 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7756 [confirm_ setDelegate:self];
7758 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7759 [page setDelegate:self];
7761 [confirm_ setPage:page];
7762 [self popUpBook:confirm_];
7766 @synchronized (self) {
7771 - (void) clearPackage:(Package *)package {
7772 @synchronized (self) {
7779 - (void) installPackage:(Package *)package {
7780 @synchronized (self) {
7787 - (void) removePackage:(Package *)package {
7788 @synchronized (self) {
7795 - (void) distUpgrade {
7796 @synchronized (self) {
7797 [database_ upgrade];
7803 [self slideUp:[[[UIActionSheet alloc]
7805 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7806 defaultButtonIndex:1
7813 @synchronized (self) {
7816 if (confirm_ != nil) {
7824 [overlay_ removeFromSuperview];
7828 detachNewThreadSelector:@selector(perform)
7831 title:UCLocalize("RUNNING")
7835 - (void) bootstrap_ {
7837 [database_ upgrade];
7838 [database_ prepare];
7839 [database_ perform];
7842 /* XXX: replace and localize */
7843 - (void) bootstrap {
7845 detachNewThreadSelector:@selector(bootstrap_)
7848 title:@"Bootstrap Install"
7852 - (void) progressViewIsComplete:(ProgressView *)progress {
7853 if (confirm_ != nil) {
7854 [underlay_ addSubview:overlay_];
7855 [confirm_ popFromSuperviewAnimated:NO];
7861 - (void) setPage:(RVPage *)page {
7862 [page resetViewAnimated:NO];
7863 [page setDelegate:self];
7864 [book_ setPage:page];
7867 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7868 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7869 [browser loadURL:url];
7873 - (void) _setHomePage {
7874 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7877 - (SectionsView *) sectionsView {
7878 if (sections_ == nil)
7879 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7883 - (void) buttonBarItemTapped:(id)sender {
7884 unsigned tag = [sender tag];
7886 [book_ resetViewAnimated:YES];
7888 } else if (tag_ == 2 && tag != 2)
7889 [[self sectionsView] resetView];
7892 case 1: [self _setHomePage]; break;
7894 case 2: [self setPage:[self sectionsView]]; break;
7895 case 3: [self setPage:changes_]; break;
7896 case 4: [self setPage:manage_]; break;
7897 case 5: [self setPage:search_]; break;
7899 default: _assert(false);
7905 - (void) applicationWillSuspend {
7907 [super applicationWillSuspend];
7910 - (void) askForSettings {
7911 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7913 UIActionSheet *role = [[[UIActionSheet alloc]
7914 initWithTitle:UCLocalize("WHO_ARE_YOU")
7915 buttons:[NSArray arrayWithObjects:
7916 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7917 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7918 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7920 defaultButtonIndex:-1
7925 [role setBodyText:UCLocalize("ROLE_EX")];
7926 [role popupAlertAnimated:YES];
7929 - (void) setPackageView:(PackageView *)view {
7931 [view setPackage:nil];
7932 #if RecyclePackageViews
7933 if ([details_ count] < 3)
7934 [details_ addObject:view];
7939 - (PackageView *) _packageView {
7940 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7943 - (PackageView *) packageView {
7944 #if RecyclePackageViews
7946 size_t count([details_ count]);
7949 view = [self _packageView];
7951 [details_ addObject:[self _packageView]];
7953 view = [[[details_ lastObject] retain] autorelease];
7954 [details_ removeLastObject];
7961 return [self _packageView];
7967 [self setStatusBarShowsProgress:NO];
7968 [self removeProgressHUD:hud_];
7973 pid_t pid = ExecFork();
7975 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7976 perror("launchctl stop");
7983 [self askForSettings];
7988 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7990 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7991 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7992 0, 0, screenrect.size.width, screenrect.size.height - 48
7993 ) database:database_];
7995 [book_ setDelegate:self];
7997 [overlay_ addSubview:book_];
7999 NSArray *buttonitems = [NSArray arrayWithObjects:
8000 [NSDictionary dictionaryWithObjectsAndKeys:
8001 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8002 @"home-up.png", kUIButtonBarButtonInfo,
8003 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
8004 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
8005 self, kUIButtonBarButtonTarget,
8006 @"Cydia", kUIButtonBarButtonTitle,
8007 @"0", kUIButtonBarButtonType,
8010 [NSDictionary dictionaryWithObjectsAndKeys:
8011 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8012 @"install-up.png", kUIButtonBarButtonInfo,
8013 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
8014 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
8015 self, kUIButtonBarButtonTarget,
8016 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
8017 @"0", kUIButtonBarButtonType,
8020 [NSDictionary dictionaryWithObjectsAndKeys:
8021 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8022 @"changes-up.png", kUIButtonBarButtonInfo,
8023 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
8024 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
8025 self, kUIButtonBarButtonTarget,
8026 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
8027 @"0", kUIButtonBarButtonType,
8030 [NSDictionary dictionaryWithObjectsAndKeys:
8031 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8032 @"manage-up.png", kUIButtonBarButtonInfo,
8033 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
8034 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
8035 self, kUIButtonBarButtonTarget,
8036 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
8037 @"0", kUIButtonBarButtonType,
8040 [NSDictionary dictionaryWithObjectsAndKeys:
8041 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8042 @"search-up.png", kUIButtonBarButtonInfo,
8043 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
8044 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
8045 self, kUIButtonBarButtonTarget,
8046 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
8047 @"0", kUIButtonBarButtonType,
8051 buttonbar_ = [[UIToolbar alloc]
8053 withFrame:CGRectMake(
8054 0, screenrect.size.height - ButtonBarHeight_,
8055 screenrect.size.width, ButtonBarHeight_
8057 withItemList:buttonitems
8060 [buttonbar_ setDelegate:self];
8061 [buttonbar_ setBarStyle:1];
8062 [buttonbar_ setButtonBarTrackingMode:2];
8064 int buttons[5] = {1, 2, 3, 4, 5};
8065 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
8066 [buttonbar_ showButtonGroup:0 withDuration:0];
8068 for (int i = 0; i != 5; ++i)
8069 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
8070 i * 64 + 2, 1, 60, ButtonBarHeight_
8073 [buttonbar_ showSelectionForButton:1];
8074 [overlay_ addSubview:buttonbar_];
8076 [UIKeyboard initImplementationNow];
8077 CGSize keysize = [UIKeyboard defaultSize];
8078 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8079 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8080 [overlay_ addSubview:keyboard_];
8083 [underlay_ addSubview:overlay_];
8087 [self sectionsView];
8088 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
8089 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
8091 manage_ = (ManageView *) [[self
8092 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8093 withClass:[ManageView class]
8096 #if RecyclePackageViews
8097 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8098 [details_ addObject:[self _packageView]];
8099 [details_ addObject:[self _packageView]];
8107 [self _setHomePage];
8110 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
8111 NSString *context([sheet context]);
8113 if ([context isEqualToString:@"missing"])
8115 else if ([context isEqualToString:@"cancel"]) {
8133 @synchronized (self) {
8138 [buttonbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
8142 if (confirm_ != nil) {
8147 } else if ([context isEqualToString:@"fixhalf"]) {
8150 @synchronized (self) {
8151 for (Package *broken in broken_) {
8154 NSString *id = [broken id];
8155 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8156 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8157 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8158 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8167 [broken_ removeAllObjects];
8176 } else if ([context isEqualToString:@"role"]) {
8178 case 1: Role_ = @"User"; break;
8179 case 2: Role_ = @"Hacker"; break;
8180 case 3: Role_ = @"Developer"; break;
8187 bool reset = Settings_ != nil;
8189 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8193 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8203 } else if ([context isEqualToString:@"upgrade"]) {
8206 @synchronized (self) {
8207 for (Package *essential in essential_)
8208 [essential install];
8231 - (void) reorganize { _pooled
8232 system("/usr/libexec/cydia/free.sh");
8233 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
8236 - (void) applicationSuspend:(__GSEvent *)event {
8237 if (hud_ == nil && ![progress_ isRunning])
8238 [super applicationSuspend:event];
8241 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8243 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8246 - (void) _setSuspended:(BOOL)value {
8248 [super _setSuspended:value];
8251 - (UIProgressHUD *) addProgressHUD {
8252 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8253 [window_ setUserInteractionEnabled:NO];
8255 [progress_ addSubview:hud];
8259 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8261 [hud removeFromSuperview];
8262 [window_ setUserInteractionEnabled:YES];
8265 - (RVPage *) pageForPackage:(NSString *)name {
8266 if (Package *package = [database_ packageWithName:name]) {
8267 PackageView *view([self packageView]);
8268 [view setPackage:package];
8271 UIActionSheet *sheet = [[[UIActionSheet alloc]
8272 initWithTitle:UCLocalize("CANNOT_LOCATE_PACKAGE")
8273 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
8274 defaultButtonIndex:0
8279 [sheet setBodyText:[NSString stringWithFormat:UCLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
8281 [sheet popupAlertAnimated:YES];
8286 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8290 NSString *href([url absoluteString]);
8291 if ([href hasPrefix:@"apptapp://package/"])
8292 return [self pageForPackage:[href substringFromIndex:18]];
8294 NSString *scheme([[url scheme] lowercaseString]);
8295 if (![scheme isEqualToString:@"cydia"])
8297 NSString *path([url absoluteString]);
8298 if ([path length] < 8)
8300 path = [path substringFromIndex:8];
8301 if (![path hasPrefix:@"/"])
8302 path = [@"/" stringByAppendingString:path];
8304 if ([path isEqualToString:@"/add-source"])
8305 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8306 else if ([path isEqualToString:@"/storage"])
8307 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8308 else if ([path isEqualToString:@"/sources"])
8309 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8310 else if ([path isEqualToString:@"/packages"])
8311 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8312 else if ([path hasPrefix:@"/url/"])
8313 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8314 else if ([path hasPrefix:@"/launch/"])
8315 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8316 else if ([path hasPrefix:@"/package-settings/"])
8317 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8318 else if ([path hasPrefix:@"/package-signature/"])
8319 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8320 else if ([path hasPrefix:@"/package/"])
8321 return [self pageForPackage:[path substringFromIndex:9]];
8322 else if ([path hasPrefix:@"/files/"]) {
8323 NSString *name = [path substringFromIndex:7];
8325 if (Package *package = [database_ packageWithName:name]) {
8326 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8327 [files setPackage:package];
8335 - (void) applicationOpenURL:(NSURL *)url {
8336 [super applicationOpenURL:url];
8338 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8339 [self setPage:page];
8340 [buttonbar_ showSelectionForButton:tag];
8345 - (void) applicationDidFinishLaunching:(id)unused {
8346 [BrowserView _initialize];
8348 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8350 Font12_ = [[UIFont systemFontOfSize:12] retain];
8351 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8352 Font14_ = [[UIFont systemFontOfSize:14] retain];
8353 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8354 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8358 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8359 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8361 window_ = [[UIWindow alloc] initWithContentRect:[UIHardware fullScreenApplicationContentRect]];
8362 [window_ orderFront:self];
8363 [window_ makeKey:self];
8364 [window_ setHidden:NO];
8366 database_ = [Database sharedInstance];
8368 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8369 [database_ setDelegate:progress_];
8370 [window_ setContentView:progress_];
8372 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8373 [progress_ setContentView:underlay_];
8375 [progress_ resetView];
8378 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8379 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8380 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8381 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8382 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8383 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8384 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8385 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8386 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8389 [self setIdleTimerDisabled:YES];
8391 hud_ = [[self addProgressHUD] retain];
8392 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8394 [self setStatusBarShowsProgress:YES];
8397 detachNewThreadSelector:@selector(reorganize)
8405 - (void) showKeyboard:(BOOL)show {
8406 CGSize keysize = [UIKeyboard defaultSize];
8407 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8408 CGRect keyup = keydown;
8409 keyup.origin.y -= keysize.height;
8411 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8412 [animation setSignificantRectFields:2];
8415 [animation setStartFrame:keydown];
8416 [animation setEndFrame:keyup];
8417 [keyboard_ activate];
8419 [animation setStartFrame:keyup];
8420 [animation setEndFrame:keydown];
8421 [keyboard_ deactivate];
8424 [[UIAnimator sharedAnimator]
8425 addAnimations:[NSArray arrayWithObjects:animation, nil]
8426 withDuration:KeyboardTime_
8431 - (void) slideUp:(UIActionSheet *)alert {
8433 [alert presentSheetFromButtonBar:buttonbar_];
8435 [alert presentSheetInView:overlay_];
8440 void AddPreferences(NSString *plist) { _pooled
8441 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8442 _assert(settings != NULL);
8443 NSMutableArray *items = [settings objectForKey:@"items"];
8447 for (NSMutableDictionary *item in items) {
8448 NSString *label = [item objectForKey:@"label"];
8449 if (label != nil && [label isEqualToString:@"Cydia"]) {
8456 for (size_t i(0); i != [items count]; ++i) {
8457 NSDictionary *item([items objectAtIndex:i]);
8458 NSString *label = [item objectForKey:@"label"];
8459 if (label != nil && [label isEqualToString:@"General"]) {
8460 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8461 @"CydiaSettings", @"bundle",
8462 @"PSLinkCell", @"cell",
8463 [NSNumber numberWithBool:YES], @"hasIcon",
8464 [NSNumber numberWithBool:YES], @"isController",
8466 nil] atIndex:(i + 1)];
8472 _assert([settings writeToFile:plist atomically:YES] == YES);
8477 id Alloc_(id self, SEL selector) {
8478 id object = alloc_(self, selector);
8479 lprintf("[%s]A-%p\n", self->isa->name, object);
8484 id Dealloc_(id self, SEL selector) {
8485 id object = dealloc_(self, selector);
8486 lprintf("[%s]D-%p\n", self->isa->name, object);
8490 Class $WebDefaultUIKitDelegate;
8492 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8494 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8495 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8496 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8497 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8500 int main(int argc, char *argv[]) { _pooled
8503 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8505 /* Library Hacks {{{ */
8506 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8508 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8509 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8510 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8511 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8512 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8515 /* Set Locale {{{ */
8516 Locale_ = CFLocaleCopyCurrent();
8517 Languages_ = [NSLocale preferredLanguages];
8518 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8519 //NSLog(@"%@", [Languages_ description]);
8521 if (Languages_ == nil || [Languages_ count] == 0)
8524 lang = [[Languages_ objectAtIndex:0] UTF8String];
8525 setenv("LANG", lang, true);
8526 //std::setlocale(LC_ALL, lang);
8527 NSLog(@"Setting Language: %s", lang);
8530 // XXX: apr_app_initialize?
8533 /* Parse Arguments {{{ */
8534 bool substrate(false);
8540 for (int argi(1); argi != argc; ++argi)
8541 if (strcmp(argv[argi], "--") == 0) {
8543 argv[argi] = argv[0];
8549 for (int argi(1); argi != arge; ++argi)
8550 if (strcmp(args[argi], "--bootstrap") == 0)
8552 else if (strcmp(args[argi], "--substrate") == 0)
8555 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8559 App_ = [[NSBundle mainBundle] bundlePath];
8560 Home_ = NSHomeDirectory();
8565 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8566 alloc_ = alloc->method_imp;
8567 alloc->method_imp = (IMP) &Alloc_;*/
8569 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8570 dealloc_ = dealloc->method_imp;
8571 dealloc->method_imp = (IMP) &Dealloc_;*/
8576 size = sizeof(maxproc);
8577 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8578 perror("sysctlbyname(\"kern.maxproc\", ?)");
8579 else if (maxproc < 64) {
8581 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8582 perror("sysctlbyname(\"kern.maxproc\", #)");
8585 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8586 char *osversion = new char[size];
8587 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8588 perror("sysctlbyname(\"kern.osversion\", ?)");
8590 System_ = [NSString stringWithUTF8String:osversion];
8592 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8593 char *machine = new char[size];
8594 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8595 perror("sysctlbyname(\"hw.machine\", ?)");
8599 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8600 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8601 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8602 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8606 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8607 NSData *data((NSData *) ecid);
8608 size_t length([data length]);
8609 uint8_t bytes[length];
8610 [data getBytes:bytes];
8611 char string[length * 2 + 1];
8612 for (size_t i(0); i != length; ++i)
8613 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8614 ChipID_ = [NSString stringWithUTF8String:string];
8618 IOObjectRelease(service);
8622 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8624 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8625 Build_ = [system objectForKey:@"ProductBuildVersion"];
8626 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8627 Product_ = [info objectForKey:@"SafariProductVersion"];
8628 Safari_ = [info objectForKey:@"CFBundleVersion"];
8631 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8632 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8634 /* Load Database {{{ */
8636 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8638 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8641 if (Metadata_ == NULL)
8642 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8644 Settings_ = [Metadata_ objectForKey:@"Settings"];
8646 Packages_ = [Metadata_ objectForKey:@"Packages"];
8647 Sections_ = [Metadata_ objectForKey:@"Sections"];
8648 Sources_ = [Metadata_ objectForKey:@"Sources"];
8651 if (Settings_ != nil)
8652 Role_ = [Settings_ objectForKey:@"Role"];
8654 if (Packages_ == nil) {
8655 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8656 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8659 if (Sections_ == nil) {
8660 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8661 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8664 if (Sources_ == nil) {
8665 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8666 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8671 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8674 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8675 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8676 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8677 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8679 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8680 unlink("/tmp/.cydia.fw");
8682 } else if (access("/User", F_OK) != 0) {
8685 system("/usr/libexec/cydia/firmware.sh");
8689 _assert([[NSFileManager defaultManager]
8690 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8691 withIntermediateDirectories:YES
8696 if (access("/tmp/cydia.chk", F_OK) == 0) {
8697 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8698 _assert(errno == ENOENT);
8699 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8700 _assert(errno == ENOENT);
8703 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8705 /* APT Initialization {{{ */
8706 _assert(pkgInitConfig(*_config));
8707 _assert(pkgInitSystem(*_config, _system));
8710 _config->Set("APT::Acquire::Translation", lang);
8711 _config->Set("Acquire::http::Timeout", 15);
8712 _config->Set("Acquire::http::MaxParallel", 3);
8714 /* Color Choices {{{ */
8715 space_ = CGColorSpaceCreateDeviceRGB();
8717 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8718 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8719 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8720 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8721 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8722 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8723 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8724 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8725 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8727 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8728 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8730 /* UIKit Configuration {{{ */
8731 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8732 if ($GSFontSetUseLegacyFontMetrics != NULL)
8733 $GSFontSetUseLegacyFontMetrics(YES);
8735 UIKeyboardDisableAutomaticAppearance();
8739 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8741 CGColorSpaceRelease(space_);