1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2009 Jay Freeman (saurik)
6 * Redistribution and use in source and binary
7 * forms, with or without modification, are permitted
8 * provided that the following conditions are met:
10 * 1. Redistributions of source code must retain the
11 * above copyright notice, this list of conditions
12 * and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the
14 * above copyright notice, this list of conditions
15 * and the following disclaimer in the documentation
16 * and/or other materials provided with the
18 * 3. The name of the author may not be used to endorse
19 * or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
23 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
24 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
28 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
33 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 // XXX: wtf/FastMalloc.h... wtf?
39 #define USE_SYSTEM_MALLOC 1
41 /* #include Directives {{{ */
42 #import "UICaboodle.h"
43 #import "UCLocalize.h"
45 #include <objc/message.h>
46 #include <objc/objc.h>
47 #include <objc/runtime.h>
49 #include <CoreGraphics/CoreGraphics.h>
50 #include <GraphicsServices/GraphicsServices.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #import <UIKit/UIKit.h>
64 #include <WebCore/WebCoreThread.h>
65 #import <WebKit/WebDefaultUIKitDelegate.h>
72 #include <ext/stdio_filebuf.h>
74 #include <apt-pkg/acquire.h>
75 #include <apt-pkg/acquire-item.h>
76 #include <apt-pkg/algorithms.h>
77 #include <apt-pkg/cachefile.h>
78 #include <apt-pkg/clean.h>
79 #include <apt-pkg/configuration.h>
80 #include <apt-pkg/debindexfile.h>
81 #include <apt-pkg/debmetaindex.h>
82 #include <apt-pkg/error.h>
83 #include <apt-pkg/init.h>
84 #include <apt-pkg/mmap.h>
85 #include <apt-pkg/pkgrecords.h>
86 #include <apt-pkg/sha1.h>
87 #include <apt-pkg/sourcelist.h>
88 #include <apt-pkg/sptr.h>
89 #include <apt-pkg/strutl.h>
90 #include <apt-pkg/tagfile.h>
92 #include <apr-1/apr_pools.h>
94 #include <sys/types.h>
96 #include <sys/sysctl.h>
97 #include <sys/param.h>
98 #include <sys/mount.h>
104 #include <mach-o/nlist.h>
114 #include <ext/hash_map>
116 #import "BrowserView.h"
117 #import "ResetView.h"
119 #import "substrate.h"
122 //#define _finline __attribute__((force_inline))
123 #define _finline inline
128 #define _limit(count) do { \
129 static size_t _count(0); \
130 if (++_count == count) \
135 #define _timestamp ({ \
137 gettimeofday(&tv, NULL); \
138 tv.tv_sec * 1000000 + tv.tv_usec; \
141 typedef std::vector<class ProfileTime *> TimeList;
151 ProfileTime(const char *name) :
155 times_.push_back(this);
158 void AddTime(uint64_t time) {
165 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
177 ProfileTimer(ProfileTime &time) :
184 time_.AddTime(_timestamp - start_);
189 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
191 std::cerr << "========" << std::endl;
194 #define _profile(name) { \
195 static ProfileTime name(#name); \
196 ProfileTimer _ ## name(name);
200 /* Objective-C Handle<> {{{ */
201 template <typename Type_>
203 typedef _H<Type_> This_;
208 _finline void Retain_() {
213 _finline void Clear_() {
219 _finline _H(const This_ &rhs) :
220 value_(rhs.value_ == nil ? nil : [rhs.value_ retain])
224 _finline _H(Type_ *value = NULL, bool mended = false) :
235 _finline operator Type_ *() const {
239 _finline This_ &operator =(Type_ *value) {
240 if (value_ != value) {
251 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
253 void NSLogPoint(const char *fix, const CGPoint &point) {
254 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
257 void NSLogRect(const char *fix, const CGRect &rect) {
258 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
261 @interface NSObject (Cydia)
262 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
263 - (id) yieldToSelector:(SEL)selector;
266 @implementation NSObject (Cydia)
271 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
272 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
273 id object([[context objectAtIndex:1] nonretainedObjectValue]);
274 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
276 /* XXX: deal with exceptions */
277 id value([self performSelector:selector withObject:object]);
279 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
280 [context removeAllObjects];
281 if ([signature methodReturnLength] != 0 && value != nil)
282 [context addObject:value];
287 performSelectorOnMainThread:@selector(doNothing)
293 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
294 /*return [self performSelector:selector withObject:object];*/
296 volatile bool stopped(false);
298 NSMutableArray *context([NSMutableArray arrayWithObjects:
299 [NSValue valueWithPointer:selector],
300 [NSValue valueWithNonretainedObject:object],
301 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
304 NSThread *thread([[[NSThread alloc]
306 selector:@selector(_yieldToContext:)
312 NSRunLoop *loop([NSRunLoop currentRunLoop]);
313 NSDate *future([NSDate distantFuture]);
315 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
317 return [context count] == 0 ? nil : [context objectAtIndex:0];
320 - (id) yieldToSelector:(SEL)selector {
321 return [self yieldToSelector:selector withObject:nil];
326 /* NSForcedOrderingSearch doesn't work on the iPhone */
327 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
328 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
329 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
331 /* iPhoneOS 2.0 Compatibility {{{ */
333 @interface UITextView (iPhoneOS)
334 - (void) setTextSize:(float)size;
337 @implementation UITextView (iPhoneOS)
339 - (void) setTextSize:(float)size {
340 [self setFont:[[self font] fontWithSize:size]];
347 /* Information Dictionaries {{{ */
348 @interface NSMutableArray (Cydia)
349 - (void) addInfoDictionary:(NSDictionary *)info;
352 @implementation NSMutableArray (Cydia)
354 - (void) addInfoDictionary:(NSDictionary *)info {
355 [self addObject:info];
360 @interface NSMutableDictionary (Cydia)
361 - (void) addInfoDictionary:(NSDictionary *)info;
364 @implementation NSMutableDictionary (Cydia)
366 - (void) addInfoDictionary:(NSDictionary *)info {
367 NSString *bundle = [info objectForKey:@"CFBundleIdentifier"];
368 [self setObject:info forKey:bundle];
373 /* Pop Transitions {{{ */
374 @interface PopTransitionView : UITransitionView {
379 @implementation PopTransitionView
381 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
382 if (from != nil && to == nil)
383 [self removeFromSuperview];
388 @implementation UIView (PopUpView)
390 - (void) popFromSuperviewAnimated:(BOOL)animated {
391 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
394 - (void) popSubview:(UIView *)view {
395 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
396 [transition setDelegate:transition];
397 [self addSubview:transition];
399 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
400 [transition transition:UITransitionNone toView:blank];
401 [transition transition:UITransitionPushFromBottom toView:view];
407 #define lprintf(args...) fprintf(stderr, args)
410 #define TraceLogging (1 && !ForRelease)
411 #define HistogramInsertionSort (0 && !ForRelease)
412 #define ProfileTimes (0 && !ForRelease)
413 #define ForSaurik (0 && !ForRelease)
414 #define LogBrowser (1 && !ForRelease)
415 #define TrackResize (0 && !ForRelease)
416 #define ManualRefresh (1 && !ForRelease)
417 #define ShowInternals (0 && !ForRelease)
418 #define IgnoreInstall (0 && !ForRelease)
419 #define RecycleWebViews 0
420 #define AlwaysReload (1 && !ForRelease)
424 #define _trace(args...)
429 #define _profile(name) {
432 #define PrintTimes() do {} while (false)
436 typedef uint32_t (*SKRadixFunction)(id, void *);
438 @interface NSMutableArray (Radix)
439 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
440 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
448 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
449 struct RadixItem_ *lhs(swap), *rhs(swap + count);
451 static const size_t width = 32;
452 static const size_t bits = 11;
453 static const size_t slots = 1 << bits;
454 static const size_t passes = (width + (bits - 1)) / bits;
456 size_t *hist(new size_t[slots]);
458 for (size_t pass(0); pass != passes; ++pass) {
459 memset(hist, 0, sizeof(size_t) * slots);
461 for (size_t i(0); i != count; ++i) {
462 uint32_t key(lhs[i].key);
464 key &= _not(uint32_t) >> width - bits;
469 for (size_t i(0); i != slots; ++i) {
470 size_t local(offset);
475 for (size_t i(0); i != count; ++i) {
476 uint32_t key(lhs[i].key);
478 key &= _not(uint32_t) >> width - bits;
479 rhs[hist[key]++] = lhs[i];
482 RadixItem_ *tmp(lhs);
489 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
490 for (size_t i(0); i != count; ++i)
491 [values addObject:[self objectAtIndex:lhs[i].index]];
492 [self setArray:values];
497 @implementation NSMutableArray (Radix)
499 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
500 size_t count([self count]);
505 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
506 [invocation setSelector:selector];
507 [invocation setArgument:&object atIndex:2];
509 /* XXX: this is an unsafe optimization of doomy hell */
510 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
511 _assert(method != NULL);
512 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
513 _assert(imp != NULL);
516 struct RadixItem_ *swap(new RadixItem_[count * 2]);
518 for (size_t i(0); i != count; ++i) {
519 RadixItem_ &item(swap[i]);
522 id object([self objectAtIndex:i]);
525 [invocation setTarget:object];
527 [invocation getReturnValue:&item.key];
529 item.key = imp(object, selector, object);
533 RadixSort_(self, count, swap);
536 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
537 size_t count([self count]);
538 struct RadixItem_ *swap(new RadixItem_[count * 2]);
540 for (size_t i(0); i != count; ++i) {
541 RadixItem_ &item(swap[i]);
544 id object([self objectAtIndex:i]);
545 item.key = function(object, argument);
548 RadixSort_(self, count, swap);
553 /* Insertion Sort {{{ */
555 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
556 const char *ptr = (const char *)list;
558 CFIndex half = count / 2;
559 const char *probe = ptr + elementSize * half;
560 CFComparisonResult cr = comparator(element, probe, context);
561 if (0 == cr) return (probe - (const char *)list) / elementSize;
562 ptr = (cr < 0) ? ptr : probe + elementSize;
563 count = (cr < 0) ? half : (half + (count & 1) - 1);
565 return (ptr - (const char *)list) / elementSize;
568 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
569 const char *ptr = (const char *)list;
571 CFIndex half = count / 2;
572 const char *probe = ptr + elementSize * half;
573 CFComparisonResult cr = comparator(element, probe, context);
574 if (0 == cr) return (probe - (const char *)list) / elementSize;
575 ptr = (cr < 0) ? ptr : probe + elementSize;
576 count = (cr < 0) ? half : (half + (count & 1) - 1);
578 return (ptr - (const char *)list) / elementSize;
581 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
582 if (range.length == 0)
584 const void **values(new const void *[range.length]);
585 CFArrayGetValues(array, range, values);
587 #if HistogramInsertionSort
588 uint32_t total(0), *offsets(new uint32_t[range.length]);
591 for (CFIndex index(1); index != range.length; ++index) {
592 const void *value(values[index]);
593 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
594 CFIndex correct(index);
595 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
598 if (correct != index) {
599 size_t offset(index - correct);
600 #if HistogramInsertionSort
604 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
606 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
607 values[correct] = value;
611 CFArrayReplaceValues(array, range, values, range.length);
614 #if HistogramInsertionSort
615 for (CFIndex index(0); index != range.length; ++index)
616 if (offsets[index] != 0)
617 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
618 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
625 /* Apple Bug Fixes {{{ */
626 @implementation UIWebDocumentView (Cydia)
628 - (void) _setScrollerOffset:(CGPoint)offset {
629 UIScroller *scroller([self _scroller]);
631 CGSize size([scroller contentSize]);
632 CGSize bounds([scroller bounds].size);
635 max.x = size.width - bounds.width;
636 max.y = size.height - bounds.height;
644 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
645 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
647 [scroller setOffset:offset];
654 kUIControlEventMouseDown = 1 << 0,
655 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
656 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
657 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
658 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
659 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
660 } UIControlEventMasks;
662 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
663 size_t length([self length] - state->state);
666 else if (length > count)
668 for (size_t i(0); i != length; ++i)
669 objects[i] = [self item:state->state++];
670 state->itemsPtr = objects;
671 state->mutationsPtr = (unsigned long *) self;
675 @interface NSString (UIKit)
676 - (NSString *) stringByAddingPercentEscapes;
677 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
680 @interface NSString (Cydia)
681 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
682 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
683 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
684 - (NSComparisonResult) compareByPath:(NSString *)other;
685 - (NSString *) stringByCachingURLWithCurrentCDN;
686 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
689 @implementation NSString (Cydia)
691 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
692 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
695 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
696 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
697 memcpy(data, bytes, length);
698 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
701 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
702 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
705 - (NSComparisonResult) compareByPath:(NSString *)other {
706 NSString *prefix = [self commonPrefixWithString:other options:0];
707 size_t length = [prefix length];
709 NSRange lrange = NSMakeRange(length, [self length] - length);
710 NSRange rrange = NSMakeRange(length, [other length] - length);
712 lrange = [self rangeOfString:@"/" options:0 range:lrange];
713 rrange = [other rangeOfString:@"/" options:0 range:rrange];
715 NSComparisonResult value;
717 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
718 value = NSOrderedSame;
719 else if (lrange.location == NSNotFound)
720 value = NSOrderedAscending;
721 else if (rrange.location == NSNotFound)
722 value = NSOrderedDescending;
724 value = NSOrderedSame;
726 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
727 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
728 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
729 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
731 NSComparisonResult result = [lpath compare:rpath];
732 return result == NSOrderedSame ? value : result;
735 - (NSString *) stringByCachingURLWithCurrentCDN {
737 stringByReplacingOccurrencesOfString:@"://"
738 withString:@"://ne.edgecastcdn.net/8003A4/"
740 /* XXX: this is somewhat inaccurate */
741 range:NSMakeRange(0, 10)
745 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
746 return [(id)CFURLCreateStringByAddingPercentEscapes(
751 kCFStringEncodingUTF8
763 _finline void clear_() {
764 if (cache_ != NULL) {
771 _finline bool empty() const {
775 _finline size_t size() const {
779 _finline char *data() const {
783 _finline void clear() {
788 _finline CYString() :
795 _finline ~CYString() {
799 void operator =(const CYString &rhs) {
803 if (rhs.cache_ == nil)
806 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
809 void set(apr_pool_t *pool, const char *data, size_t size) {
815 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
816 memcpy(temp, data, size);
823 _finline void set(apr_pool_t *pool, const char *data) {
824 set(pool, data, data == NULL ? 0 : strlen(data));
827 _finline void set(apr_pool_t *pool, const std::string &rhs) {
828 set(pool, rhs.data(), rhs.size());
831 bool operator ==(const CYString &rhs) const {
832 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
835 operator CFStringRef() {
836 if (cache_ == NULL) {
839 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
843 _finline operator id() {
844 return (NSString *) static_cast<CFStringRef>(*this);
849 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
852 struct NSStringMapHash :
853 std::unary_function<NSString *, size_t>
855 _finline size_t operator ()(NSString *value) const {
856 return CFStringHashNSString((CFStringRef) value);
860 struct NSStringMapLess :
861 std::binary_function<NSString *, NSString *, bool>
863 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
864 return [lhs compare:rhs] == NSOrderedAscending;
868 struct NSStringMapEqual :
869 std::binary_function<NSString *, NSString *, bool>
871 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
872 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
873 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
874 //[lhs isEqualToString:rhs];
878 /* Perl-Compatible RegEx {{{ */
888 Pcre(const char *regex) :
893 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
896 lprintf("%d:%s\n", offset, error);
900 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
901 matches_ = new int[(capture_ + 1) * 3];
909 NSString *operator [](size_t match) {
910 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
913 bool operator ()(NSString *data) {
914 // XXX: length is for characters, not for bytes
915 return operator ()([data UTF8String], [data length]);
918 bool operator ()(const char *data, size_t size) {
920 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
924 /* Mime Addresses {{{ */
925 @interface Address : NSObject {
931 - (NSString *) address;
933 - (void) setAddress:(NSString *)address;
935 + (Address *) addressWithString:(NSString *)string;
936 - (Address *) initWithString:(NSString *)string;
939 @implementation Address
948 - (NSString *) name {
952 - (NSString *) address {
956 - (void) setAddress:(NSString *)address {
958 [address_ autorelease];
962 address_ = [address retain];
965 + (Address *) addressWithString:(NSString *)string {
966 return [[[Address alloc] initWithString:string] autorelease];
969 + (NSArray *) _attributeKeys {
970 return [NSArray arrayWithObjects:@"address", @"name", nil];
973 - (NSArray *) attributeKeys {
974 return [[self class] _attributeKeys];
977 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
978 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
981 - (Address *) initWithString:(NSString *)string {
982 if ((self = [super init]) != nil) {
983 const char *data = [string UTF8String];
984 size_t size = [string length];
986 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
988 if (address_r(data, size)) {
989 name_ = [address_r[1] retain];
990 address_ = [address_r[2] retain];
992 name_ = [string retain];
1000 /* CoreGraphics Primitives {{{ */
1011 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1014 Set(space, red, green, blue, alpha);
1019 CGColorRelease(color_);
1026 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1028 float color[] = {red, green, blue, alpha};
1029 color_ = CGColorCreate(space, color);
1032 operator CGColorRef() {
1038 extern "C" void UISetColor(CGColorRef color);
1040 /* Random Global Variables {{{ */
1041 static const int PulseInterval_ = 50000;
1042 static const int ButtonBarHeight_ = 48;
1043 static const float KeyboardTime_ = 0.3f;
1045 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1046 #define NotifyConfig_ "/etc/notify.conf"
1048 static bool Queuing_;
1050 static CGColor Blue_;
1051 static CGColor Blueish_;
1052 static CGColor Black_;
1053 static CGColor Off_;
1054 static CGColor White_;
1055 static CGColor Gray_;
1056 static CGColor Green_;
1057 static CGColor Purple_;
1058 static CGColor Purplish_;
1060 static UIColor *InstallingColor_;
1061 static UIColor *RemovingColor_;
1063 static NSString *App_;
1064 static NSString *Home_;
1065 static BOOL Sounds_Keyboard_;
1067 static BOOL Advanced_;
1068 static BOOL Loaded_;
1069 static BOOL Ignored_;
1071 static UIFont *Font12_;
1072 static UIFont *Font12Bold_;
1073 static UIFont *Font14_;
1074 static UIFont *Font18Bold_;
1075 static UIFont *Font22Bold_;
1077 static const char *Machine_ = NULL;
1078 static const NSString *UniqueID_ = nil;
1079 static const NSString *Build_ = nil;
1080 static const NSString *Product_ = nil;
1081 static const NSString *Safari_ = nil;
1083 CFLocaleRef Locale_;
1084 NSArray *Languages_;
1085 CGColorSpaceRef space_;
1090 static NSDictionary *SectionMap_;
1091 static NSMutableDictionary *Metadata_;
1092 static _transient NSMutableDictionary *Settings_;
1093 static _transient NSString *Role_;
1094 static _transient NSMutableDictionary *Packages_;
1095 static _transient NSMutableDictionary *Sections_;
1096 static _transient NSMutableDictionary *Sources_;
1097 static bool Changed_;
1098 static NSDate *now_;
1101 static NSMutableArray *Documents_;
1104 NSString *GetLastUpdate() {
1105 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1108 return UCLocalize("NEVER_OR_UNKNOWN");
1110 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1111 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1113 CFRelease(formatter);
1115 return [(NSString *) formatted autorelease];
1118 /* Display Helpers {{{ */
1119 inline float Interpolate(float begin, float end, float fraction) {
1120 return (end - begin) * fraction + begin;
1123 /* XXX: localize this! */
1124 NSString *SizeString(double size) {
1125 bool negative = size < 0;
1130 while (size > 1024) {
1135 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1137 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1140 static _finline CFStringRef CFCString(const char *value) {
1141 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1144 const char *StripVersion_(const char *version) {
1145 const char *colon(strchr(version, ':'));
1147 version = colon + 1;
1151 CFStringRef StripVersion(const char *version) {
1152 const char *colon(strchr(version, ':'));
1154 version = colon + 1;
1155 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1157 return CFCString(version);
1160 NSString *LocalizeSection(NSString *section) {
1161 static Pcre title_r("^(.*?) \\((.*)\\)$");
1162 if (title_r(section)) {
1163 NSString *parent(title_r[1]);
1164 NSString *child(title_r[2]);
1166 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1167 LocalizeSection(parent),
1168 LocalizeSection(child)
1172 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1175 NSString *Simplify(NSString *title) {
1176 const char *data = [title UTF8String];
1177 size_t size = [title length];
1179 static Pcre square_r("^\\[(.*)\\]$");
1180 if (square_r(data, size))
1181 return Simplify(square_r[1]);
1183 static Pcre paren_r("^\\((.*)\\)$");
1184 if (paren_r(data, size))
1185 return Simplify(paren_r[1]);
1187 static Pcre title_r("^(.*?) \\((.*)\\)$");
1188 if (title_r(data, size))
1189 return Simplify(title_r[1]);
1195 bool isSectionVisible(NSString *section) {
1196 NSDictionary *metadata([Sections_ objectForKey:section]);
1197 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1198 return hidden == nil || ![hidden boolValue];
1201 /* Delegate Prototypes {{{ */
1205 @interface NSObject (ProgressDelegate)
1208 @implementation NSObject(ProgressDelegate)
1210 - (void) _setProgressError:(NSArray *)args {
1211 [self performSelector:@selector(setProgressError:forPackage:)
1212 withObject:[args objectAtIndex:0]
1213 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1219 @protocol ProgressDelegate
1220 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1221 - (void) setProgressTitle:(NSString *)title;
1222 - (void) setProgressPercent:(float)percent;
1223 - (void) startProgress;
1224 - (void) addProgressOutput:(NSString *)output;
1225 - (bool) isCancelling:(size_t)received;
1228 @protocol ConfigurationDelegate
1229 - (void) repairWithSelector:(SEL)selector;
1230 - (void) setConfigurationData:(NSString *)data;
1235 @protocol CydiaDelegate
1236 - (void) setPackageView:(PackageView *)view;
1237 - (void) clearPackage:(Package *)package;
1238 - (void) installPackage:(Package *)package;
1239 - (void) removePackage:(Package *)package;
1240 - (void) slideUp:(UIActionSheet *)alert;
1241 - (void) distUpgrade;
1242 - (void) updateData;
1244 - (void) askForSettings;
1245 - (UIProgressHUD *) addProgressHUD;
1246 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1247 - (RVPage *) pageForPackage:(NSString *)name;
1248 - (PackageView *) packageView;
1252 /* Status Delegation {{{ */
1254 public pkgAcquireStatus
1257 _transient NSObject<ProgressDelegate> *delegate_;
1265 void setDelegate(id delegate) {
1266 delegate_ = delegate;
1269 virtual bool MediaChange(std::string media, std::string drive) {
1273 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1276 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1277 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1278 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1281 virtual void Done(pkgAcquire::ItemDesc &item) {
1284 virtual void Fail(pkgAcquire::ItemDesc &item) {
1286 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1287 item.Owner->Status == pkgAcquire::Item::StatDone
1291 std::string &error(item.Owner->ErrorText);
1295 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1296 NSArray *fields([description componentsSeparatedByString:@" "]);
1297 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1299 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1300 withObject:[NSArray arrayWithObjects:
1301 [NSString stringWithUTF8String:error.c_str()],
1308 virtual bool Pulse(pkgAcquire *Owner) {
1309 bool value = pkgAcquireStatus::Pulse(Owner);
1312 double(CurrentBytes + CurrentItems) /
1313 double(TotalBytes + TotalItems)
1316 [delegate_ setProgressPercent:percent];
1317 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1320 virtual void Start() {
1321 [delegate_ startProgress];
1324 virtual void Stop() {
1328 /* Progress Delegation {{{ */
1333 _transient id<ProgressDelegate> delegate_;
1336 virtual void Update() {
1337 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1338 [delegate_ setProgressPercent:(Percent / 100)];*/
1347 void setDelegate(id delegate) {
1348 delegate_ = delegate;
1351 virtual void Done() {
1352 //[delegate_ setProgressPercent:1];
1357 /* Database Interface {{{ */
1358 typedef std::map< unsigned long, _H<Source> > SourceMap;
1360 @interface Database : NSObject {
1366 pkgCacheFile cache_;
1367 pkgDepCache::Policy *policy_;
1368 pkgRecords *records_;
1369 pkgProblemResolver *resolver_;
1370 pkgAcquire *fetcher_;
1372 SPtr<pkgPackageManager> manager_;
1373 pkgSourceList *list_;
1376 NSMutableArray *packages_;
1378 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1387 + (Database *) sharedInstance;
1390 - (void) _readCydia:(NSNumber *)fd;
1391 - (void) _readStatus:(NSNumber *)fd;
1392 - (void) _readOutput:(NSNumber *)fd;
1396 - (Package *) packageWithName:(NSString *)name;
1398 - (pkgCacheFile &) cache;
1399 - (pkgDepCache::Policy *) policy;
1400 - (pkgRecords *) records;
1401 - (pkgProblemResolver *) resolver;
1402 - (pkgAcquire &) fetcher;
1403 - (pkgSourceList &) list;
1404 - (NSArray *) packages;
1405 - (NSArray *) sources;
1406 - (void) reloadData;
1414 - (NSString *) updateWithStatus:(Status &)status;
1416 - (void) setDelegate:(id)delegate;
1417 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1421 /* Source Class {{{ */
1422 @interface Source : NSObject {
1423 CYString depiction_;
1424 CYString description_;
1430 CYString distribution_;
1436 CYString defaultIcon_;
1438 NSDictionary *record_;
1442 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1444 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1446 - (NSString *) depictionForPackage:(NSString *)package;
1447 - (NSString *) supportForPackage:(NSString *)package;
1449 - (NSDictionary *) record;
1453 - (NSString *) distribution;
1454 - (NSString *) type;
1456 - (NSString *) host;
1458 - (NSString *) name;
1459 - (NSString *) description;
1460 - (NSString *) label;
1461 - (NSString *) origin;
1462 - (NSString *) version;
1464 - (NSString *) defaultIcon;
1468 @implementation Source
1472 distribution_.clear();
1475 description_.clear();
1481 defaultIcon_.clear();
1483 if (record_ != nil) {
1499 + (NSArray *) _attributeKeys {
1500 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1503 - (NSArray *) attributeKeys {
1504 return [[self class] _attributeKeys];
1507 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1508 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1511 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1514 trusted_ = index->IsTrusted();
1516 uri_.set(pool, index->GetURI());
1517 distribution_.set(pool, index->GetDist());
1518 type_.set(pool, index->GetType());
1520 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1521 if (dindex != NULL) {
1523 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1526 pkgTagFile tags(&fd);
1528 pkgTagSection section;
1535 {"default-icon", &defaultIcon_},
1536 {"depiction", &depiction_},
1537 {"description", &description_},
1539 {"origin", &origin_},
1540 {"support", &support_},
1541 {"version", &version_},
1544 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1545 const char *start, *end;
1547 if (section.Find(names[i].name_, start, end)) {
1548 CYString &value(*names[i].value_);
1549 value.set(pool, start, end - start);
1555 record_ = [Sources_ objectForKey:[self key]];
1557 record_ = [record_ retain];
1559 host_ = [[[[NSURL URLWithString:uri_] host] lowercaseString] retain];
1562 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1563 if ((self = [super init]) != nil) {
1564 [self setMetaIndex:index inPool:pool];
1568 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1569 NSDictionary *lhr = [self record];
1570 NSDictionary *rhr = [source record];
1573 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1575 NSString *lhs = [self name];
1576 NSString *rhs = [source name];
1578 if ([lhs length] != 0 && [rhs length] != 0) {
1579 unichar lhc = [lhs characterAtIndex:0];
1580 unichar rhc = [rhs characterAtIndex:0];
1582 if (isalpha(lhc) && !isalpha(rhc))
1583 return NSOrderedAscending;
1584 else if (!isalpha(lhc) && isalpha(rhc))
1585 return NSOrderedDescending;
1588 return [lhs compare:rhs options:LaxCompareOptions_];
1591 - (NSString *) depictionForPackage:(NSString *)package {
1592 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1595 - (NSString *) supportForPackage:(NSString *)package {
1596 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1599 - (NSDictionary *) record {
1607 - (NSString *) uri {
1611 - (NSString *) distribution {
1612 return distribution_;
1615 - (NSString *) type {
1619 - (NSString *) key {
1620 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1623 - (NSString *) host {
1627 - (NSString *) name {
1628 return origin_.empty() ? host_ : origin_;
1631 - (NSString *) description {
1632 return description_;
1635 - (NSString *) label {
1636 return label_.empty() ? host_ : label_;
1639 - (NSString *) origin {
1643 - (NSString *) version {
1647 - (NSString *) defaultIcon {
1648 return defaultIcon_;
1653 /* Relationship Class {{{ */
1654 @interface Relationship : NSObject {
1659 - (NSString *) type;
1661 - (NSString *) name;
1665 @implementation Relationship
1673 - (NSString *) type {
1681 - (NSString *) name {
1688 /* Package Class {{{ */
1689 @interface Package : NSObject {
1693 pkgCache::VerIterator version_;
1694 pkgCache::PkgIterator iterator_;
1695 _transient Database *database_;
1696 pkgCache::VerFileIterator file_;
1703 NSString *section$_;
1708 CYString installed_;
1714 CYString depiction_;
1724 NSMutableArray *tags_;
1727 NSArray *relationships_;
1729 NSMutableDictionary *metadata_;
1730 _transient NSDate *firstSeen_;
1731 _transient NSDate *lastSeen_;
1735 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1736 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1738 - (pkgCache::PkgIterator) iterator;
1741 - (NSString *) section;
1742 - (NSString *) simpleSection;
1744 - (NSString *) longSection;
1745 - (NSString *) shortSection;
1749 - (Address *) maintainer;
1751 - (NSString *) longDescription;
1752 - (NSString *) shortDescription;
1755 - (NSMutableDictionary *) metadata;
1757 - (BOOL) subscribed;
1760 - (NSString *) latest;
1761 - (NSString *) installed;
1762 - (BOOL) uninstalled;
1765 - (BOOL) upgradableAndEssential:(BOOL)essential;
1768 - (BOOL) unfiltered;
1772 - (BOOL) halfConfigured;
1773 - (BOOL) halfInstalled;
1775 - (NSString *) mode;
1778 - (NSString *) name;
1780 - (NSString *) homepage;
1781 - (NSString *) depiction;
1782 - (Address *) author;
1784 - (NSString *) support;
1786 - (NSArray *) files;
1787 - (NSArray *) relationships;
1788 - (NSArray *) warnings;
1789 - (NSArray *) applications;
1791 - (Source *) source;
1792 - (NSString *) role;
1794 - (BOOL) matches:(NSString *)text;
1796 - (bool) hasSupportingRole;
1797 - (BOOL) hasTag:(NSString *)tag;
1798 - (NSString *) primaryPurpose;
1799 - (NSArray *) purposes;
1800 - (bool) isCommercial;
1802 - (CYString &) cyname;
1804 - (uint32_t) compareBySection:(NSArray *)sections;
1806 - (uint32_t) compareForChanges;
1811 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1812 - (bool) isInstalledAndVisible:(NSNumber *)number;
1813 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1814 - (bool) isVisibleInSource:(Source *)source;
1818 uint32_t PackageChangesRadix(Package *self, void *) {
1823 uint32_t timestamp : 30;
1824 uint32_t ignored : 1;
1825 uint32_t upgradable : 1;
1829 bool upgradable([self upgradableAndEssential:YES]);
1830 value.bits.upgradable = upgradable ? 1 : 0;
1833 value.bits.timestamp = 0;
1834 value.bits.ignored = [self ignored] ? 0 : 1;
1835 value.bits.upgradable = 1;
1837 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1838 value.bits.ignored = 0;
1839 value.bits.upgradable = 0;
1842 return _not(uint32_t) - value.key;
1845 _finline static void Stifle(uint8_t &value) {
1848 uint32_t PackagePrefixRadix(Package *self, void *context) {
1849 size_t offset(reinterpret_cast<size_t>(context));
1850 CYString &name([self cyname]);
1852 size_t size(name.size());
1855 char *text(name.data());
1858 if (!isdigit(text[0]))
1862 while (size != digits && isdigit(text[digits]))
1872 if (offset == 0 && zeros != 0) {
1873 memset(data, '0', zeros);
1874 memcpy(data + zeros, text, 4 - zeros);
1876 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1877 if (size <= offset - zeros)
1880 text += offset - zeros;
1881 size -= offset - zeros;
1884 memcpy(data, text, 4);
1886 memcpy(data, text, size);
1887 memset(data + size, 0, 4 - size);
1890 for (size_t i(0); i != 4; ++i)
1891 if (isalpha(data[i]))
1896 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1898 /* XXX: ntohl may be more honest */
1899 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1902 CYString &(*PackageName)(Package *self, SEL sel);
1904 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1905 _profile(PackageNameCompare)
1906 CYString &lhi(PackageName(lhs, @selector(cyname)));
1907 CYString &rhi(PackageName(rhs, @selector(cyname)));
1908 CFStringRef lhn(lhi), rhn(rhi);
1910 _profile(PackageNameCompare$NumbersLast)
1911 if (!lhi.empty() && !rhi.empty()) {
1912 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1913 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1914 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1915 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1916 return lha ? NSOrderedAscending : NSOrderedDescending;
1920 CFIndex length = CFStringGetLength(lhn);
1922 _profile(PackageNameCompare$Compare)
1923 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1928 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1929 return PackageNameCompare(*lhs, *rhs, context);
1932 struct PackageNameOrdering :
1933 std::binary_function<Package *, Package *, bool>
1935 _finline bool operator ()(Package *lhs, Package *rhs) const {
1936 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1940 @implementation Package
1942 - (NSString *) description {
1943 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1949 if (section$_ != nil)
1950 [section$_ release];
1955 if (sponsor$_ != nil)
1956 [sponsor$_ release];
1957 if (author$_ != nil)
1964 if (relationships_ != nil)
1965 [relationships_ release];
1966 if (metadata_ != nil)
1967 [metadata_ release];
1972 + (NSString *) webScriptNameForSelector:(SEL)selector {
1973 if (selector == @selector(hasTag:))
1979 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1980 return [self webScriptNameForSelector:selector] == nil;
1983 + (NSArray *) _attributeKeys {
1984 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];
1987 - (NSArray *) attributeKeys {
1988 return [[self class] _attributeKeys];
1991 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1992 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2002 _profile(Package$parse)
2003 pkgRecords::Parser *parser;
2005 _profile(Package$parse$Lookup)
2006 parser = &[database_ records]->Lookup(file_);
2011 _profile(Package$parse$Find)
2017 {"depiction", &depiction_},
2018 {"homepage", &homepage_},
2019 {"website", &website},
2020 {"support", &support_},
2021 {"sponsor", &sponsor_},
2022 {"author", &author_},
2025 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2026 const char *start, *end;
2028 if (parser->Find(names[i].name_, start, end)) {
2029 CYString &value(*names[i].value_);
2030 _profile(Package$parse$Value)
2031 value.set(pool_, start, end - start);
2037 _profile(Package$parse$Tagline)
2038 const char *start, *end;
2039 if (parser->ShortDesc(start, end)) {
2040 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2043 while (stop != start && stop[-1] == '\r')
2045 tagline_.set(pool_, start, stop - start);
2049 _profile(Package$parse$Retain)
2050 if (!homepage_.empty())
2051 homepage_ = website;
2052 if (homepage_ == depiction_)
2058 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2059 if ((self = [super init]) != nil) {
2060 _profile(Package$initWithVersion)
2061 @synchronized (database) {
2062 era_ = [database era];
2066 iterator_ = version.ParentPkg();
2067 database_ = database;
2069 _profile(Package$initWithVersion$Latest)
2070 latest_ = (NSString *) StripVersion(version_.VerStr());
2073 pkgCache::VerIterator current;
2074 _profile(Package$initWithVersion$Versions)
2075 current = iterator_.CurrentVer();
2077 installed_.set(pool_, StripVersion_(current.VerStr()));
2079 if (!version_.end())
2080 file_ = version_.FileList();
2082 pkgCache &cache([database_ cache]);
2083 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2087 _profile(Package$initWithVersion$Name)
2088 id_.set(pool_, iterator_.Name());
2089 name_.set(pool, iterator_.Display());
2093 _profile(Package$initWithVersion$Source)
2094 source_ = [database_ getSource:file_.File()];
2103 _profile(Package$initWithVersion$Tags)
2104 pkgCache::TagIterator tag(iterator_.TagList());
2106 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2108 const char *name(tag.Name());
2109 [tags_ addObject:(NSString *)CFCString(name)];
2110 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2111 role_ = (NSString *) CFCString(name + 6);
2112 if (visible_ && strncmp(name, "require::", 9) == 0 && (
2117 } while (!tag.end());
2121 bool changed(false);
2122 NSString *key([id_ lowercaseString]);
2124 _profile(Package$initWithVersion$Metadata)
2125 metadata_ = [Packages_ objectForKey:key];
2127 if (metadata_ == nil) {
2130 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2131 firstSeen_, @"FirstSeen",
2132 latest_, @"LastVersion",
2137 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2138 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2140 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2141 subscribed_ = [subscribed boolValue];
2143 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2145 if (firstSeen_ == nil) {
2146 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2147 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2151 if (version == nil) {
2152 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2155 if (![version isEqualToString:latest_]) {
2156 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2158 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2163 metadata_ = [metadata_ retain];
2166 [Packages_ setObject:metadata_ forKey:key];
2171 _profile(Package$initWithVersion$Section)
2172 section_.set(pool_, iterator_.Section());
2175 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2176 visible_ = visible_ && [self hasSupportingRole] && [self unfiltered];
2177 } _end } return self;
2180 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2181 pkgCache::VerIterator version;
2183 _profile(Package$packageWithIterator$GetCandidateVer)
2184 version = [database policy]->GetCandidateVer(iterator);
2190 return [[[Package alloc]
2191 initWithVersion:version
2198 - (pkgCache::PkgIterator) iterator {
2202 - (NSString *) section {
2203 if (section$_ == nil) {
2204 if (section_.empty())
2207 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2208 NSString *name(section_);
2211 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2212 if (NSString *rename = [value objectForKey:@"Rename"]) {
2217 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2221 - (NSString *) simpleSection {
2222 if (NSString *section = [self section])
2223 return Simplify(section);
2228 - (NSString *) longSection {
2229 return LocalizeSection([self section]);
2232 - (NSString *) shortSection {
2233 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2236 - (NSString *) uri {
2239 pkgIndexFile *index;
2240 pkgCache::PkgFileIterator file(file_.File());
2241 if (![database_ list].FindIndex(file, index))
2243 return [NSString stringWithUTF8String:iterator_->Path];
2244 //return [NSString stringWithUTF8String:file.Site()];
2245 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2249 - (Address *) maintainer {
2252 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2253 const std::string &maintainer(parser->Maintainer());
2254 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2258 return version_.end() ? 0 : version_->InstalledSize;
2261 - (NSString *) longDescription {
2264 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2265 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2267 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2268 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2269 if ([lines count] < 2)
2272 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2273 for (size_t i(1), e([lines count]); i != e; ++i) {
2274 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2275 [trimmed addObject:trim];
2278 return [trimmed componentsJoinedByString:@"\n"];
2281 - (NSString *) shortDescription {
2286 _profile(Package$index)
2287 CFStringRef name((CFStringRef) [self name]);
2288 if (CFStringGetLength(name) == 0)
2290 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2291 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2293 return toupper(character);
2297 - (NSMutableDictionary *) metadata {
2302 if (subscribed_ && lastSeen_ != nil)
2307 - (BOOL) subscribed {
2312 NSDictionary *metadata([self metadata]);
2313 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2314 return [ignored boolValue];
2319 - (NSString *) latest {
2323 - (NSString *) installed {
2327 - (BOOL) uninstalled {
2328 return installed_.empty();
2332 return !version_.end();
2335 - (BOOL) upgradableAndEssential:(BOOL)essential {
2336 _profile(Package$upgradableAndEssential)
2337 pkgCache::VerIterator current(iterator_.CurrentVer());
2339 return essential && essential_ && visible_;
2341 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2345 - (BOOL) essential {
2350 return [database_ cache][iterator_].InstBroken();
2353 - (BOOL) unfiltered {
2354 NSString *section([self section]);
2355 return section == nil || isSectionVisible(section);
2363 unsigned char current(iterator_->CurrentState);
2364 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2367 - (BOOL) halfConfigured {
2368 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2371 - (BOOL) halfInstalled {
2372 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2376 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2377 return state.Mode != pkgDepCache::ModeKeep;
2380 - (NSString *) mode {
2381 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2383 switch (state.Mode) {
2384 case pkgDepCache::ModeDelete:
2385 if ((state.iFlags & pkgDepCache::Purge) != 0)
2389 case pkgDepCache::ModeKeep:
2390 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2391 return @"REINSTALL";
2392 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2396 case pkgDepCache::ModeInstall:
2397 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2398 return @"REINSTALL";
2399 else*/ switch (state.Status) {
2401 return @"DOWNGRADE";
2407 return @"NEW_INSTALL";
2420 - (NSString *) name {
2421 return name_.empty() ? id_ : name_;
2424 - (UIImage *) icon {
2425 NSString *section = [self simpleSection];
2429 if ([icon_ hasPrefix:@"file:///"])
2430 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2431 if (icon == nil) if (section != nil)
2432 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2433 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2434 if ([dicon hasPrefix:@"file:///"])
2435 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2437 icon = [UIImage applicationImageNamed:@"unknown.png"];
2441 - (NSString *) homepage {
2445 - (NSString *) depiction {
2446 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2449 - (Address *) sponsor {
2450 if (sponsor$_ == nil) {
2451 if (sponsor_.empty())
2453 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2457 - (Address *) author {
2458 if (author$_ == nil) {
2459 if (author_.empty())
2461 author$_ = [[Address addressWithString:author_] retain];
2465 - (NSString *) support {
2466 return !support_.empty() ? support_ : [[self source] supportForPackage:id_];
2469 - (NSArray *) files {
2470 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2471 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2474 fin.open([path UTF8String]);
2479 while (std::getline(fin, line))
2480 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2485 - (NSArray *) relationships {
2486 return relationships_;
2489 - (NSArray *) warnings {
2490 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2491 const char *name(iterator_.Name());
2493 size_t length(strlen(name));
2494 if (length < 2) invalid:
2495 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2496 else for (size_t i(0); i != length; ++i)
2498 /* XXX: technically this is not allowed */
2499 (name[i] < 'A' || name[i] > 'Z') &&
2500 (name[i] < 'a' || name[i] > 'z') &&
2501 (name[i] < '0' || name[i] > '9') &&
2502 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2505 if (strcmp(name, "cydia") != 0) {
2507 bool _private = false;
2510 bool repository = [[self section] isEqualToString:@"Repositories"];
2512 if (NSArray *files = [self files])
2513 for (NSString *file in files)
2514 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2516 else if (!_private && [file isEqualToString:@"/private"])
2518 else if (!stash && [file isEqualToString:@"/var/stash"])
2521 /* XXX: this is not sensitive enough. only some folders are valid. */
2522 if (cydia && !repository)
2523 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2525 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2527 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2530 return [warnings count] == 0 ? nil : warnings;
2533 - (NSArray *) applications {
2534 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2536 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2538 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2539 if (NSArray *files = [self files])
2540 for (NSString *file in files)
2541 if (application_r(file)) {
2542 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2543 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2544 if ([id isEqualToString:me])
2547 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2549 display = application_r[1];
2551 NSString *bundle([file stringByDeletingLastPathComponent]);
2552 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2553 if (icon == nil || [icon length] == 0)
2555 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2557 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2558 [applications addObject:application];
2560 [application addObject:id];
2561 [application addObject:display];
2562 [application addObject:url];
2565 return [applications count] == 0 ? nil : applications;
2568 - (Source *) source {
2570 @synchronized (database_) {
2571 if ([database_ era] != era_ || file_.end())
2574 source_ = [database_ getSource:file_.File()];
2586 - (NSString *) role {
2590 - (BOOL) matches:(NSString *)text {
2596 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2597 if (range.location != NSNotFound)
2600 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2601 if (range.location != NSNotFound)
2604 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2605 if (range.location != NSNotFound)
2611 - (bool) hasSupportingRole {
2614 if ([role_ isEqualToString:@"enduser"])
2616 if ([Role_ isEqualToString:@"User"])
2618 if ([role_ isEqualToString:@"hacker"])
2620 if ([Role_ isEqualToString:@"Hacker"])
2622 if ([role_ isEqualToString:@"developer"])
2624 if ([Role_ isEqualToString:@"Developer"])
2629 - (BOOL) hasTag:(NSString *)tag {
2630 return tags_ == nil ? NO : [tags_ containsObject:tag];
2633 - (NSString *) primaryPurpose {
2634 for (NSString *tag in tags_)
2635 if ([tag hasPrefix:@"purpose::"])
2636 return [tag substringFromIndex:9];
2640 - (NSArray *) purposes {
2641 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2642 for (NSString *tag in tags_)
2643 if ([tag hasPrefix:@"purpose::"])
2644 [purposes addObject:[tag substringFromIndex:9]];
2645 return [purposes count] == 0 ? nil : purposes;
2648 - (bool) isCommercial {
2649 return [self hasTag:@"cydia::commercial"];
2652 - (CYString &) cyname {
2653 return name_.empty() ? id_ : name_;
2656 - (uint32_t) compareBySection:(NSArray *)sections {
2657 NSString *section([self section]);
2658 for (size_t i(0), e([sections count]); i != e; ++i) {
2659 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2663 return _not(uint32_t);
2666 - (uint32_t) compareForChanges {
2671 uint32_t timestamp : 30;
2672 uint32_t ignored : 1;
2673 uint32_t upgradable : 1;
2677 bool upgradable([self upgradableAndEssential:YES]);
2678 value.bits.upgradable = upgradable ? 1 : 0;
2681 value.bits.timestamp = 0;
2682 value.bits.ignored = [self ignored] ? 0 : 1;
2683 value.bits.upgradable = 1;
2685 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2686 value.bits.ignored = 0;
2687 value.bits.upgradable = 0;
2690 return _not(uint32_t) - value.key;
2694 pkgProblemResolver *resolver = [database_ resolver];
2695 resolver->Clear(iterator_);
2696 resolver->Protect(iterator_);
2700 pkgProblemResolver *resolver = [database_ resolver];
2701 resolver->Clear(iterator_);
2702 resolver->Protect(iterator_);
2703 pkgCacheFile &cache([database_ cache]);
2704 cache->MarkInstall(iterator_, false);
2705 pkgDepCache::StateCache &state((*cache)[iterator_]);
2706 if (!state.Install())
2707 cache->SetReInstall(iterator_, true);
2711 pkgProblemResolver *resolver = [database_ resolver];
2712 resolver->Clear(iterator_);
2713 resolver->Protect(iterator_);
2714 resolver->Remove(iterator_);
2715 [database_ cache]->MarkDelete(iterator_, true);
2718 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2719 _profile(Package$isUnfilteredAndSearchedForBy)
2722 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2723 value &= [self unfiltered];
2726 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2727 value &= [self matches:search];
2734 - (bool) isInstalledAndVisible:(NSNumber *)number {
2735 return (![number boolValue] || [self visible]) && ![self uninstalled];
2738 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2739 NSString *section = [self section];
2743 [self uninstalled] && (
2745 section == nil && [name length] == 0 ||
2746 [name isEqualToString:section]
2750 - (bool) isVisibleInSource:(Source *)source {
2751 return [self source] == source && [self visible];
2756 /* Section Class {{{ */
2757 @interface Section : NSObject {
2762 NSString *localized_;
2765 - (NSComparisonResult) compareByLocalized:(Section *)section;
2766 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2767 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2768 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2769 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2770 - (NSString *) name;
2777 - (void) addToCount;
2779 - (void) setCount:(size_t)count;
2780 - (NSString *) localized;
2784 @implementation Section
2788 if (localized_ != nil)
2789 [localized_ release];
2793 - (NSComparisonResult) compareByLocalized:(Section *)section {
2794 NSString *lhs(localized_);
2795 NSString *rhs([section localized]);
2797 /*if ([lhs length] != 0 && [rhs length] != 0) {
2798 unichar lhc = [lhs characterAtIndex:0];
2799 unichar rhc = [rhs characterAtIndex:0];
2801 if (isalpha(lhc) && !isalpha(rhc))
2802 return NSOrderedAscending;
2803 else if (!isalpha(lhc) && isalpha(rhc))
2804 return NSOrderedDescending;
2807 return [lhs compare:rhs options:LaxCompareOptions_];
2810 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2811 if ((self = [self initWithName:name localize:NO]) != nil) {
2812 if (localized != nil)
2813 localized_ = [localized retain];
2817 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2818 return [self initWithName:name row:0 localize:localize];
2821 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2822 if ((self = [super init]) != nil) {
2823 name_ = [name retain];
2827 localized_ = [LocalizeSection(name_) retain];
2831 /* XXX: localize the index thingees */
2832 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2833 if ((self = [super init]) != nil) {
2834 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2840 - (NSString *) name {
2860 - (void) addToCount {
2864 - (void) setCount:(size_t)count {
2868 - (NSString *) localized {
2876 static NSArray *Finishes_;
2878 /* Database Implementation {{{ */
2879 @implementation Database
2881 + (Database *) sharedInstance {
2882 static Database *instance;
2883 if (instance == nil)
2884 instance = [[Database alloc] init];
2894 NSRecycleZone(zone_);
2895 // XXX: malloc_destroy_zone(zone_);
2896 apr_pool_destroy(pool_);
2900 - (void) _readCydia:(NSNumber *)fd { _pooled
2901 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2902 std::istream is(&ib);
2905 static Pcre finish_r("^finish:([^:]*)$");
2907 while (std::getline(is, line)) {
2908 const char *data(line.c_str());
2909 size_t size = line.size();
2910 lprintf("C:%s\n", data);
2912 if (finish_r(data, size)) {
2913 NSString *finish = finish_r[1];
2914 int index = [Finishes_ indexOfObject:finish];
2915 if (index != INT_MAX && index > Finish_)
2923 - (void) _readStatus:(NSNumber *)fd { _pooled
2924 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2925 std::istream is(&ib);
2928 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2929 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2931 while (std::getline(is, line)) {
2932 const char *data(line.c_str());
2933 size_t size = line.size();
2934 lprintf("S:%s\n", data);
2936 if (conffile_r(data, size)) {
2937 [delegate_ setConfigurationData:conffile_r[1]];
2938 } else if (strncmp(data, "status: ", 8) == 0) {
2939 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2940 [delegate_ setProgressTitle:string];
2941 } else if (pmstatus_r(data, size)) {
2942 std::string type([pmstatus_r[1] UTF8String]);
2943 NSString *id = pmstatus_r[2];
2945 float percent([pmstatus_r[3] floatValue]);
2946 [delegate_ setProgressPercent:(percent / 100)];
2948 NSString *string = pmstatus_r[4];
2950 if (type == "pmerror")
2951 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2952 withObject:[NSArray arrayWithObjects:string, id, nil]
2955 else if (type == "pmstatus") {
2956 [delegate_ setProgressTitle:string];
2957 } else if (type == "pmconffile")
2958 [delegate_ setConfigurationData:string];
2959 else _assert(false);
2960 } else _assert(false);
2966 - (void) _readOutput:(NSNumber *)fd { _pooled
2967 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2968 std::istream is(&ib);
2971 while (std::getline(is, line)) {
2972 lprintf("O:%s\n", line.c_str());
2973 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2983 - (Package *) packageWithName:(NSString *)name {
2984 if (static_cast<pkgDepCache *>(cache_) == NULL)
2986 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2987 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2990 - (Database *) init {
2991 if ((self = [super init]) != nil) {
2998 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2999 apr_pool_create(&pool_, NULL);
3001 packages_ = [[NSMutableArray alloc] init];
3005 _assert(pipe(fds) != -1);
3008 _config->Set("APT::Keep-Fds::", cydiafd_);
3009 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3012 detachNewThreadSelector:@selector(_readCydia:)
3014 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3017 _assert(pipe(fds) != -1);
3021 detachNewThreadSelector:@selector(_readStatus:)
3023 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3026 _assert(pipe(fds) != -1);
3027 _assert(dup2(fds[0], 0) != -1);
3028 _assert(close(fds[0]) != -1);
3030 input_ = fdopen(fds[1], "a");
3032 _assert(pipe(fds) != -1);
3033 _assert(dup2(fds[1], 1) != -1);
3034 _assert(close(fds[1]) != -1);
3037 detachNewThreadSelector:@selector(_readOutput:)
3039 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3044 - (pkgCacheFile &) cache {
3048 - (pkgDepCache::Policy *) policy {
3052 - (pkgRecords *) records {
3056 - (pkgProblemResolver *) resolver {
3060 - (pkgAcquire &) fetcher {
3064 - (pkgSourceList &) list {
3068 - (NSArray *) packages {
3072 - (NSArray *) sources {
3073 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3074 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3075 [sources addObject:i->second];
3079 - (NSArray *) issues {
3080 if (cache_->BrokenCount() == 0)
3083 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3085 for (Package *package in packages_) {
3086 if (![package broken])
3088 pkgCache::PkgIterator pkg([package iterator]);
3090 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3091 [entry addObject:[package name]];
3092 [issues addObject:entry];
3094 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3098 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3099 pkgCache::DepIterator start;
3100 pkgCache::DepIterator end;
3101 dep.GlobOr(start, end); // ++dep
3103 if (!cache_->IsImportantDep(end))
3105 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3108 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3109 [entry addObject:failure];
3110 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3112 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
3113 [failure addObject:[package name]];
3115 pkgCache::PkgIterator target(start.TargetPkg());
3116 if (target->ProvidesList != 0)
3117 [failure addObject:@"?"];
3119 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3121 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3122 else if (!cache_[target].CandidateVerIter(cache_).end())
3123 [failure addObject:@"-"];
3124 else if (target->ProvidesList == 0)
3125 [failure addObject:@"!"];
3127 [failure addObject:@"%"];
3131 if (start.TargetVer() != 0)
3132 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3143 - (void) reloadData { _pooled
3144 @synchronized (self) {
3148 [packages_ removeAllObjects];
3174 apr_pool_clear(pool_);
3175 NSRecycleZone(zone_);
3177 int chk(creat("/tmp/cydia.chk", 0644));
3182 if (!cache_.Open(progress_, true)) {
3184 if (!_error->PopMessage(error))
3187 lprintf("cache_.Open():[%s]\n", error.c_str());
3189 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3190 [delegate_ repairWithSelector:@selector(configure)];
3191 else if (error == "The package lists or status file could not be parsed or opened.")
3192 [delegate_ repairWithSelector:@selector(update)];
3193 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3194 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3195 // else if (error == "The list of sources could not be read.")
3196 else _assert(false);
3202 unlink("/tmp/cydia.chk");
3204 now_ = [[NSDate date] retain];
3206 policy_ = new pkgDepCache::Policy();
3207 records_ = new pkgRecords(cache_);
3208 resolver_ = new pkgProblemResolver(cache_);
3209 fetcher_ = new pkgAcquire(&status_);
3212 list_ = new pkgSourceList();
3213 _assert(list_->ReadMainList());
3215 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3216 _assert(pkgApplyStatus(cache_));
3218 if (cache_->BrokenCount() != 0) {
3219 _assert(pkgFixBroken(cache_));
3220 _assert(cache_->BrokenCount() == 0);
3221 _assert(pkgMinimizeUpgrade(cache_));
3226 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3227 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3228 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3229 // XXX: this could be more intelligent
3230 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3231 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3233 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3240 /*std::vector<Package *> packages;
3241 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3242 [packages_ release];
3247 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3248 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3249 //packages.push_back(package);
3250 [packages_ addObject:package];
3254 /*if (packages.empty())
3255 packages_ = [[NSArray alloc] init];
3257 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3260 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3261 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3262 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3270 /*if (!packages.empty())
3271 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3272 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3274 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3276 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3278 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3284 - (void) configure {
3285 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3286 system([dpkg UTF8String]);
3294 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3295 _assert(!_error->PendingError());
3298 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3301 public pkgArchiveCleaner
3304 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3309 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3311 while (_error->PopMessage(error))
3312 lprintf("ArchiveCleaner: %s\n", error.c_str());
3317 pkgRecords records(cache_);
3319 lock_ = new FileFd();
3320 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3321 _assert(!_error->PendingError());
3324 // XXX: explain this with an error message
3325 _assert(list.ReadMainList());
3327 manager_ = (_system->CreatePM(cache_));
3328 _assert(manager_->GetArchives(fetcher_, &list, &records));
3329 _assert(!_error->PendingError());
3333 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3335 _assert(list.ReadMainList());
3336 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3337 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3340 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3345 bool failed = false;
3346 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3347 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3349 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3352 std::string uri = (*item)->DescURI();
3353 std::string error = (*item)->ErrorText;
3355 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3358 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3359 withObject:[NSArray arrayWithObjects:
3360 [NSString stringWithUTF8String:error.c_str()],
3372 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3374 if (_error->PendingError()) {
3379 if (result == pkgPackageManager::Failed) {
3384 if (result != pkgPackageManager::Completed) {
3389 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3391 _assert(list.ReadMainList());
3392 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3393 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3396 if (![before isEqualToArray:after])
3401 _assert(pkgDistUpgrade(cache_));
3405 [self updateWithStatus:status_];
3408 - (NSString *) updateWithStatus:(Status &)status {
3410 _assert(list.ReadMainList());
3413 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3415 if (_error->PendingError()) {
3417 if (!_error->PopMessage(error))
3420 return [NSString stringWithUTF8String:error.c_str()];
3423 pkgAcquire fetcher(&status);
3424 _assert(list.GetIndexes(&fetcher));
3426 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3427 bool failed = false;
3428 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3429 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3430 (*item)->Finished();
3434 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3435 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3436 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3439 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3446 - (void) setDelegate:(id)delegate {
3447 delegate_ = delegate;
3448 status_.setDelegate(delegate);
3449 progress_.setDelegate(delegate);
3452 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3453 SourceMap::const_iterator i(sources_.find(file->ID));
3454 return i == sources_.end() ? nil : i->second;
3460 /* PopUp Windows {{{ */
3461 @interface PopUpView : UIView {
3462 _transient id delegate_;
3463 UITransitionView *transition_;
3468 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3472 @implementation PopUpView
3475 [transition_ setDelegate:nil];
3476 [transition_ release];
3482 [transition_ transition:UITransitionPushFromTop toView:nil];
3485 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3486 if (from != nil && to == nil)
3487 [self removeFromSuperview];
3490 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3491 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3492 delegate_ = delegate;
3494 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3495 [self addSubview:transition_];
3497 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3499 [view addSubview:self];
3501 [transition_ setDelegate:self];
3503 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3504 [transition_ transition:UITransitionNone toView:blank];
3505 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3512 /* Confirmation View {{{ */
3513 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3514 if (!iterator.end())
3515 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3516 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3518 pkgCache::PkgIterator package(dep.TargetPkg());
3521 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3528 /* Web Scripting {{{ */
3529 @interface CydiaObject : NSObject {
3533 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3536 @implementation CydiaObject
3539 [indirect_ release];
3543 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3544 if ((self = [super init]) != nil) {
3545 indirect_ = [indirect retain];
3549 + (NSArray *) _attributeKeys {
3550 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3553 - (NSArray *) attributeKeys {
3554 return [[self class] _attributeKeys];
3557 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3558 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3561 - (NSString *) device {
3562 return [[UIDevice currentDevice] uniqueIdentifier];
3565 #if 0 // XXX: implement!
3566 - (NSString *) mac {
3567 if (![indirect_ promptForSensitive:@"Mac Address"])
3571 - (NSString *) serial {
3572 if (![indirect_ promptForSensitive:@"Serial #"])
3576 - (NSString *) firewire {
3577 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3581 - (NSString *) imei {
3582 if (![indirect_ promptForSensitive:@"IMEI"])
3587 + (NSString *) webScriptNameForSelector:(SEL)selector {
3588 if (selector == @selector(close))
3590 else if (selector == @selector(getPackageById:))
3591 return @"getPackageById";
3592 else if (selector == @selector(setAutoPopup:))
3593 return @"setAutoPopup";
3594 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3595 return @"setButtonImage";
3596 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3597 return @"setButtonTitle";
3598 else if (selector == @selector(setFinishHook:))
3599 return @"setFinishHook";
3600 else if (selector == @selector(setPopupHook:))
3601 return @"setPopupHook";
3602 else if (selector == @selector(setSpecial:))
3603 return @"setSpecial";
3604 else if (selector == @selector(setViewportWidth:))
3605 return @"setViewportWidth";
3606 else if (selector == @selector(supports:))
3608 else if (selector == @selector(stringWithFormat:arguments:))
3610 else if (selector == @selector(localizedStringForKey:value:table:))
3612 else if (selector == @selector(du:))
3614 else if (selector == @selector(statfs:))
3620 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3621 return [self webScriptNameForSelector:selector] == nil;
3624 - (BOOL) supports:(NSString *)feature {
3625 return [feature isEqualToString:@"window.open"];
3628 - (Package *) getPackageById:(NSString *)id {
3629 return [[Database sharedInstance] packageWithName:id];
3632 - (NSArray *) statfs:(NSString *)path {
3635 if (path == nil || statfs([path UTF8String], &stat) == -1)
3638 return [NSArray arrayWithObjects:
3639 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3640 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3641 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3645 - (NSNumber *) du:(NSString *)path {
3646 NSNumber *value(nil);
3649 _assert(pipe(fds) != -1);
3651 pid_t pid(ExecFork());
3653 _assert(dup2(fds[1], 1) != -1);
3654 _assert(close(fds[0]) != -1);
3655 _assert(close(fds[1]) != -1);
3656 /* XXX: this should probably not use du */
3657 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3662 _assert(close(fds[1]) != -1);
3664 if (FILE *du = fdopen(fds[0], "r")) {
3666 while (fgets(line, sizeof(line), du) != NULL) {
3667 size_t length(strlen(line));
3668 while (length != 0 && line[length - 1] == '\n')
3669 line[--length] = '\0';
3670 if (char *tab = strchr(line, '\t')) {
3672 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3677 } else _assert(close(fds[0]));
3681 if (waitpid(pid, &status, 0) == -1)
3684 else _assert(false);
3693 - (void) setAutoPopup:(BOOL)popup {
3694 [indirect_ setAutoPopup:popup];
3697 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3698 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3701 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3702 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3705 - (void) setSpecial:(id)function {
3706 [indirect_ setSpecial:function];
3709 - (void) setFinishHook:(id)function {
3710 [indirect_ setFinishHook:function];
3713 - (void) setPopupHook:(id)function {
3714 [indirect_ setPopupHook:function];
3717 - (void) setViewportWidth:(float)width {
3718 [indirect_ setViewportWidth:width];
3721 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3722 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3723 unsigned count([arguments count]);
3725 for (unsigned i(0); i != count; ++i)
3726 values[i] = [arguments objectAtIndex:i];
3727 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3730 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3731 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3733 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3739 @interface CydiaBrowserView : BrowserView {
3740 CydiaObject *cydia_;
3745 @implementation CydiaBrowserView
3752 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3753 [super webView:sender didClearWindowObject:window forFrame:frame];
3754 [window setValue:cydia_ forKey:@"cydia"];
3757 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3758 NSMutableURLRequest *copy = [request mutableCopy];
3760 if (Machine_ != NULL)
3761 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3762 if (UniqueID_ != nil)
3763 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
3766 [copy setValue:Role_ forHTTPHeaderField:@"X-Role"];
3771 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3772 if ((self = [super initWithBook:book]) != nil) {
3773 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3775 WebView *webview([webview_ webView]);
3777 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3778 NSString *application = package == nil ? @"Cydia" : [NSString
3779 stringWithFormat:@"Cydia/%@",
3783 if (Product_ != nil)
3784 application = [NSString stringWithFormat:@"%@ Version/%@", application, Product_];
3786 application = [NSString stringWithFormat:@"%@ Mobile/%@", application, Build_];
3788 application = [NSString stringWithFormat:@"%@ Safari/%@", application, Safari_];
3790 [webview setApplicationNameForUserAgent:application];
3796 @protocol ConfirmationViewDelegate
3802 @interface ConfirmationView : CydiaBrowserView {
3803 _transient Database *database_;
3804 UIActionSheet *essential_;
3811 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3815 @implementation ConfirmationView
3822 if (essential_ != nil)
3823 [essential_ release];
3829 [book_ popFromSuperviewAnimated:YES];
3832 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3833 NSString *context([sheet context]);
3835 if ([context isEqualToString:@"remove"]) {
3843 [delegate_ confirm];
3850 } else if ([context isEqualToString:@"unable"]) {
3854 [super alertSheet:sheet buttonClicked:button];
3857 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3858 [super webView:sender didClearWindowObject:window forFrame:frame];
3859 [window setValue:changes_ forKey:@"changes"];
3860 [window setValue:issues_ forKey:@"issues"];
3861 [window setValue:sizes_ forKey:@"sizes"];
3864 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3865 if ((self = [super initWithBook:book]) != nil) {
3866 database_ = database;
3868 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3869 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3870 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3871 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3872 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3876 pkgDepCache::Policy *policy([database_ policy]);
3878 pkgCacheFile &cache([database_ cache]);
3879 NSArray *packages = [database_ packages];
3880 for (Package *package in packages) {
3881 pkgCache::PkgIterator iterator = [package iterator];
3882 pkgDepCache::StateCache &state(cache[iterator]);
3884 NSString *name([package name]);
3886 if (state.NewInstall())
3887 [installing addObject:name];
3888 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3889 [reinstalling addObject:name];
3890 else if (state.Upgrade())
3891 [upgrading addObject:name];
3892 else if (state.Downgrade())
3893 [downgrading addObject:name];
3894 else if (state.Delete()) {
3895 if ([package essential])
3897 [removing addObject:name];
3900 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3901 substrate_ |= DepSubstrate(iterator.CurrentVer());
3906 else if (Advanced_ || true) {
3907 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
3909 essential_ = [[UIActionSheet alloc]
3910 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
3911 buttons:[NSArray arrayWithObjects:
3912 [NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")],
3913 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
3915 defaultButtonIndex:0
3921 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3923 [essential_ setBodyText:UCLocalize("REMOVING_ESSENTIALS_EX")];
3925 essential_ = [[UIActionSheet alloc]
3926 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
3927 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
3928 defaultButtonIndex:0
3933 [essential_ setBodyText:UCLocalize("UNABLE_TO_COMPLY_EX")];
3936 changes_ = [[NSArray alloc] initWithObjects:
3944 issues_ = [database_ issues];
3946 issues_ = [issues_ retain];
3948 sizes_ = [[NSArray alloc] initWithObjects:
3949 SizeString([database_ fetcher].FetchNeeded()),
3950 SizeString([database_ fetcher].PartialPresent()),
3951 SizeString([database_ cache]->UsrSize()),
3954 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3958 - (NSString *) backButtonTitle {
3959 return UCLocalize("CONFIRM");
3962 - (NSString *) leftButtonTitle {
3963 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
3966 - (id) rightButtonTitle {
3967 return issues_ != nil ? nil : [super rightButtonTitle];
3970 - (id) _rightButtonTitle {
3971 #if AlwaysReload || IgnoreInstall
3972 return [super _rightButtonTitle];
3974 return UCLocalize("CONFIRM");
3978 - (void) _leftButtonClicked {
3983 - (void) _rightButtonClicked {
3985 return [super _rightButtonClicked];
3987 if (essential_ != nil)
3988 [essential_ popupAlertAnimated:YES];
3992 [delegate_ confirm];
4000 /* Progress Data {{{ */
4001 @interface ProgressData : NSObject {
4007 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4014 @implementation ProgressData
4016 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4017 if ((self = [super init]) != nil) {
4018 selector_ = selector;
4038 /* Progress View {{{ */
4039 @interface ProgressView : UIView <
4040 ConfigurationDelegate,
4043 _transient Database *database_;
4045 UIView *background_;
4046 UITransitionView *transition_;
4048 UINavigationBar *navbar_;
4049 UIProgressBar *progress_;
4050 UITextView *output_;
4051 UITextLabel *status_;
4052 UIPushButton *close_;
4055 SHA1SumValue springlist_;
4056 SHA1SumValue notifyconf_;
4057 SHA1SumValue sandplate_;
4060 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
4062 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4063 - (void) setContentView:(UIView *)view;
4066 - (void) _retachThread;
4067 - (void) _detachNewThreadData:(ProgressData *)data;
4068 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4074 @protocol ProgressViewDelegate
4075 - (void) progressViewIsComplete:(ProgressView *)sender;
4078 @implementation ProgressView
4081 [transition_ setDelegate:nil];
4082 [navbar_ setDelegate:nil];
4085 if (background_ != nil)
4086 [background_ release];
4087 [transition_ release];
4090 [progress_ release];
4097 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
4098 if (bootstrap_ && from == overlay_ && to == view_)
4102 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4103 if ((self = [super initWithFrame:frame]) != nil) {
4104 database_ = database;
4105 delegate_ = delegate;
4107 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4108 [transition_ setDelegate:self];
4110 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4113 [overlay_ setBackgroundColor:[UIColor blackColor]];
4115 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4116 [background_ setBackgroundColor:[UIColor blackColor]];
4117 [self addSubview:background_];
4120 [self addSubview:transition_];
4122 CGSize navsize = [UINavigationBar defaultSize];
4123 CGRect navrect = {{0, 0}, navsize};
4125 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4126 [overlay_ addSubview:navbar_];
4128 [navbar_ setBarStyle:1];
4129 [navbar_ setDelegate:self];
4131 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4132 [navbar_ pushNavigationItem:navitem];
4134 CGRect bounds = [overlay_ bounds];
4135 CGSize prgsize = [UIProgressBar defaultSize];
4138 (bounds.size.width - prgsize.width) / 2,
4139 bounds.size.height - prgsize.height - 20
4142 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4143 [progress_ setStyle:0];
4145 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4147 bounds.size.height - prgsize.height - 50,
4148 bounds.size.width - 20,
4152 [status_ setColor:[UIColor whiteColor]];
4153 [status_ setBackgroundColor:[UIColor clearColor]];
4155 [status_ setCentersHorizontally:YES];
4156 //[status_ setFont:font];
4159 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4161 navrect.size.height + 20,
4162 bounds.size.width - 20,
4163 bounds.size.height - navsize.height - 62 - navrect.size.height
4167 //[output_ setTextFont:@"Courier New"];
4168 [output_ setTextSize:12];
4170 [output_ setTextColor:[UIColor whiteColor]];
4171 [output_ setBackgroundColor:[UIColor clearColor]];
4173 [output_ setMarginTop:0];
4174 [output_ setAllowsRubberBanding:YES];
4175 [output_ setEditable:NO];
4177 [overlay_ addSubview:output_];
4179 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4181 bounds.size.height - prgsize.height - 50,
4182 bounds.size.width - 20,
4186 [close_ setAutosizesToFit:NO];
4187 [close_ setDrawsShadow:YES];
4188 [close_ setStretchBackground:YES];
4189 [close_ setEnabled:YES];
4191 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4192 [close_ setTitleFont:bold];
4194 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
4195 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4196 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4200 - (void) setContentView:(UIView *)view {
4201 view_ = [view retain];
4204 - (void) resetView {
4205 [transition_ transition:6 toView:view_];
4208 - (void) _checkError {
4209 if (_error->PendingError()) {
4211 if (!_error->PopMessage(error))
4214 UIActionSheet *sheet = [[[UIActionSheet alloc]
4215 initWithTitle:UCLocalize("ERROR")
4216 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4217 defaultButtonIndex:0
4222 [sheet setBodyText:[NSString stringWithUTF8String:error.c_str()]];
4223 [sheet popupAlertAnimated:YES];
4228 [delegate_ progressViewIsComplete:self];
4232 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4235 MMap mmap(file, MMap::ReadOnly);
4237 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4238 if (!(notifyconf_ == sha1.Result()))
4245 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4248 MMap mmap(file, MMap::ReadOnly);
4250 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4251 if (!(springlist_ == sha1.Result()))
4257 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4258 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4259 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4260 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4261 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4264 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4266 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
4267 [cache autorelease];
4269 NSFileManager *manager = [NSFileManager defaultManager];
4270 NSError *error = nil;
4272 id system = [cache objectForKey:@"System"];
4277 if (stat(Cache_, &info) == -1)
4280 [system removeAllObjects];
4282 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4283 for (NSString *app in apps)
4284 if ([app hasSuffix:@".app"]) {
4285 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4286 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4287 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4289 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4290 [info setObject:path forKey:@"Path"];
4291 [info setObject:@"System" forKey:@"ApplicationType"];
4292 [system addInfoDictionary:info];
4298 [cache writeToFile:@Cache_ atomically:YES];
4300 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
4302 if (chmod(Cache_, info.st_mode) == -1)
4306 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4309 notify_post("com.apple.mobile.application_installed");
4311 [delegate_ setStatusBarShowsProgress:NO];
4314 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4315 NSString *context([sheet context]);
4317 if ([context isEqualToString:@"error"])
4319 else if ([context isEqualToString:@"_error"]) {
4322 } else if ([context isEqualToString:@"conffile"]) {
4323 FILE *input = [database_ input];
4327 fprintf(input, "N\n");
4331 fprintf(input, "Y\n");
4342 - (void) closeButtonPushed {
4351 [delegate_ suspendWithAnimation:YES];
4355 system("launchctl stop com.apple.SpringBoard");
4359 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4368 - (void) _retachThread {
4369 UINavigationItem *item = [navbar_ topItem];
4370 [item setTitle:UCLocalize("COMPLETE")];
4372 [overlay_ addSubview:close_];
4373 [progress_ removeFromSuperview];
4374 [status_ removeFromSuperview];
4379 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4380 [[data target] performSelector:[data selector] withObject:[data object]];
4383 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4386 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4387 UINavigationItem *item = [navbar_ topItem];
4388 [item setTitle:title];
4390 [status_ setText:nil];
4391 [output_ setText:@""];
4392 [progress_ setProgress:0];
4394 [close_ removeFromSuperview];
4395 [overlay_ addSubview:progress_];
4396 [overlay_ addSubview:status_];
4398 [delegate_ setStatusBarShowsProgress:YES];
4403 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4406 MMap mmap(file, MMap::ReadOnly);
4408 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4409 notifyconf_ = sha1.Result();
4415 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4418 MMap mmap(file, MMap::ReadOnly);
4420 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4421 springlist_ = sha1.Result();
4425 [transition_ transition:6 toView:overlay_];
4428 detachNewThreadSelector:@selector(_detachNewThreadData:)
4430 withObject:[[ProgressData alloc]
4431 initWithSelector:selector
4438 - (void) repairWithSelector:(SEL)selector {
4440 detachNewThreadSelector:selector
4443 title:UCLocalize("REPAIRING")
4447 - (void) setConfigurationData:(NSString *)data {
4449 performSelectorOnMainThread:@selector(_setConfigurationData:)
4455 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4456 Package *package = id == nil ? nil : [database_ packageWithName:id];
4458 UIActionSheet *sheet = [[[UIActionSheet alloc]
4459 initWithTitle:(package == nil ? id : [package name])
4460 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4461 defaultButtonIndex:0
4466 [sheet setBodyText:error];
4467 [sheet popupAlertAnimated:YES];
4470 - (void) setProgressTitle:(NSString *)title {
4472 performSelectorOnMainThread:@selector(_setProgressTitle:)
4478 - (void) setProgressPercent:(float)percent {
4480 performSelectorOnMainThread:@selector(_setProgressPercent:)
4481 withObject:[NSNumber numberWithFloat:percent]
4486 - (void) startProgress {
4489 - (void) addProgressOutput:(NSString *)output {
4491 performSelectorOnMainThread:@selector(_addProgressOutput:)
4497 - (bool) isCancelling:(size_t)received {
4501 - (void) _setConfigurationData:(NSString *)data {
4502 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4504 _assert(conffile_r(data));
4506 NSString *ofile = conffile_r[1];
4507 //NSString *nfile = conffile_r[2];
4509 UIActionSheet *sheet = [[[UIActionSheet alloc]
4510 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4511 buttons:[NSArray arrayWithObjects:
4512 UCLocalize("KEEP_OLD_COPY"),
4513 UCLocalize("ACCEPT_NEW_COPY"),
4514 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4516 defaultButtonIndex:0
4521 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4522 [sheet popupAlertAnimated:YES];
4525 - (void) _setProgressTitle:(NSString *)title {
4526 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4527 for (size_t i(0), e([words count]); i != e; ++i) {
4528 NSString *word([words objectAtIndex:i]);
4529 if (Package *package = [database_ packageWithName:word])
4530 [words replaceObjectAtIndex:i withObject:[package name]];
4533 [status_ setText:[words componentsJoinedByString:@" "]];
4536 - (void) _setProgressPercent:(NSNumber *)percent {
4537 [progress_ setProgress:[percent floatValue]];
4540 - (void) _addProgressOutput:(NSString *)output {
4541 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4542 CGSize size = [output_ contentSize];
4543 CGRect rect = {{0, size.height}, {size.width, 0}};
4544 [output_ scrollRectToVisible:rect animated:YES];
4547 - (BOOL) isRunning {
4554 /* Package Cell {{{ */
4555 @interface PackageCell : UITableCell {
4558 NSString *description_;
4565 UITextLabel *status_;
4569 - (PackageCell *) init;
4570 - (void) setPackage:(Package *)package;
4572 + (int) heightForPackage:(Package *)package;
4576 @implementation PackageCell
4578 - (void) clearPackage {
4589 if (description_ != nil) {
4590 [description_ release];
4594 if (source_ != nil) {
4599 if (badge_ != nil) {
4609 [self clearPackage];
4616 - (PackageCell *) init {
4617 if ((self = [super init]) != nil) {
4619 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4620 [status_ setBackgroundColor:[UIColor clearColor]];
4621 [status_ setFont:small];
4626 - (void) setPackage:(Package *)package {
4627 [self clearPackage];
4630 Source *source = [package source];
4632 icon_ = [[package icon] retain];
4633 name_ = [[package name] retain];
4634 description_ = [[package shortDescription] retain];
4635 commercial_ = [package isCommercial];
4637 package_ = [package retain];
4639 NSString *label = nil;
4640 bool trusted = false;
4642 if (source != nil) {
4643 label = [source label];
4644 trusted = [source trusted];
4645 } else if ([[package id] isEqualToString:@"firmware"])
4646 label = UCLocalize("APPLE");
4648 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4650 NSString *from(label);
4652 NSString *section = [package simpleSection];
4653 if (section != nil && ![section isEqualToString:label]) {
4654 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4655 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4658 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4659 source_ = [from retain];
4661 if (NSString *purpose = [package primaryPurpose])
4662 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4663 badge_ = [badge_ retain];
4666 if (NSString *mode = [package mode]) {
4667 [badge_ setImage:[UIImage applicationImageNamed:
4668 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4671 [status_ setText:[NSString stringWithFormat:UCLocalize("QUEUED_FOR"), UCLocalize(mode)]];
4672 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4673 } else if ([package half]) {
4674 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4675 [status_ setText:UCLocalize("PACKAGE_DAMAGED")];
4676 [status_ setColor:[UIColor redColor]];
4678 [badge_ setImage:nil];
4679 [status_ setText:nil];
4686 - (void) drawRect:(CGRect)rect {
4690 if (NSString *mode = [package_ mode]) {
4691 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4692 color = remove ? RemovingColor_ : InstallingColor_;
4694 color = [UIColor whiteColor];
4696 [self setBackgroundColor:color];
4700 [super drawRect:rect];
4703 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4705 CGContextRef context(UIGraphicsGetCurrentContext());
4706 [[self backgroundColor] set];
4708 back.size.height -= 1;
4709 CGContextFillRect(context, back);
4712 [super drawBackgroundInRect:rect withFade:fade];
4715 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4718 rect.size = [icon_ size];
4720 rect.size.width /= 2;
4721 rect.size.height /= 2;
4723 rect.origin.x = 25 - rect.size.width / 2;
4724 rect.origin.y = 25 - rect.size.height / 2;
4726 [icon_ drawInRect:rect];
4729 if (badge_ != nil) {
4730 CGSize size = [badge_ size];
4732 [badge_ drawAtPoint:CGPointMake(
4733 36 - size.width / 2,
4734 36 - size.height / 2
4742 UISetColor(commercial_ ? Purple_ : Black_);
4743 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4744 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4747 UISetColor(commercial_ ? Purplish_ : Gray_);
4748 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4750 [super drawContentInRect:rect selected:selected];
4753 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4755 [super setSelected:selected withFade:fade];
4758 + (int) heightForPackage:(Package *)package {
4764 /* Section Cell {{{ */
4765 @interface SectionCell : UISimpleTableCell {
4770 _UISwitchSlider *switch_;
4775 - (void) setSection:(Section *)section editing:(BOOL)editing;
4779 @implementation SectionCell
4781 - (void) clearSection {
4782 if (section_ != nil) {
4792 if (count_ != nil) {
4799 [self clearSection];
4806 if ((self = [super init]) != nil) {
4807 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4809 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4810 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4814 - (void) onSwitch:(id)sender {
4815 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4816 if (metadata == nil) {
4817 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4818 [Sections_ setObject:metadata forKey:section_];
4822 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4825 - (void) setSection:(Section *)section editing:(BOOL)editing {
4826 if (editing != editing_) {
4828 [switch_ removeFromSuperview];
4830 [self addSubview:switch_];
4834 [self clearSection];
4836 if (section == nil) {
4837 name_ = [UCLocalize("ALL_PACKAGES") retain];
4840 section_ = [section localized];
4841 if (section_ != nil)
4842 section_ = [section_ retain];
4843 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4844 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4847 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4851 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4852 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4859 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4861 CGSize size = [count_ sizeWithFont:Font14_];
4865 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4867 [super drawContentInRect:rect selected:selected];
4873 /* File Table {{{ */
4874 @interface FileTable : RVPage {
4875 _transient Database *database_;
4878 NSMutableArray *files_;
4882 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4883 - (void) setPackage:(Package *)package;
4887 @implementation FileTable
4890 if (package_ != nil)
4899 - (int) numberOfRowsInTable:(UITable *)table {
4900 return files_ == nil ? 0 : [files_ count];
4903 - (float) table:(UITable *)table heightForRow:(int)row {
4907 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4908 if (reusing == nil) {
4909 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4910 UIFont *font = [UIFont systemFontOfSize:16];
4911 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4913 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4917 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4921 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4922 if ((self = [super initWithBook:book]) != nil) {
4923 database_ = database;
4925 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4927 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4928 [self addSubview:list_];
4930 UITableColumn *column = [[[UITableColumn alloc]
4931 initWithTitle:UCLocalize("NAME")
4933 width:[self frame].size.width
4936 [list_ setDataSource:self];
4937 [list_ setSeparatorStyle:1];
4938 [list_ addTableColumn:column];
4939 [list_ setDelegate:self];
4940 [list_ setReusesTableCells:YES];
4944 - (void) setPackage:(Package *)package {
4945 if (package_ != nil) {
4946 [package_ autorelease];
4955 [files_ removeAllObjects];
4957 if (package != nil) {
4958 package_ = [package retain];
4959 name_ = [[package id] retain];
4961 if (NSArray *files = [package files])
4962 [files_ addObjectsFromArray:files];
4964 if ([files_ count] != 0) {
4965 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4966 [files_ removeObjectAtIndex:0];
4967 [files_ sortUsingSelector:@selector(compareByPath:)];
4969 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4970 [stack addObject:@"/"];
4972 for (int i(0), e([files_ count]); i != e; ++i) {
4973 NSString *file = [files_ objectAtIndex:i];
4974 while (![file hasPrefix:[stack lastObject]])
4975 [stack removeLastObject];
4976 NSString *directory = [stack lastObject];
4977 [stack addObject:[file stringByAppendingString:@"/"]];
4978 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4979 ([stack count] - 2) * 3, "",
4980 [file substringFromIndex:[directory length]]
4989 - (void) resetViewAnimated:(BOOL)animated {
4990 [list_ resetViewAnimated:animated];
4993 - (void) reloadData {
4994 [self setPackage:[database_ packageWithName:name_]];
4995 [self reloadButtons];
4998 - (NSString *) title {
4999 return UCLocalize("INSTALLED_FILES");
5002 - (NSString *) backButtonTitle {
5003 return UCLocalize("FILES");
5008 /* Package View {{{ */
5009 @interface PackageView : CydiaBrowserView {
5010 _transient Database *database_;
5014 NSMutableArray *buttons_;
5017 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5018 - (void) setPackage:(Package *)package;
5022 @implementation PackageView
5025 if (package_ != nil)
5034 if ([self retainCount] == 1)
5035 [delegate_ setPackageView:self];
5039 /* XXX: this is not safe at all... localization of /fail/ */
5040 - (void) _clickButtonWithName:(NSString *)name {
5041 if ([name isEqualToString:UCLocalize("CLEAR")])
5042 [delegate_ clearPackage:package_];
5043 else if ([name isEqualToString:UCLocalize("INSTALL")])
5044 [delegate_ installPackage:package_];
5045 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5046 [delegate_ installPackage:package_];
5047 else if ([name isEqualToString:UCLocalize("REMOVE")])
5048 [delegate_ removePackage:package_];
5049 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5050 [delegate_ installPackage:package_];
5051 else _assert(false);
5054 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5055 NSString *context([sheet context]);
5057 if ([context isEqualToString:@"modify"]) {
5058 int count = [buttons_ count];
5059 _assert(count != 0);
5060 _assert(button <= count + 1);
5062 if (count != button - 1)
5063 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
5067 [super alertSheet:sheet buttonClicked:button];
5070 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5071 return [super webView:sender didFinishLoadForFrame:frame];
5074 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5075 [super webView:sender didClearWindowObject:window forFrame:frame];
5076 [window setValue:package_ forKey:@"package"];
5079 - (bool) _allowJavaScriptPanel {
5084 - (void) __rightButtonClicked {
5085 int count = [buttons_ count];
5086 _assert(count != 0);
5089 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5091 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
5092 [buttons addObjectsFromArray:buttons_];
5093 [buttons addObject:UCLocalize("CANCEL")];
5095 [delegate_ slideUp:[[[UIActionSheet alloc]
5098 defaultButtonIndex:([buttons count] - 1)
5105 - (void) _rightButtonClicked {
5107 [super _rightButtonClicked];
5109 [self __rightButtonClicked];
5113 - (id) _rightButtonTitle {
5114 int count = [buttons_ count];
5115 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5118 - (NSString *) backButtonTitle {
5122 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5123 if ((self = [super initWithBook:book]) != nil) {
5124 database_ = database;
5125 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5126 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5130 - (void) setPackage:(Package *)package {
5131 if (package_ != nil) {
5132 [package_ autorelease];
5141 [buttons_ removeAllObjects];
5143 if (package != nil) {
5146 package_ = [package retain];
5147 name_ = [[package id] retain];
5148 commercial_ = [package isCommercial];
5150 if ([package_ mode] != nil)
5151 [buttons_ addObject:UCLocalize("CLEAR")];
5152 if ([package_ source] == nil);
5153 else if ([package_ upgradableAndEssential:NO])
5154 [buttons_ addObject:UCLocalize("UPGRADE")];
5155 else if ([package_ uninstalled])
5156 [buttons_ addObject:UCLocalize("INSTALL")];
5158 [buttons_ addObject:UCLocalize("REINSTALL")];
5159 if (![package_ uninstalled])
5160 [buttons_ addObject:UCLocalize("REMOVE")];
5162 if (special_ != NULL) {
5163 CGRect frame([webview_ frame]);
5164 frame.size.width = 320;
5165 frame.size.height = 0;
5166 [webview_ setFrame:frame];
5168 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5171 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5173 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5175 [self setFinishHook:nil];
5176 [self setPopupHook:nil];
5179 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5180 [super callFunction:special_];
5184 [self reloadButtons];
5187 - (bool) isLoading {
5188 return commercial_ ? [super isLoading] : false;
5191 - (void) reloadData {
5192 [self setPackage:[database_ packageWithName:name_]];
5197 /* Package Table {{{ */
5198 @interface PackageTable : RVPage {
5199 _transient Database *database_;
5201 NSMutableArray *packages_;
5202 NSMutableArray *sections_;
5203 UISectionList *list_;
5206 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5208 - (void) setDelegate:(id)delegate;
5210 - (void) reloadData;
5211 - (void) resetCursor;
5213 - (UISectionList *) list;
5215 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5219 @implementation PackageTable
5222 [list_ setDataSource:nil];
5225 [packages_ release];
5226 [sections_ release];
5231 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5232 return [sections_ count];
5235 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5236 return [[sections_ objectAtIndex:section] name];
5239 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5240 return [[sections_ objectAtIndex:section] row];
5243 - (int) numberOfRowsInTable:(UITable *)table {
5244 return [packages_ count];
5247 - (float) table:(UITable *)table heightForRow:(int)row {
5248 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
5251 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
5253 reusing = [[[PackageCell alloc] init] autorelease];
5254 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
5258 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5262 - (void) tableRowSelected:(NSNotification *)notification {
5263 int row = [[notification object] selectedRow];
5267 Package *package = [packages_ objectAtIndex:row];
5268 package = [database_ packageWithName:[package id]];
5269 PackageView *view([delegate_ packageView]);
5270 [view setPackage:package];
5271 [view setDelegate:delegate_];
5272 [book_ pushPage:view];
5275 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5276 if ((self = [super initWithBook:book]) != nil) {
5277 database_ = database;
5278 title_ = [title retain];
5280 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5281 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5283 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
5284 [list_ setDataSource:self];
5286 UITableColumn *column = [[[UITableColumn alloc]
5287 initWithTitle:UCLocalize("NAME")
5289 width:[self frame].size.width
5292 UITable *table = [list_ table];
5293 [table setSeparatorStyle:1];
5294 [table addTableColumn:column];
5295 [table setDelegate:self];
5296 [table setReusesTableCells:YES];
5298 [self addSubview:list_];
5300 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5301 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5305 - (void) setDelegate:(id)delegate {
5306 delegate_ = delegate;
5309 - (bool) hasPackage:(Package *)package {
5313 - (void) reloadData {
5314 NSArray *packages = [database_ packages];
5316 [packages_ removeAllObjects];
5317 [sections_ removeAllObjects];
5319 _profile(PackageTable$reloadData$Filter)
5320 for (Package *package in packages)
5321 if ([self hasPackage:package])
5322 [packages_ addObject:package];
5325 Section *section = nil;
5327 _profile(PackageTable$reloadData$Section)
5328 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5332 _profile(PackageTable$reloadData$Section$Package)
5333 package = [packages_ objectAtIndex:offset];
5334 index = [package index];
5337 if (section == nil || [section index] != index) {
5338 _profile(PackageTable$reloadData$Section$Allocate)
5339 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5342 _profile(PackageTable$reloadData$Section$Add)
5343 [sections_ addObject:section];
5347 [section addToCount];
5351 _profile(PackageTable$reloadData$List)
5356 - (NSString *) title {
5360 - (void) resetViewAnimated:(BOOL)animated {
5361 [list_ resetViewAnimated:animated];
5364 - (void) resetCursor {
5365 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
5368 - (UISectionList *) list {
5372 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5373 [list_ setShouldHideHeaderInShortLists:hide];
5378 /* Filtered Package Table {{{ */
5379 @interface FilteredPackageTable : PackageTable {
5385 - (void) setObject:(id)object;
5387 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5391 @implementation FilteredPackageTable
5399 - (void) setObject:(id)object {
5405 object_ = [object retain];
5408 - (bool) hasPackage:(Package *)package {
5409 _profile(FilteredPackageTable$hasPackage)
5410 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5414 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5415 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5417 object_ = object == nil ? nil : [object retain];
5419 /* XXX: this is an unsafe optimization of doomy hell */
5420 Method method = class_getInstanceMethod([Package class], filter);
5421 _assert(method != NULL);
5422 imp_ = method_getImplementation(method);
5423 _assert(imp_ != NULL);
5432 /* Add Source View {{{ */
5433 @interface AddSourceView : RVPage {
5434 _transient Database *database_;
5437 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5441 @implementation AddSourceView
5443 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5444 if ((self = [super initWithBook:book]) != nil) {
5445 database_ = database;
5451 /* Source Cell {{{ */
5452 @interface SourceCell : UITableCell {
5455 NSString *description_;
5461 - (SourceCell *) initWithSource:(Source *)source;
5465 @implementation SourceCell
5470 [description_ release];
5475 - (SourceCell *) initWithSource:(Source *)source {
5476 if ((self = [super init]) != nil) {
5478 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5480 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5481 icon_ = [icon_ retain];
5483 origin_ = [[source name] retain];
5484 label_ = [[source uri] retain];
5485 description_ = [[source description] retain];
5489 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5491 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5498 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5502 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5506 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5508 [super drawContentInRect:rect selected:selected];
5513 /* Source Table {{{ */
5514 @interface SourceTable : RVPage {
5515 _transient Database *database_;
5516 UISectionList *list_;
5517 NSMutableArray *sources_;
5518 UIActionSheet *alert_;
5522 UIProgressHUD *hud_;
5525 //NSURLConnection *installer_;
5526 NSURLConnection *trivial_bz2_;
5527 NSURLConnection *trivial_gz_;
5528 //NSURLConnection *automatic_;
5533 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5537 @implementation SourceTable
5539 - (void) _deallocConnection:(NSURLConnection *)connection {
5540 if (connection != nil) {
5541 [connection cancel];
5542 //[connection setDelegate:nil];
5543 [connection release];
5548 [[list_ table] setDelegate:nil];
5549 [list_ setDataSource:nil];
5558 //[self _deallocConnection:installer_];
5559 [self _deallocConnection:trivial_gz_];
5560 [self _deallocConnection:trivial_bz2_];
5561 //[self _deallocConnection:automatic_];
5568 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5569 return offset_ == 0 ? 1 : 2;
5572 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5573 switch (section + (offset_ == 0 ? 1 : 0)) {
5574 case 0: return UCLocalize("ENTERED_BY_USER");
5575 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5583 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5584 switch (section + (offset_ == 0 ? 1 : 0)) {
5586 case 1: return offset_;
5594 - (int) numberOfRowsInTable:(UITable *)table {
5595 return [sources_ count];
5598 - (float) table:(UITable *)table heightForRow:(int)row {
5599 Source *source = [sources_ objectAtIndex:row];
5600 return [source description] == nil ? 56 : 73;
5603 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5604 Source *source = [sources_ objectAtIndex:row];
5605 // XXX: weird warning, stupid selectors ;P
5606 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5609 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5613 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5617 - (void) tableRowSelected:(NSNotification*)notification {
5618 UITable *table([list_ table]);
5619 int row([table selectedRow]);
5623 Source *source = [sources_ objectAtIndex:row];
5625 PackageTable *packages = [[[FilteredPackageTable alloc]
5628 title:[source label]
5629 filter:@selector(isVisibleInSource:)
5633 [packages setDelegate:delegate_];
5635 [book_ pushPage:packages];
5638 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5639 Source *source = [sources_ objectAtIndex:row];
5640 return [source record] != nil;
5643 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5644 [[list_ table] setDeleteConfirmationRow:row];
5647 - (void) table:(UITable *)table deleteRow:(int)row {
5648 Source *source = [sources_ objectAtIndex:row];
5649 [Sources_ removeObjectForKey:[source key]];
5650 [delegate_ syncData];
5654 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5657 @"./", @"Distribution",
5658 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5660 [delegate_ syncData];
5663 - (NSString *) getWarning {
5664 NSString *href(href_);
5665 NSRange colon([href rangeOfString:@"://"]);
5666 if (colon.location != NSNotFound)
5667 href = [href substringFromIndex:(colon.location + 3)];
5668 href = [href stringByAddingPercentEscapes];
5669 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5670 href = [href stringByCachingURLWithCurrentCDN];
5672 NSURL *url([NSURL URLWithString:href]);
5674 NSStringEncoding encoding;
5675 NSError *error(nil);
5677 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5678 return [warning length] == 0 ? nil : warning;
5682 - (void) _endConnection:(NSURLConnection *)connection {
5683 NSURLConnection **field = NULL;
5684 if (connection == trivial_bz2_)
5685 field = &trivial_bz2_;
5686 else if (connection == trivial_gz_)
5687 field = &trivial_gz_;
5688 _assert(field != NULL);
5689 [connection release];
5693 trivial_bz2_ == nil &&
5699 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5702 UIActionSheet *sheet = [[[UIActionSheet alloc]
5703 initWithTitle:UCLocalize("SOURCE_WARNING")
5704 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5705 defaultButtonIndex:0
5710 [sheet setNumberOfRows:1];
5712 [sheet setBodyText:warning];
5713 [sheet popupAlertAnimated:YES];
5716 } else if (error_ != nil) {
5717 UIActionSheet *sheet = [[[UIActionSheet alloc]
5718 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5719 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5720 defaultButtonIndex:0
5725 [sheet setBodyText:[error_ localizedDescription]];
5726 [sheet popupAlertAnimated:YES];
5728 UIActionSheet *sheet = [[[UIActionSheet alloc]
5729 initWithTitle:UCLocalize("NOT_REPOSITORY")
5730 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5731 defaultButtonIndex:0
5736 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5737 [sheet popupAlertAnimated:YES];
5740 [delegate_ setStatusBarShowsProgress:NO];
5741 [delegate_ removeProgressHUD:hud_];
5751 if (error_ != nil) {
5758 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5759 switch ([response statusCode]) {
5765 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5766 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5768 error_ = [error retain];
5769 [self _endConnection:connection];
5772 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5773 [self _endConnection:connection];
5776 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5777 NSMutableURLRequest *request = [NSMutableURLRequest
5778 requestWithURL:[NSURL URLWithString:href]
5779 cachePolicy:NSURLRequestUseProtocolCachePolicy
5780 timeoutInterval:20.0
5783 [request setHTTPMethod:method];
5785 if (Machine_ != NULL)
5786 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5787 if (UniqueID_ != nil)
5788 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5791 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5793 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5796 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5797 NSString *context([sheet context]);
5799 if ([context isEqualToString:@"source"]) {
5802 NSString *href = [[sheet textField] text];
5804 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5806 if (![href hasSuffix:@"/"])
5807 href_ = [href stringByAppendingString:@"/"];
5810 href_ = [href_ retain];
5812 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5813 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5814 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5818 hud_ = [[delegate_ addProgressHUD] retain];
5819 [hud_ setText:UCLocalize("VERIFYING_URL")];
5830 } else if ([context isEqualToString:@"trivial"])
5832 else if ([context isEqualToString:@"urlerror"])
5834 else if ([context isEqualToString:@"warning"]) {
5854 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5855 if ((self = [super initWithBook:book]) != nil) {
5856 database_ = database;
5857 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5859 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5860 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5861 [list_ setShouldHideHeaderInShortLists:NO];
5863 [self addSubview:list_];
5864 [list_ setDataSource:self];
5866 UITableColumn *column = [[UITableColumn alloc]
5867 initWithTitle:UCLocalize("NAME")
5869 width:[self frame].size.width
5872 UITable *table = [list_ table];
5873 [table setSeparatorStyle:1];
5874 [table addTableColumn:column];
5875 [table setDelegate:self];
5879 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5880 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5884 - (void) reloadData {
5886 _assert(list.ReadMainList());
5888 [sources_ removeAllObjects];
5889 [sources_ addObjectsFromArray:[database_ sources]];
5891 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5894 int count = [sources_ count];
5895 for (offset_ = 0; offset_ != count; ++offset_) {
5896 Source *source = [sources_ objectAtIndex:offset_];
5897 if ([source record] == nil)
5904 - (void) resetViewAnimated:(BOOL)animated {
5905 [list_ resetViewAnimated:animated];
5908 - (void) _leftButtonClicked {
5909 /*[book_ pushPage:[[[AddSourceView alloc]
5914 UIActionSheet *sheet = [[[UIActionSheet alloc]
5915 initWithTitle:UCLocalize("ENTER_APT_URL")
5916 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
5917 defaultButtonIndex:0
5922 [sheet setNumberOfRows:1];
5924 [sheet addTextFieldWithValue:@"http://" label:@""];
5926 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5927 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5928 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5929 [traits setKeyboardType:UIKeyboardTypeURL];
5930 // XXX: UIReturnKeyDone
5931 [traits setReturnKeyType:UIReturnKeyNext];
5933 [sheet popupAlertAnimated:YES];
5936 - (void) _rightButtonClicked {
5937 UITable *table = [list_ table];
5938 BOOL editing = [table isRowDeletionEnabled];
5939 [table enableRowDeletion:!editing animated:YES];
5940 [book_ reloadButtonsForPage:self];
5943 - (NSString *) title {
5944 return UCLocalize("SOURCES");
5947 - (NSString *) leftButtonTitle {
5948 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
5951 - (id) rightButtonTitle {
5952 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
5955 - (UINavigationButtonStyle) rightButtonStyle {
5956 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5962 /* Installed View {{{ */
5963 @interface InstalledView : RVPage {
5964 _transient Database *database_;
5965 FilteredPackageTable *packages_;
5969 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5973 @implementation InstalledView
5976 [packages_ release];
5980 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5981 if ((self = [super initWithBook:book]) != nil) {
5982 database_ = database;
5984 packages_ = [[FilteredPackageTable alloc]
5988 filter:@selector(isInstalledAndVisible:)
5989 with:[NSNumber numberWithBool:YES]
5992 [self addSubview:packages_];
5994 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5995 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5999 - (void) resetViewAnimated:(BOOL)animated {
6000 [packages_ resetViewAnimated:animated];
6003 - (void) reloadData {
6004 [packages_ reloadData];
6007 - (void) _rightButtonClicked {
6008 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6009 [packages_ reloadData];
6011 [book_ reloadButtonsForPage:self];
6014 - (NSString *) title {
6015 return UCLocalize("INSTALLED");
6018 - (NSString *) backButtonTitle {
6019 return UCLocalize("PACKAGES");
6022 - (id) rightButtonTitle {
6023 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6026 - (UINavigationButtonStyle) rightButtonStyle {
6027 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6030 - (void) setDelegate:(id)delegate {
6031 [super setDelegate:delegate];
6032 [packages_ setDelegate:delegate];
6039 @interface HomeView : CydiaBrowserView {
6044 @implementation HomeView
6046 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6047 NSString *context([sheet context]);
6049 if ([context isEqualToString:@"about"])
6052 [super alertSheet:sheet buttonClicked:button];
6055 - (void) _leftButtonClicked {
6056 UIActionSheet *sheet = [[[UIActionSheet alloc]
6057 initWithTitle:UCLocalize("ABOUT_CYDIA")
6058 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6059 defaultButtonIndex:0
6065 @"Copyright (C) 2008-2009\n"
6066 "Jay Freeman (saurik)\n"
6067 "saurik@saurik.com\n"
6068 "http://www.saurik.com/\n"
6071 "http://www.theokorigroup.com/\n"
6073 "College of Creative Studies,\n"
6074 "University of California,\n"
6076 "http://www.ccs.ucsb.edu/"
6079 [sheet popupAlertAnimated:YES];
6082 - (NSString *) leftButtonTitle {
6083 return UCLocalize("ABOUT");
6088 /* Manage View {{{ */
6089 @interface ManageView : CydiaBrowserView {
6094 @implementation ManageView
6096 - (NSString *) title {
6097 return UCLocalize("MANAGE");
6100 - (void) _leftButtonClicked {
6101 [delegate_ askForSettings];
6104 - (NSString *) leftButtonTitle {
6105 return UCLocalize("SETTINGS");
6109 - (id) _rightButtonTitle {
6110 return Queuing_ ? UCLocalize("QUEUE") : nil;
6113 - (UINavigationButtonStyle) rightButtonStyle {
6114 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6117 - (void) _rightButtonClicked {
6122 - (bool) isLoading {
6129 /* Cydia Book {{{ */
6130 @interface CYBook : RVBook <
6133 _transient Database *database_;
6134 UINavigationBar *overlay_;
6135 UINavigationBar *underlay_;
6136 UIProgressIndicator *indicator_;
6137 UITextLabel *prompt_;
6138 UIProgressBar *progress_;
6139 UINavigationButton *cancel_;
6143 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6149 @implementation CYBook
6153 [indicator_ release];
6155 [progress_ release];
6160 - (NSString *) getTitleForPage:(RVPage *)page {
6161 return [super getTitleForPage:page];
6169 [UIView beginAnimations:nil context:NULL];
6171 CGRect ovrframe = [overlay_ frame];
6172 ovrframe.origin.y = 0;
6173 [overlay_ setFrame:ovrframe];
6175 CGRect barframe = [navbar_ frame];
6176 barframe.origin.y += ovrframe.size.height;
6177 [navbar_ setFrame:barframe];
6179 CGRect trnframe = [transition_ frame];
6180 trnframe.origin.y += ovrframe.size.height;
6181 trnframe.size.height -= ovrframe.size.height;
6182 [transition_ setFrame:trnframe];
6184 [UIView endAnimations];
6186 [indicator_ startAnimation];
6187 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6188 [progress_ setProgress:0];
6191 [overlay_ addSubview:cancel_];
6194 detachNewThreadSelector:@selector(_update)
6200 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6201 NSString *context([sheet context]);
6203 if ([context isEqualToString:@"refresh"])
6207 - (void) _update_:(NSString *)error {
6210 [indicator_ stopAnimation];
6212 [UIView beginAnimations:nil context:NULL];
6214 CGRect ovrframe = [overlay_ frame];
6215 ovrframe.origin.y = -ovrframe.size.height;
6216 [overlay_ setFrame:ovrframe];
6218 CGRect barframe = [navbar_ frame];
6219 barframe.origin.y -= ovrframe.size.height;
6220 [navbar_ setFrame:barframe];
6222 CGRect trnframe = [transition_ frame];
6223 trnframe.origin.y -= ovrframe.size.height;
6224 trnframe.size.height += ovrframe.size.height;
6225 [transition_ setFrame:trnframe];
6227 [UIView commitAnimations];
6230 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6232 UIActionSheet *sheet = [[[UIActionSheet alloc]
6233 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6234 buttons:[NSArray arrayWithObjects:
6237 defaultButtonIndex:0
6242 [sheet setBodyText:error];
6243 [sheet popupAlertAnimated:YES];
6245 [self reloadButtons];
6249 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6250 if ((self = [super initWithFrame:frame]) != nil) {
6251 database_ = database;
6253 CGRect ovrrect = [navbar_ bounds];
6254 ovrrect.size.height = [UINavigationBar defaultSize].height;
6255 ovrrect.origin.y = -ovrrect.size.height;
6257 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6258 [self addSubview:overlay_];
6260 ovrrect.origin.y = frame.size.height;
6261 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6262 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6263 [self addSubview:underlay_];
6265 [overlay_ setBarStyle:1];
6266 [underlay_ setBarStyle:1];
6268 int barstyle = [overlay_ _barStyle:NO];
6269 bool ugly = barstyle == 0;
6271 UIProgressIndicatorStyle style = ugly ?
6272 UIProgressIndicatorStyleMediumBrown :
6273 UIProgressIndicatorStyleMediumWhite;
6275 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
6276 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6277 CGRect indrect = {{indoffset, indoffset}, indsize};
6279 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6280 [indicator_ setStyle:style];
6281 [overlay_ addSubview:indicator_];
6283 CGSize prmsize = {215, indsize.height + 4};
6286 indoffset * 2 + indsize.width,
6290 unsigned(ovrrect.size.height - prmsize.height) / 2
6293 UIFont *font = [UIFont systemFontOfSize:15];
6295 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6297 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6298 [prompt_ setBackgroundColor:[UIColor clearColor]];
6299 [prompt_ setFont:font];
6301 [overlay_ addSubview:prompt_];
6303 CGSize prgsize = {75, 100};
6306 ovrrect.size.width - prgsize.width - 10,
6307 (ovrrect.size.height - prgsize.height) / 2
6310 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6311 [progress_ setStyle:0];
6312 [overlay_ addSubview:progress_];
6314 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6315 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6317 CGRect frame = [cancel_ frame];
6318 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6319 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6320 [cancel_ setFrame:frame];
6322 [cancel_ setBarStyle:barstyle];
6326 - (void) _onCancel {
6328 [cancel_ removeFromSuperview];
6331 - (void) _update { _pooled
6333 status.setDelegate(self);
6335 NSString *error([database_ updateWithStatus:status]);
6338 performSelectorOnMainThread:@selector(_update_:)
6344 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6345 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6348 - (void) setProgressTitle:(NSString *)title {
6350 performSelectorOnMainThread:@selector(_setProgressTitle:)
6356 - (void) setProgressPercent:(float)percent {
6358 performSelectorOnMainThread:@selector(_setProgressPercent:)
6359 withObject:[NSNumber numberWithFloat:percent]
6364 - (void) startProgress {
6367 - (void) addProgressOutput:(NSString *)output {
6369 performSelectorOnMainThread:@selector(_addProgressOutput:)
6375 - (bool) isCancelling:(size_t)received {
6379 - (void) _setProgressTitle:(NSString *)title {
6380 [prompt_ setText:title];
6383 - (void) _setProgressPercent:(NSNumber *)percent {
6384 [progress_ setProgress:[percent floatValue]];
6387 - (void) _addProgressOutput:(NSString *)output {
6392 /* Cydia:// Protocol {{{ */
6393 @interface CydiaURLProtocol : NSURLProtocol {
6398 @implementation CydiaURLProtocol
6400 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6401 NSURL *url([request URL]);
6404 NSString *scheme([[url scheme] lowercaseString]);
6405 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6410 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6414 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6415 id<NSURLProtocolClient> client([self client]);
6417 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6419 NSData *data(UIImagePNGRepresentation(icon));
6421 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6422 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6423 [client URLProtocol:self didLoadData:data];
6424 [client URLProtocolDidFinishLoading:self];
6428 - (void) startLoading {
6429 id<NSURLProtocolClient> client([self client]);
6430 NSURLRequest *request([self request]);
6432 NSURL *url([request URL]);
6433 NSString *href([url absoluteString]);
6435 NSString *path([href substringFromIndex:8]);
6436 NSRange slash([path rangeOfString:@"/"]);
6439 if (slash.location == NSNotFound) {
6443 command = [path substringToIndex:slash.location];
6444 path = [path substringFromIndex:(slash.location + 1)];
6447 Database *database([Database sharedInstance]);
6449 if ([command isEqualToString:@"package-icon"]) {
6452 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6453 Package *package([database packageWithName:path]);
6456 UIImage *icon([package icon]);
6457 [self _returnPNGWithImage:icon forRequest:request];
6458 } else if ([command isEqualToString:@"source-icon"]) {
6461 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6462 NSString *source(Simplify(path));
6463 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6465 icon = [UIImage applicationImageNamed:@"unknown.png"];
6466 [self _returnPNGWithImage:icon forRequest:request];
6467 } else if ([command isEqualToString:@"uikit-image"]) {
6470 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6471 UIImage *icon(_UIImageWithName(path));
6472 [self _returnPNGWithImage:icon forRequest:request];
6473 } else if ([command isEqualToString:@"section-icon"]) {
6476 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6477 NSString *section(Simplify(path));
6478 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6480 icon = [UIImage applicationImageNamed:@"unknown.png"];
6481 [self _returnPNGWithImage:icon forRequest:request];
6483 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6487 - (void) stopLoading {
6493 /* Sections View {{{ */
6494 @interface SectionsView : RVPage {
6495 _transient Database *database_;
6496 NSMutableArray *sections_;
6497 NSMutableArray *filtered_;
6498 UITransitionView *transition_;
6504 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6505 - (void) reloadData;
6510 @implementation SectionsView
6513 [list_ setDataSource:nil];
6514 [list_ setDelegate:nil];
6516 [sections_ release];
6517 [filtered_ release];
6518 [transition_ release];
6520 [accessory_ release];
6524 - (int) numberOfRowsInTable:(UITable *)table {
6525 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6528 - (float) table:(UITable *)table heightForRow:(int)row {
6532 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6534 reusing = [[[SectionCell alloc] init] autorelease];
6535 [(SectionCell *)reusing setSection:(editing_ ?
6536 [sections_ objectAtIndex:row] :
6537 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6538 ) editing:editing_];
6542 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6546 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6550 - (void) tableRowSelected:(NSNotification *)notification {
6551 int row = [[notification object] selectedRow];
6562 title = UCLocalize("ALL_PACKAGES");
6564 section = [filtered_ objectAtIndex:(row - 1)];
6565 name = [section name];
6568 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6571 title = UCLocalize("NO_SECTION");
6575 PackageTable *table = [[[FilteredPackageTable alloc]
6579 filter:@selector(isVisiblyUninstalledInSection:)
6583 [table setDelegate:delegate_];
6585 [book_ pushPage:table];
6588 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6589 if ((self = [super initWithBook:book]) != nil) {
6590 database_ = database;
6592 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6593 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6595 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6596 [self addSubview:transition_];
6598 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6599 [transition_ transition:0 toView:list_];
6601 UITableColumn *column = [[[UITableColumn alloc]
6602 initWithTitle:UCLocalize("NAME")
6604 width:[self frame].size.width
6607 [list_ setDataSource:self];
6608 [list_ setSeparatorStyle:1];
6609 [list_ addTableColumn:column];
6610 [list_ setDelegate:self];
6611 [list_ setReusesTableCells:YES];
6615 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6616 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6620 - (void) reloadData {
6621 NSArray *packages = [database_ packages];
6623 [sections_ removeAllObjects];
6624 [filtered_ removeAllObjects];
6627 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6628 SectionMap sections;
6629 sections.resize(64);
6631 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6635 for (Package *package in packages) {
6636 NSString *name([package section]);
6637 NSString *key(name == nil ? @"" : name);
6642 _profile(SectionsView$reloadData$Section)
6643 section = §ions[key];
6644 if (*section == nil) {
6645 _profile(SectionsView$reloadData$Section$Allocate)
6646 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6651 [*section addToCount];
6653 _profile(SectionsView$reloadData$Filter)
6654 if (![package valid] || ![package uninstalled] || ![package visible])
6658 [*section addToRow];
6662 _profile(SectionsView$reloadData$Section)
6663 section = [sections objectForKey:key];
6664 if (section == nil) {
6665 _profile(SectionsView$reloadData$Section$Allocate)
6666 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6667 [sections setObject:section forKey:key];
6672 [section addToCount];
6674 _profile(SectionsView$reloadData$Filter)
6675 if (![package valid] || ![package uninstalled] || ![package visible])
6685 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6686 [sections_ addObject:i->second];
6688 [sections_ addObjectsFromArray:[sections allValues]];
6691 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6693 for (Section *section in sections_) {
6694 size_t count([section row]);
6698 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6699 [section setCount:count];
6700 [filtered_ addObject:section];
6707 - (void) resetView {
6709 [self _rightButtonClicked];
6712 - (void) resetViewAnimated:(BOOL)animated {
6713 [list_ resetViewAnimated:animated];
6716 - (void) _rightButtonClicked {
6717 if ((editing_ = !editing_))
6720 [delegate_ updateData];
6721 [book_ reloadTitleForPage:self];
6722 [book_ reloadButtonsForPage:self];
6725 - (NSString *) title {
6726 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("INSTALL_BY_SECTION");
6729 - (NSString *) backButtonTitle {
6730 return UCLocalize("SECTIONS");
6733 - (id) rightButtonTitle {
6734 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6737 - (UINavigationButtonStyle) rightButtonStyle {
6738 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6741 - (UIView *) accessoryView {
6747 /* Changes View {{{ */
6748 @interface ChangesView : RVPage {
6749 _transient Database *database_;
6750 NSMutableArray *packages_;
6751 NSMutableArray *sections_;
6752 UISectionList *list_;
6756 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6757 - (void) reloadData;
6761 @implementation ChangesView
6764 [[list_ table] setDelegate:nil];
6765 [list_ setDataSource:nil];
6767 [packages_ release];
6768 [sections_ release];
6773 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6774 return [sections_ count];
6777 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6778 return [[sections_ objectAtIndex:section] name];
6781 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6782 return [[sections_ objectAtIndex:section] row];
6785 - (int) numberOfRowsInTable:(UITable *)table {
6786 return [packages_ count];
6789 - (float) table:(UITable *)table heightForRow:(int)row {
6790 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6793 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6795 reusing = [[[PackageCell alloc] init] autorelease];
6796 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6800 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6804 - (void) tableRowSelected:(NSNotification *)notification {
6805 int row = [[notification object] selectedRow];
6808 Package *package = [packages_ objectAtIndex:row];
6809 PackageView *view([delegate_ packageView]);
6810 [view setDelegate:delegate_];
6811 [view setPackage:package];
6812 [book_ pushPage:view];
6815 - (void) _leftButtonClicked {
6816 [(CYBook *)book_ update];
6817 [self reloadButtons];
6820 - (void) _rightButtonClicked {
6821 [delegate_ distUpgrade];
6824 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6825 if ((self = [super initWithBook:book]) != nil) {
6826 database_ = database;
6828 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6829 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6831 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6832 [self addSubview:list_];
6834 [list_ setShouldHideHeaderInShortLists:NO];
6835 [list_ setDataSource:self];
6836 //[list_ setSectionListStyle:1];
6838 UITableColumn *column = [[[UITableColumn alloc]
6839 initWithTitle:UCLocalize("NAME")
6841 width:[self frame].size.width
6844 UITable *table = [list_ table];
6845 [table setSeparatorStyle:1];
6846 [table addTableColumn:column];
6847 [table setDelegate:self];
6848 [table setReusesTableCells:YES];
6852 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6853 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6857 - (void) reloadData {
6858 NSArray *packages = [database_ packages];
6860 [packages_ removeAllObjects];
6861 [sections_ removeAllObjects];
6864 for (Package *package in packages)
6866 [package uninstalled] && [package valid] && [package visible] ||
6867 [package upgradableAndEssential:YES]
6869 [packages_ addObject:package];
6872 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6875 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6876 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6877 Section *section = nil;
6881 bool unseens = false;
6883 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6885 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6886 Package *package = [packages_ objectAtIndex:offset];
6888 BOOL uae = [package upgradableAndEssential:YES];
6894 _profile(ChangesView$reloadData$Remember)
6895 seen = [package seen];
6898 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6903 name = UCLocalize("UNKNOWN");
6905 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6909 _profile(ChangesView$reloadData$Allocate)
6910 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
6911 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6912 [sections_ addObject:section];
6916 [section addToCount];
6917 } else if ([package ignored])
6918 [ignored addToCount];
6921 [upgradable addToCount];
6926 CFRelease(formatter);
6929 Section *last = [sections_ lastObject];
6930 size_t count = [last count];
6931 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6932 [sections_ removeLastObject];
6935 if ([ignored count] != 0)
6936 [sections_ insertObject:ignored atIndex:0];
6938 [sections_ insertObject:upgradable atIndex:0];
6941 [self reloadButtons];
6944 - (void) resetViewAnimated:(BOOL)animated {
6945 [list_ resetViewAnimated:animated];
6948 - (NSString *) leftButtonTitle {
6949 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
6952 - (id) rightButtonTitle {
6953 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6956 - (NSString *) title {
6957 return UCLocalize("CHANGES");
6962 /* Search View {{{ */
6963 @protocol SearchViewDelegate
6964 - (void) showKeyboard:(BOOL)show;
6967 @interface SearchView : RVPage {
6969 UISearchField *field_;
6970 UITransitionView *transition_;
6971 FilteredPackageTable *table_;
6972 UIPreferencesTable *advanced_;
6978 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6979 - (void) reloadData;
6983 @implementation SearchView
6986 [field_ setDelegate:nil];
6988 [accessory_ release];
6990 [transition_ release];
6992 [advanced_ release];
6997 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7001 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7003 case 0: return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("ADVANCED_SEARCH"), UCLocalize("COMING_SOON")];
7005 default: _assert(false);
7009 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7013 default: _assert(false);
7017 - (void) _showKeyboard:(BOOL)show {
7018 CGSize keysize = [UIKeyboard defaultSize];
7019 CGRect keydown = [book_ pageBounds];
7020 CGRect keyup = keydown;
7021 keyup.size.height -= keysize.height - ButtonBarHeight_;
7023 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7025 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7026 [animation setSignificantRectFields:8];
7029 [animation setStartFrame:keydown];
7030 [animation setEndFrame:keyup];
7032 [animation setStartFrame:keyup];
7033 [animation setEndFrame:keydown];
7036 UIAnimator *animator = [UIAnimator sharedAnimator];
7039 addAnimations:[NSArray arrayWithObjects:animation, nil]
7040 withDuration:(KeyboardTime_ - delay)
7045 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7047 [delegate_ showKeyboard:show];
7050 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7051 [self _showKeyboard:YES];
7054 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7055 [self _showKeyboard:NO];
7058 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7060 NSString *text([field_ text]);
7061 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7067 - (void) textFieldClearButtonPressed:(UITextField *)field {
7071 - (void) keyboardInputShouldDelete:(id)input {
7075 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7076 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7080 [field_ resignFirstResponder];
7085 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7086 if ((self = [super initWithBook:book]) != nil) {
7087 CGRect pageBounds = [book_ pageBounds];
7089 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
7090 [self addSubview:transition_];
7092 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
7094 [advanced_ setReusesTableCells:YES];
7095 [advanced_ setDataSource:self];
7096 [advanced_ reloadData];
7098 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
7099 CGColor dimmed(space_, 0, 0, 0, 0.5);
7100 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
7102 table_ = [[FilteredPackageTable alloc]
7106 filter:@selector(isUnfilteredAndSearchedForBy:)
7110 [table_ setShouldHideHeaderInShortLists:NO];
7111 [transition_ transition:0 toView:table_];
7120 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
7127 [self bounds].size.width - area.origin.x - 18;
7129 area.size.height = [UISearchField defaultHeight];
7131 field_ = [[UISearchField alloc] initWithFrame:area];
7133 UIFont *font = [UIFont systemFontOfSize:16];
7134 [field_ setFont:font];
7136 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7137 [field_ setDelegate:self];
7139 [field_ setPaddingTop:5];
7141 UITextInputTraits *traits([field_ textInputTraits]);
7142 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7143 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7144 [traits setReturnKeyType:UIReturnKeySearch];
7146 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7148 accessory_ = [[UIView alloc] initWithFrame:accrect];
7149 [accessory_ addSubview:field_];
7151 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
7152 [configure setShowPressFeedback:YES];
7153 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
7154 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
7155 [accessory_ addSubview:configure];*/
7157 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7158 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7164 LKAnimation *animation = [LKTransition animation];
7165 [animation setType:@"oglFlip"];
7166 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
7167 [animation setFillMode:@"extended"];
7168 [animation setTransitionFlags:3];
7169 [animation setDuration:10];
7170 [animation setSpeed:0.35];
7171 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
7172 [[transition_ _layer] addAnimation:animation forKey:0];
7173 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
7174 flipped_ = !flipped_;
7178 - (void) configurePushed {
7179 [field_ resignFirstResponder];
7183 - (void) resetViewAnimated:(BOOL)animated {
7186 [table_ resetViewAnimated:animated];
7189 - (void) _reloadData {
7192 - (void) reloadData {
7195 [table_ setObject:[field_ text]];
7196 _profile(SearchView$reloadData)
7197 [table_ reloadData];
7200 [table_ resetCursor];
7203 - (UIView *) accessoryView {
7207 - (NSString *) title {
7211 - (NSString *) backButtonTitle {
7212 return UCLocalize("SEARCH");
7215 - (void) setDelegate:(id)delegate {
7216 [table_ setDelegate:delegate];
7217 [super setDelegate:delegate];
7223 @interface SettingsView : RVPage {
7224 _transient Database *database_;
7227 UIPreferencesTable *table_;
7228 _UISwitchSlider *subscribedSwitch_;
7229 _UISwitchSlider *ignoredSwitch_;
7230 UIPreferencesControlTableCell *subscribedCell_;
7231 UIPreferencesControlTableCell *ignoredCell_;
7234 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7238 @implementation SettingsView
7241 [table_ setDataSource:nil];
7244 if (package_ != nil)
7247 [subscribedSwitch_ release];
7248 [ignoredSwitch_ release];
7249 [subscribedCell_ release];
7250 [ignoredCell_ release];
7254 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7255 if (package_ == nil)
7261 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7262 if (package_ == nil)
7269 default: _assert(false);
7275 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7276 if (package_ == nil)
7283 default: _assert(false);
7289 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7290 if (package_ == nil)
7297 default: _assert(false);
7303 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7304 if (package_ == nil)
7307 _UISwitchSlider *slider([cell control]);
7308 BOOL value([slider value] != 0);
7309 NSMutableDictionary *metadata([package_ metadata]);
7312 if (NSNumber *number = [metadata objectForKey:key])
7313 before = [number boolValue];
7317 if (value != before) {
7318 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7320 [delegate_ updateData];
7324 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7325 [self onSomething:cell withKey:@"IsSubscribed"];
7328 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7329 [self onSomething:cell withKey:@"IsIgnored"];
7332 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7333 if (package_ == nil)
7337 case 0: switch (row) {
7339 return subscribedCell_;
7341 return ignoredCell_;
7342 default: _assert(false);
7345 case 1: switch (row) {
7347 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7348 [cell setShowSelection:NO];
7349 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7353 default: _assert(false);
7356 default: _assert(false);
7362 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7363 if ((self = [super initWithBook:book])) {
7364 database_ = database;
7365 name_ = [package retain];
7367 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7368 [self addSubview:table_];
7370 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7371 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
7373 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7374 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
7376 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7377 [subscribedCell_ setShowSelection:NO];
7378 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7379 [subscribedCell_ setControl:subscribedSwitch_];
7381 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7382 [ignoredCell_ setShowSelection:NO];
7383 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7384 [ignoredCell_ setControl:ignoredSwitch_];
7386 [table_ setDataSource:self];
7391 - (void) resetViewAnimated:(BOOL)animated {
7392 [table_ resetViewAnimated:animated];
7395 - (void) reloadData {
7396 if (package_ != nil)
7397 [package_ autorelease];
7398 package_ = [database_ packageWithName:name_];
7399 if (package_ != nil) {
7401 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7402 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7405 [table_ reloadData];
7408 - (NSString *) title {
7409 return UCLocalize("SETTINGS");
7414 /* Signature View {{{ */
7415 @interface SignatureView : CydiaBrowserView {
7416 _transient Database *database_;
7420 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7424 @implementation SignatureView
7431 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7433 [super webView:sender didClearWindowObject:window forFrame:frame];
7436 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7437 if ((self = [super initWithBook:book]) != nil) {
7438 database_ = database;
7439 package_ = [package retain];
7444 - (void) resetViewAnimated:(BOOL)animated {
7447 - (void) reloadData {
7448 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7454 @interface Cydia : UIApplication <
7455 ConfirmationViewDelegate,
7456 ProgressViewDelegate,
7465 UIToolbar *buttonbar_;
7469 NSMutableArray *essential_;
7470 NSMutableArray *broken_;
7472 Database *database_;
7473 ProgressView *progress_;
7477 UIKeyboard *keyboard_;
7478 UIProgressHUD *hud_;
7480 SectionsView *sections_;
7481 ChangesView *changes_;
7482 ManageView *manage_;
7483 SearchView *search_;
7485 NSMutableArray *details_;
7490 @implementation Cydia
7493 if ([broken_ count] != 0) {
7494 int count = [broken_ count];
7496 UIActionSheet *sheet = [[[UIActionSheet alloc]
7497 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7498 buttons:[NSArray arrayWithObjects:
7499 UCLocalize("FORCIBLY_CLEAR"),
7500 UCLocalize("TEMPORARY_IGNORE"),
7502 defaultButtonIndex:0
7507 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7508 [sheet popupAlertAnimated:YES];
7509 } else if (!Ignored_ && [essential_ count] != 0) {
7510 int count = [essential_ count];
7512 UIActionSheet *sheet = [[[UIActionSheet alloc]
7513 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7514 buttons:[NSArray arrayWithObjects:
7515 UCLocalize("UPGRADE_ESSENTIAL"),
7516 UCLocalize("COMPLETE_UPGRADE"),
7517 UCLocalize("TEMPORARY_IGNORE"),
7519 defaultButtonIndex:0
7524 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7525 [sheet popupAlertAnimated:YES];
7529 - (void) _reloadData {
7532 static bool loaded(false);
7533 UIProgressHUD *hud([self addProgressHUD]);
7534 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7537 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7540 [self removeProgressHUD:hud];
7544 [essential_ removeAllObjects];
7545 [broken_ removeAllObjects];
7547 NSArray *packages = [database_ packages];
7548 for (Package *package in packages) {
7550 [broken_ addObject:package];
7551 if ([package upgradableAndEssential:NO]) {
7552 if ([package essential])
7553 [essential_ addObject:package];
7559 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7560 [buttonbar_ setBadgeValue:badge forButton:3];
7561 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7562 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7563 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7564 [self setApplicationBadge:badge];
7566 [self setApplicationBadgeString:badge];
7568 [buttonbar_ setBadgeValue:nil forButton:3];
7569 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7570 [buttonbar_ setBadgeAnimated:NO forButton:3];
7571 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7572 [self removeApplicationBadge];
7573 else // XXX: maybe use setApplicationBadgeString also?
7574 [self setApplicationIconBadgeNumber:0];
7578 [buttonbar_ setBadgeValue:nil forButton:4];
7582 // XXX: what is this line of code for?
7583 if ([packages count] == 0);
7584 else if (Loaded_ || ManualRefresh) loaded:
7589 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7590 NSTimeInterval interval([update timeIntervalSinceNow]);
7591 if (interval <= 0 && interval > -600)
7599 - (void) _saveConfig {
7602 NSString *error(nil);
7603 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7605 NSError *error(nil);
7606 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7607 NSLog(@"failure to save metadata data: %@", error);
7610 NSLog(@"failure to serialize metadata: %@", error);
7618 - (void) updateData {
7621 /* XXX: this is just stupid */
7622 if (tag_ != 2 && sections_ != nil)
7623 [sections_ reloadData];
7624 if (tag_ != 3 && changes_ != nil)
7625 [changes_ reloadData];
7626 if (tag_ != 5 && search_ != nil)
7627 [search_ reloadData];
7637 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7638 _assert(file != NULL);
7640 NSArray *keys = [Sources_ allKeys];
7642 for (NSString *key in keys) {
7643 NSDictionary *source = [Sources_ objectForKey:key];
7645 fprintf(file, "%s %s %s\n",
7646 [[source objectForKey:@"Type"] UTF8String],
7647 [[source objectForKey:@"URI"] UTF8String],
7648 [[source objectForKey:@"Distribution"] UTF8String]
7657 detachNewThreadSelector:@selector(update_)
7660 title:UCLocalize("UPDATING_SOURCES")
7664 - (void) reloadData {
7665 @synchronized (self) {
7666 if (confirm_ == nil)
7672 pkgProblemResolver *resolver = [database_ resolver];
7674 resolver->InstallProtect();
7675 if (!resolver->Resolve(true))
7679 - (void) popUpBook:(RVBook *)book {
7680 [underlay_ popSubview:book];
7683 - (CGRect) popUpBounds {
7684 return [underlay_ bounds];
7688 [database_ prepare];
7690 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7691 [confirm_ setDelegate:self];
7693 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7694 [page setDelegate:self];
7696 [confirm_ setPage:page];
7697 [self popUpBook:confirm_];
7701 @synchronized (self) {
7706 - (void) clearPackage:(Package *)package {
7707 @synchronized (self) {
7714 - (void) installPackage:(Package *)package {
7715 @synchronized (self) {
7722 - (void) removePackage:(Package *)package {
7723 @synchronized (self) {
7730 - (void) distUpgrade {
7731 @synchronized (self) {
7732 [database_ upgrade];
7738 [self slideUp:[[[UIActionSheet alloc]
7740 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7741 defaultButtonIndex:1
7748 @synchronized (self) {
7751 if (confirm_ != nil) {
7759 [overlay_ removeFromSuperview];
7763 detachNewThreadSelector:@selector(perform)
7766 title:UCLocalize("RUNNING")
7770 - (void) bootstrap_ {
7772 [database_ upgrade];
7773 [database_ prepare];
7774 [database_ perform];
7777 /* XXX: replace and localize */
7778 - (void) bootstrap {
7780 detachNewThreadSelector:@selector(bootstrap_)
7783 title:@"Bootstrap Install"
7787 - (void) progressViewIsComplete:(ProgressView *)progress {
7788 if (confirm_ != nil) {
7789 [underlay_ addSubview:overlay_];
7790 [confirm_ popFromSuperviewAnimated:NO];
7796 - (void) setPage:(RVPage *)page {
7797 [page resetViewAnimated:NO];
7798 [page setDelegate:self];
7799 [book_ setPage:page];
7802 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7803 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7804 [browser loadURL:url];
7808 - (void) _setHomePage {
7809 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7812 - (SectionsView *) sectionsView {
7813 if (sections_ == nil)
7814 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7818 - (void) buttonBarItemTapped:(id)sender {
7819 unsigned tag = [sender tag];
7821 [book_ resetViewAnimated:YES];
7823 } else if (tag_ == 2 && tag != 2)
7824 [[self sectionsView] resetView];
7827 case 1: [self _setHomePage]; break;
7829 case 2: [self setPage:[self sectionsView]]; break;
7830 case 3: [self setPage:changes_]; break;
7831 case 4: [self setPage:manage_]; break;
7832 case 5: [self setPage:search_]; break;
7834 default: _assert(false);
7840 - (void) applicationWillSuspend {
7842 [super applicationWillSuspend];
7845 - (void) askForSettings {
7846 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7848 UIActionSheet *role = [[[UIActionSheet alloc]
7849 initWithTitle:UCLocalize("WHO_ARE_YOU")
7850 buttons:[NSArray arrayWithObjects:
7851 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7852 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7853 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7855 defaultButtonIndex:-1
7860 [role setBodyText:UCLocalize("ROLE_EX")];
7861 [role popupAlertAnimated:YES];
7864 - (void) setPackageView:(PackageView *)view {
7866 [view setPackage:nil];
7867 if ([details_ count] < 3)
7868 [details_ addObject:view];
7872 - (PackageView *) _packageView {
7873 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7876 - (PackageView *) packageView {
7878 size_t count([details_ count]);
7881 view = [self _packageView];
7883 [details_ addObject:[self _packageView]];
7885 view = [[[details_ lastObject] retain] autorelease];
7886 [details_ removeLastObject];
7896 [self setStatusBarShowsProgress:NO];
7897 [self removeProgressHUD:hud_];
7902 pid_t pid = ExecFork();
7904 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7905 perror("launchctl stop");
7912 [self askForSettings];
7917 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7919 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7920 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7921 0, 0, screenrect.size.width, screenrect.size.height - 48
7922 ) database:database_];
7924 [book_ setDelegate:self];
7926 [overlay_ addSubview:book_];
7928 NSArray *buttonitems = [NSArray arrayWithObjects:
7929 [NSDictionary dictionaryWithObjectsAndKeys:
7930 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7931 @"home-up.png", kUIButtonBarButtonInfo,
7932 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7933 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7934 self, kUIButtonBarButtonTarget,
7935 @"Cydia", kUIButtonBarButtonTitle,
7936 @"0", kUIButtonBarButtonType,
7939 [NSDictionary dictionaryWithObjectsAndKeys:
7940 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7941 @"install-up.png", kUIButtonBarButtonInfo,
7942 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7943 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7944 self, kUIButtonBarButtonTarget,
7945 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7946 @"0", kUIButtonBarButtonType,
7949 [NSDictionary dictionaryWithObjectsAndKeys:
7950 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7951 @"changes-up.png", kUIButtonBarButtonInfo,
7952 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7953 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7954 self, kUIButtonBarButtonTarget,
7955 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
7956 @"0", kUIButtonBarButtonType,
7959 [NSDictionary dictionaryWithObjectsAndKeys:
7960 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7961 @"manage-up.png", kUIButtonBarButtonInfo,
7962 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7963 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7964 self, kUIButtonBarButtonTarget,
7965 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
7966 @"0", kUIButtonBarButtonType,
7969 [NSDictionary dictionaryWithObjectsAndKeys:
7970 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7971 @"search-up.png", kUIButtonBarButtonInfo,
7972 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7973 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7974 self, kUIButtonBarButtonTarget,
7975 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
7976 @"0", kUIButtonBarButtonType,
7980 buttonbar_ = [[UIToolbar alloc]
7982 withFrame:CGRectMake(
7983 0, screenrect.size.height - ButtonBarHeight_,
7984 screenrect.size.width, ButtonBarHeight_
7986 withItemList:buttonitems
7989 [buttonbar_ setDelegate:self];
7990 [buttonbar_ setBarStyle:1];
7991 [buttonbar_ setButtonBarTrackingMode:2];
7993 int buttons[5] = {1, 2, 3, 4, 5};
7994 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7995 [buttonbar_ showButtonGroup:0 withDuration:0];
7997 for (int i = 0; i != 5; ++i)
7998 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7999 i * 64 + 2, 1, 60, ButtonBarHeight_
8002 [buttonbar_ showSelectionForButton:1];
8003 [overlay_ addSubview:buttonbar_];
8005 [UIKeyboard initImplementationNow];
8006 CGSize keysize = [UIKeyboard defaultSize];
8007 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8008 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8009 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
8010 [overlay_ addSubview:keyboard_];
8013 [underlay_ addSubview:overlay_];
8017 [self sectionsView];
8018 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
8019 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
8021 manage_ = (ManageView *) [[self
8022 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8023 withClass:[ManageView class]
8026 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8027 [details_ addObject:[self _packageView]];
8028 [details_ addObject:[self _packageView]];
8035 [self _setHomePage];
8038 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
8039 NSString *context([sheet context]);
8041 if ([context isEqualToString:@"missing"])
8043 else if ([context isEqualToString:@"cancel"]) {
8061 @synchronized (self) {
8066 [buttonbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
8070 if (confirm_ != nil) {
8075 } else if ([context isEqualToString:@"fixhalf"]) {
8078 @synchronized (self) {
8079 for (Package *broken in broken_) {
8082 NSString *id = [broken id];
8083 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8084 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8085 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8086 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8095 [broken_ removeAllObjects];
8104 } else if ([context isEqualToString:@"role"]) {
8106 case 1: Role_ = @"User"; break;
8107 case 2: Role_ = @"Hacker"; break;
8108 case 3: Role_ = @"Developer"; break;
8115 bool reset = Settings_ != nil;
8117 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8121 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8131 } else if ([context isEqualToString:@"upgrade"]) {
8134 @synchronized (self) {
8135 for (Package *essential in essential_)
8136 [essential install];
8159 - (void) reorganize { _pooled
8160 system("/usr/libexec/cydia/free.sh");
8161 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
8164 - (void) applicationSuspend:(__GSEvent *)event {
8165 if (hud_ == nil && ![progress_ isRunning])
8166 [super applicationSuspend:event];
8169 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8171 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8174 - (void) _setSuspended:(BOOL)value {
8176 [super _setSuspended:value];
8179 - (UIProgressHUD *) addProgressHUD {
8180 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8181 [window_ setUserInteractionEnabled:NO];
8183 [progress_ addSubview:hud];
8187 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8189 [hud removeFromSuperview];
8190 [window_ setUserInteractionEnabled:YES];
8193 - (RVPage *) pageForPackage:(NSString *)name {
8194 if (Package *package = [database_ packageWithName:name]) {
8195 PackageView *view([self packageView]);
8196 [view setPackage:package];
8199 UIActionSheet *sheet = [[[UIActionSheet alloc]
8200 initWithTitle:UCLocalize("CANNOT_LOCATE_PACKAGE")
8201 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
8202 defaultButtonIndex:0
8207 [sheet setBodyText:[NSString stringWithFormat:UCLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
8209 [sheet popupAlertAnimated:YES];
8214 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8218 NSString *href([url absoluteString]);
8219 if ([href hasPrefix:@"apptapp://package/"])
8220 return [self pageForPackage:[href substringFromIndex:18]];
8222 NSString *scheme([[url scheme] lowercaseString]);
8223 if (![scheme isEqualToString:@"cydia"])
8225 NSString *path([url absoluteString]);
8226 if ([path length] < 8)
8228 path = [path substringFromIndex:8];
8229 if (![path hasPrefix:@"/"])
8230 path = [@"/" stringByAppendingString:path];
8232 if ([path isEqualToString:@"/add-source"])
8233 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8234 else if ([path isEqualToString:@"/storage"])
8235 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8236 else if ([path isEqualToString:@"/sources"])
8237 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8238 else if ([path isEqualToString:@"/packages"])
8239 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8240 else if ([path hasPrefix:@"/url/"])
8241 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8242 else if ([path hasPrefix:@"/launch/"])
8243 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8244 else if ([path hasPrefix:@"/package-settings/"])
8245 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8246 else if ([path hasPrefix:@"/package-signature/"])
8247 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8248 else if ([path hasPrefix:@"/package/"])
8249 return [self pageForPackage:[path substringFromIndex:9]];
8250 else if ([path hasPrefix:@"/files/"]) {
8251 NSString *name = [path substringFromIndex:7];
8253 if (Package *package = [database_ packageWithName:name]) {
8254 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8255 [files setPackage:package];
8263 - (void) applicationOpenURL:(NSURL *)url {
8264 [super applicationOpenURL:url];
8266 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8267 [self setPage:page];
8268 [buttonbar_ showSelectionForButton:tag];
8273 - (void) applicationDidFinishLaunching:(id)unused {
8275 Font12_ = [[UIFont systemFontOfSize:12] retain];
8276 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8277 Font14_ = [[UIFont systemFontOfSize:14] retain];
8278 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8279 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8283 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8284 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8286 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8288 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8289 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
8291 [window_ orderFront:self];
8292 [window_ makeKey:self];
8293 [window_ setHidden:NO];
8295 database_ = [Database sharedInstance];
8296 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8297 [database_ setDelegate:progress_];
8298 [window_ setContentView:progress_];
8300 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8301 [progress_ setContentView:underlay_];
8303 [progress_ resetView];
8306 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8307 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8308 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL /*||
8309 readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL*/ ||
8310 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8311 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8312 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8313 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
8314 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
8316 [self setIdleTimerDisabled:YES];
8318 hud_ = [[self addProgressHUD] retain];
8319 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8321 [self setStatusBarShowsProgress:YES];
8324 detachNewThreadSelector:@selector(reorganize)
8332 - (void) showKeyboard:(BOOL)show {
8333 CGSize keysize = [UIKeyboard defaultSize];
8334 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8335 CGRect keyup = keydown;
8336 keyup.origin.y -= keysize.height;
8338 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8339 [animation setSignificantRectFields:2];
8342 [animation setStartFrame:keydown];
8343 [animation setEndFrame:keyup];
8344 [keyboard_ activate];
8346 [animation setStartFrame:keyup];
8347 [animation setEndFrame:keydown];
8348 [keyboard_ deactivate];
8351 [[UIAnimator sharedAnimator]
8352 addAnimations:[NSArray arrayWithObjects:animation, nil]
8353 withDuration:KeyboardTime_
8358 - (void) slideUp:(UIActionSheet *)alert {
8360 [alert presentSheetFromButtonBar:buttonbar_];
8362 [alert presentSheetInView:overlay_];
8367 void AddPreferences(NSString *plist) { _pooled
8368 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8369 _assert(settings != NULL);
8370 NSMutableArray *items = [settings objectForKey:@"items"];
8374 for (NSMutableDictionary *item in items) {
8375 NSString *label = [item objectForKey:@"label"];
8376 if (label != nil && [label isEqualToString:@"Cydia"]) {
8383 for (size_t i(0); i != [items count]; ++i) {
8384 NSDictionary *item([items objectAtIndex:i]);
8385 NSString *label = [item objectForKey:@"label"];
8386 if (label != nil && [label isEqualToString:@"General"]) {
8387 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8388 @"CydiaSettings", @"bundle",
8389 @"PSLinkCell", @"cell",
8390 [NSNumber numberWithBool:YES], @"hasIcon",
8391 [NSNumber numberWithBool:YES], @"isController",
8393 nil] atIndex:(i + 1)];
8399 _assert([settings writeToFile:plist atomically:YES] == YES);
8404 id Alloc_(id self, SEL selector) {
8405 id object = alloc_(self, selector);
8406 lprintf("[%s]A-%p\n", self->isa->name, object);
8411 id Dealloc_(id self, SEL selector) {
8412 id object = dealloc_(self, selector);
8413 lprintf("[%s]D-%p\n", self->isa->name, object);
8417 Class $WebDefaultUIKitDelegate;
8419 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8421 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8422 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8423 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8424 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8427 int main(int argc, char *argv[]) { _pooled
8430 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8432 /* Library Hacks {{{ */
8433 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8435 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8436 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8437 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8438 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8439 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8442 /* Set Locale {{{ */
8443 Locale_ = CFLocaleCopyCurrent();
8444 Languages_ = [NSLocale preferredLanguages];
8445 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8446 //NSLog(@"%@", [Languages_ description]);
8448 if (Languages_ == nil || [Languages_ count] == 0)
8451 lang = [[Languages_ objectAtIndex:0] UTF8String];
8452 setenv("LANG", lang, true);
8453 //std::setlocale(LC_ALL, lang);
8454 NSLog(@"Setting Language: %s", lang);
8457 // XXX: apr_app_initialize?
8460 /* Parse Arguments {{{ */
8461 bool substrate(false);
8467 for (int argi(1); argi != argc; ++argi)
8468 if (strcmp(argv[argi], "--") == 0) {
8470 argv[argi] = argv[0];
8476 for (int argi(1); argi != arge; ++argi)
8477 if (strcmp(args[argi], "--bootstrap") == 0)
8479 else if (strcmp(args[argi], "--substrate") == 0)
8482 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8487 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8488 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8489 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8490 Sounds_Keyboard_ = [keyboard boolValue];
8493 App_ = [[NSBundle mainBundle] bundlePath];
8494 Home_ = NSHomeDirectory();
8499 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8500 alloc_ = alloc->method_imp;
8501 alloc->method_imp = (IMP) &Alloc_;*/
8503 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8504 dealloc_ = dealloc->method_imp;
8505 dealloc->method_imp = (IMP) &Dealloc_;*/
8510 size = sizeof(maxproc);
8511 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8512 perror("sysctlbyname(\"kern.maxproc\", ?)");
8513 else if (maxproc < 64) {
8515 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8516 perror("sysctlbyname(\"kern.maxproc\", #)");
8519 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8520 char *machine = new char[size];
8521 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8522 perror("sysctlbyname(\"hw.machine\", ?)");
8526 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8528 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8529 Build_ = [system objectForKey:@"ProductBuildVersion"];
8530 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8531 Product_ = [info objectForKey:@"SafariProductVersion"];
8532 Safari_ = [info objectForKey:@"CFBundleVersion"];
8535 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8536 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8538 /* Load Database {{{ */
8540 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8542 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8545 if (Metadata_ == NULL)
8546 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8548 Settings_ = [Metadata_ objectForKey:@"Settings"];
8550 Packages_ = [Metadata_ objectForKey:@"Packages"];
8551 Sections_ = [Metadata_ objectForKey:@"Sections"];
8552 Sources_ = [Metadata_ objectForKey:@"Sources"];
8555 if (Settings_ != nil)
8556 Role_ = [Settings_ objectForKey:@"Role"];
8558 if (Packages_ == nil) {
8559 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8560 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8563 if (Sections_ == nil) {
8564 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8565 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8568 if (Sources_ == nil) {
8569 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8570 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8575 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8578 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8579 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8580 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8581 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8583 if (access("/User", F_OK) != 0) {
8585 system("/usr/libexec/cydia/firmware.sh");
8589 _assert([[NSFileManager defaultManager]
8590 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8591 withIntermediateDirectories:YES
8596 if (access("/tmp/cydia.chk", F_OK) == 0) {
8597 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8598 _assert(errno == ENOENT);
8599 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8600 _assert(errno == ENOENT);
8603 _assert(pkgInitConfig(*_config));
8604 _assert(pkgInitSystem(*_config, _system));
8607 _config->Set("APT::Acquire::Translation", lang);
8608 _config->Set("Acquire::http::Timeout", 15);
8609 _config->Set("Acquire::http::MaxParallel", 4);
8611 /* Color Choices {{{ */
8612 space_ = CGColorSpaceCreateDeviceRGB();
8614 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8615 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8616 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8617 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8618 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8619 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8620 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8621 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8622 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8623 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8624 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8625 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8626 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8627 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8628 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8631 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8632 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8635 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8637 /* UIKit Configuration {{{ */
8638 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8639 if ($GSFontSetUseLegacyFontMetrics != NULL)
8640 $GSFontSetUseLegacyFontMetrics(YES);
8642 UIKeyboardDisableAutomaticAppearance();
8646 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8648 CGColorSpaceRelease(space_);