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/UCPlatform.h"
43 #import "UICaboodle/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 "UICaboodle/BrowserView.h"
117 #import "UICaboodle/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 RecyclePackageViews 1
421 #define AlwaysReload (0 && !ForRelease)
425 #define _trace(args...)
430 #define _profile(name) {
433 #define PrintTimes() do {} while (false)
437 typedef uint32_t (*SKRadixFunction)(id, void *);
439 @interface NSMutableArray (Radix)
440 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
441 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
449 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
450 struct RadixItem_ *lhs(swap), *rhs(swap + count);
452 static const size_t width = 32;
453 static const size_t bits = 11;
454 static const size_t slots = 1 << bits;
455 static const size_t passes = (width + (bits - 1)) / bits;
457 size_t *hist(new size_t[slots]);
459 for (size_t pass(0); pass != passes; ++pass) {
460 memset(hist, 0, sizeof(size_t) * slots);
462 for (size_t i(0); i != count; ++i) {
463 uint32_t key(lhs[i].key);
465 key &= _not(uint32_t) >> width - bits;
470 for (size_t i(0); i != slots; ++i) {
471 size_t local(offset);
476 for (size_t i(0); i != count; ++i) {
477 uint32_t key(lhs[i].key);
479 key &= _not(uint32_t) >> width - bits;
480 rhs[hist[key]++] = lhs[i];
483 RadixItem_ *tmp(lhs);
490 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
491 for (size_t i(0); i != count; ++i)
492 [values addObject:[self objectAtIndex:lhs[i].index]];
493 [self setArray:values];
498 @implementation NSMutableArray (Radix)
500 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
501 size_t count([self count]);
506 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
507 [invocation setSelector:selector];
508 [invocation setArgument:&object atIndex:2];
510 /* XXX: this is an unsafe optimization of doomy hell */
511 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
512 _assert(method != NULL);
513 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
514 _assert(imp != NULL);
517 struct RadixItem_ *swap(new RadixItem_[count * 2]);
519 for (size_t i(0); i != count; ++i) {
520 RadixItem_ &item(swap[i]);
523 id object([self objectAtIndex:i]);
526 [invocation setTarget:object];
528 [invocation getReturnValue:&item.key];
530 item.key = imp(object, selector, object);
534 RadixSort_(self, count, swap);
537 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
538 size_t count([self count]);
539 struct RadixItem_ *swap(new RadixItem_[count * 2]);
541 for (size_t i(0); i != count; ++i) {
542 RadixItem_ &item(swap[i]);
545 id object([self objectAtIndex:i]);
546 item.key = function(object, argument);
549 RadixSort_(self, count, swap);
554 /* Insertion Sort {{{ */
556 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
557 const char *ptr = (const char *)list;
559 CFIndex half = count / 2;
560 const char *probe = ptr + elementSize * half;
561 CFComparisonResult cr = comparator(element, probe, context);
562 if (0 == cr) return (probe - (const char *)list) / elementSize;
563 ptr = (cr < 0) ? ptr : probe + elementSize;
564 count = (cr < 0) ? half : (half + (count & 1) - 1);
566 return (ptr - (const char *)list) / elementSize;
569 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
570 const char *ptr = (const char *)list;
572 CFIndex half = count / 2;
573 const char *probe = ptr + elementSize * half;
574 CFComparisonResult cr = comparator(element, probe, context);
575 if (0 == cr) return (probe - (const char *)list) / elementSize;
576 ptr = (cr < 0) ? ptr : probe + elementSize;
577 count = (cr < 0) ? half : (half + (count & 1) - 1);
579 return (ptr - (const char *)list) / elementSize;
582 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
583 if (range.length == 0)
585 const void **values(new const void *[range.length]);
586 CFArrayGetValues(array, range, values);
588 #if HistogramInsertionSort
589 uint32_t total(0), *offsets(new uint32_t[range.length]);
592 for (CFIndex index(1); index != range.length; ++index) {
593 const void *value(values[index]);
594 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
595 CFIndex correct(index);
596 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
599 if (correct != index) {
600 size_t offset(index - correct);
601 #if HistogramInsertionSort
605 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
607 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
608 values[correct] = value;
612 CFArrayReplaceValues(array, range, values, range.length);
615 #if HistogramInsertionSort
616 for (CFIndex index(0); index != range.length; ++index)
617 if (offsets[index] != 0)
618 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
619 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
626 /* Apple Bug Fixes {{{ */
627 @implementation UIWebDocumentView (Cydia)
629 - (void) _setScrollerOffset:(CGPoint)offset {
630 UIScroller *scroller([self _scroller]);
632 CGSize size([scroller contentSize]);
633 CGSize bounds([scroller bounds].size);
636 max.x = size.width - bounds.width;
637 max.y = size.height - bounds.height;
645 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
646 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
648 [scroller setOffset:offset];
655 kUIControlEventMouseDown = 1 << 0,
656 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
657 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
658 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
659 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
660 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
661 } UIControlEventMasks;
663 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
664 size_t length([self length] - state->state);
667 else if (length > count)
669 for (size_t i(0); i != length; ++i)
670 objects[i] = [self item:state->state++];
671 state->itemsPtr = objects;
672 state->mutationsPtr = (unsigned long *) self;
676 @interface NSString (UIKit)
677 - (NSString *) stringByAddingPercentEscapes;
678 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
681 @interface NSString (Cydia)
682 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
683 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
684 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
685 - (NSComparisonResult) compareByPath:(NSString *)other;
686 - (NSString *) stringByCachingURLWithCurrentCDN;
687 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
690 @implementation NSString (Cydia)
692 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
693 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
696 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
697 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
698 memcpy(data, bytes, length);
699 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
702 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
703 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
706 - (NSComparisonResult) compareByPath:(NSString *)other {
707 NSString *prefix = [self commonPrefixWithString:other options:0];
708 size_t length = [prefix length];
710 NSRange lrange = NSMakeRange(length, [self length] - length);
711 NSRange rrange = NSMakeRange(length, [other length] - length);
713 lrange = [self rangeOfString:@"/" options:0 range:lrange];
714 rrange = [other rangeOfString:@"/" options:0 range:rrange];
716 NSComparisonResult value;
718 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
719 value = NSOrderedSame;
720 else if (lrange.location == NSNotFound)
721 value = NSOrderedAscending;
722 else if (rrange.location == NSNotFound)
723 value = NSOrderedDescending;
725 value = NSOrderedSame;
727 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
728 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
729 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
730 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
732 NSComparisonResult result = [lpath compare:rpath];
733 return result == NSOrderedSame ? value : result;
736 - (NSString *) stringByCachingURLWithCurrentCDN {
738 stringByReplacingOccurrencesOfString:@"://"
739 withString:@"://ne.edgecastcdn.net/8003A4/"
741 /* XXX: this is somewhat inaccurate */
742 range:NSMakeRange(0, 10)
746 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
747 return [(id)CFURLCreateStringByAddingPercentEscapes(
752 kCFStringEncodingUTF8
764 _finline void clear_() {
765 if (cache_ != NULL) {
772 _finline bool empty() const {
776 _finline size_t size() const {
780 _finline char *data() const {
784 _finline void clear() {
789 _finline CYString() :
796 _finline ~CYString() {
800 void operator =(const CYString &rhs) {
804 if (rhs.cache_ == nil)
807 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
810 void set(apr_pool_t *pool, const char *data, size_t size) {
816 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
817 memcpy(temp, data, size);
824 _finline void set(apr_pool_t *pool, const char *data) {
825 set(pool, data, data == NULL ? 0 : strlen(data));
828 _finline void set(apr_pool_t *pool, const std::string &rhs) {
829 set(pool, rhs.data(), rhs.size());
832 bool operator ==(const CYString &rhs) const {
833 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
836 operator CFStringRef() {
837 if (cache_ == NULL) {
840 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
844 _finline operator id() {
845 return (NSString *) static_cast<CFStringRef>(*this);
850 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
853 struct NSStringMapHash :
854 std::unary_function<NSString *, size_t>
856 _finline size_t operator ()(NSString *value) const {
857 return CFStringHashNSString((CFStringRef) value);
861 struct NSStringMapLess :
862 std::binary_function<NSString *, NSString *, bool>
864 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
865 return [lhs compare:rhs] == NSOrderedAscending;
869 struct NSStringMapEqual :
870 std::binary_function<NSString *, NSString *, bool>
872 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
873 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
874 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
875 //[lhs isEqualToString:rhs];
879 /* Perl-Compatible RegEx {{{ */
889 Pcre(const char *regex) :
894 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
897 lprintf("%d:%s\n", offset, error);
901 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
902 matches_ = new int[(capture_ + 1) * 3];
910 NSString *operator [](size_t match) {
911 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
914 bool operator ()(NSString *data) {
915 // XXX: length is for characters, not for bytes
916 return operator ()([data UTF8String], [data length]);
919 bool operator ()(const char *data, size_t size) {
921 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
925 /* Mime Addresses {{{ */
926 @interface Address : NSObject {
932 - (NSString *) address;
934 - (void) setAddress:(NSString *)address;
936 + (Address *) addressWithString:(NSString *)string;
937 - (Address *) initWithString:(NSString *)string;
940 @implementation Address
949 - (NSString *) name {
953 - (NSString *) address {
957 - (void) setAddress:(NSString *)address {
959 [address_ autorelease];
963 address_ = [address retain];
966 + (Address *) addressWithString:(NSString *)string {
967 return [[[Address alloc] initWithString:string] autorelease];
970 + (NSArray *) _attributeKeys {
971 return [NSArray arrayWithObjects:@"address", @"name", nil];
974 - (NSArray *) attributeKeys {
975 return [[self class] _attributeKeys];
978 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
979 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
982 - (Address *) initWithString:(NSString *)string {
983 if ((self = [super init]) != nil) {
984 const char *data = [string UTF8String];
985 size_t size = [string length];
987 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
989 if (address_r(data, size)) {
990 name_ = [address_r[1] retain];
991 address_ = [address_r[2] retain];
993 name_ = [string retain];
1001 /* CoreGraphics Primitives {{{ */
1012 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1015 Set(space, red, green, blue, alpha);
1020 CGColorRelease(color_);
1027 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1029 float color[] = {red, green, blue, alpha};
1030 color_ = CGColorCreate(space, color);
1033 operator CGColorRef() {
1039 extern "C" void UISetColor(CGColorRef color);
1041 /* Random Global Variables {{{ */
1042 static const int PulseInterval_ = 50000;
1043 static const int ButtonBarHeight_ = 48;
1044 static const float KeyboardTime_ = 0.3f;
1046 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1047 #define NotifyConfig_ "/etc/notify.conf"
1049 static bool Queuing_;
1051 static CGColor Blue_;
1052 static CGColor Blueish_;
1053 static CGColor Black_;
1054 static CGColor Off_;
1055 static CGColor White_;
1056 static CGColor Gray_;
1057 static CGColor Green_;
1058 static CGColor Purple_;
1059 static CGColor Purplish_;
1061 static UIColor *InstallingColor_;
1062 static UIColor *RemovingColor_;
1064 static NSString *App_;
1065 static NSString *Home_;
1066 static BOOL Sounds_Keyboard_;
1068 static BOOL Advanced_;
1069 static BOOL Loaded_;
1070 static BOOL Ignored_;
1072 static UIFont *Font12_;
1073 static UIFont *Font12Bold_;
1074 static UIFont *Font14_;
1075 static UIFont *Font18Bold_;
1076 static UIFont *Font22Bold_;
1078 static const char *Machine_ = NULL;
1079 static const NSString *UniqueID_ = nil;
1080 static const NSString *Build_ = nil;
1081 static const NSString *Product_ = nil;
1082 static const NSString *Safari_ = nil;
1084 CFLocaleRef Locale_;
1085 NSArray *Languages_;
1086 CGColorSpaceRef space_;
1091 static NSDictionary *SectionMap_;
1092 static NSMutableDictionary *Metadata_;
1093 static _transient NSMutableDictionary *Settings_;
1094 static _transient NSString *Role_;
1095 static _transient NSMutableDictionary *Packages_;
1096 static _transient NSMutableDictionary *Sections_;
1097 static _transient NSMutableDictionary *Sources_;
1098 static bool Changed_;
1099 static NSDate *now_;
1102 static NSMutableArray *Documents_;
1105 NSString *GetLastUpdate() {
1106 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1109 return UCLocalize("NEVER_OR_UNKNOWN");
1111 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1112 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1114 CFRelease(formatter);
1116 return [(NSString *) formatted autorelease];
1119 /* Display Helpers {{{ */
1120 inline float Interpolate(float begin, float end, float fraction) {
1121 return (end - begin) * fraction + begin;
1124 /* XXX: localize this! */
1125 NSString *SizeString(double size) {
1126 bool negative = size < 0;
1131 while (size > 1024) {
1136 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1138 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1141 static _finline CFStringRef CFCString(const char *value) {
1142 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1145 const char *StripVersion_(const char *version) {
1146 const char *colon(strchr(version, ':'));
1148 version = colon + 1;
1152 CFStringRef StripVersion(const char *version) {
1153 const char *colon(strchr(version, ':'));
1155 version = colon + 1;
1156 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1158 return CFCString(version);
1161 NSString *LocalizeSection(NSString *section) {
1162 static Pcre title_r("^(.*?) \\((.*)\\)$");
1163 if (title_r(section)) {
1164 NSString *parent(title_r[1]);
1165 NSString *child(title_r[2]);
1167 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1168 LocalizeSection(parent),
1169 LocalizeSection(child)
1173 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1176 NSString *Simplify(NSString *title) {
1177 const char *data = [title UTF8String];
1178 size_t size = [title length];
1180 static Pcre square_r("^\\[(.*)\\]$");
1181 if (square_r(data, size))
1182 return Simplify(square_r[1]);
1184 static Pcre paren_r("^\\((.*)\\)$");
1185 if (paren_r(data, size))
1186 return Simplify(paren_r[1]);
1188 static Pcre title_r("^(.*?) \\((.*)\\)$");
1189 if (title_r(data, size))
1190 return Simplify(title_r[1]);
1196 bool isSectionVisible(NSString *section) {
1197 NSDictionary *metadata([Sections_ objectForKey:section]);
1198 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1199 return hidden == nil || ![hidden boolValue];
1202 /* Delegate Prototypes {{{ */
1206 @interface NSObject (ProgressDelegate)
1209 @implementation NSObject(ProgressDelegate)
1211 - (void) _setProgressError:(NSArray *)args {
1212 [self performSelector:@selector(setProgressError:forPackage:)
1213 withObject:[args objectAtIndex:0]
1214 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1220 @protocol ProgressDelegate
1221 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1222 - (void) setProgressTitle:(NSString *)title;
1223 - (void) setProgressPercent:(float)percent;
1224 - (void) startProgress;
1225 - (void) addProgressOutput:(NSString *)output;
1226 - (bool) isCancelling:(size_t)received;
1229 @protocol ConfigurationDelegate
1230 - (void) repairWithSelector:(SEL)selector;
1231 - (void) setConfigurationData:(NSString *)data;
1236 @protocol CydiaDelegate
1237 - (void) setPackageView:(PackageView *)view;
1238 - (void) clearPackage:(Package *)package;
1239 - (void) installPackage:(Package *)package;
1240 - (void) removePackage:(Package *)package;
1241 - (void) slideUp:(UIActionSheet *)alert;
1242 - (void) distUpgrade;
1243 - (void) updateData;
1245 - (void) askForSettings;
1246 - (UIProgressHUD *) addProgressHUD;
1247 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1248 - (RVPage *) pageForPackage:(NSString *)name;
1249 - (PackageView *) packageView;
1253 /* Status Delegation {{{ */
1255 public pkgAcquireStatus
1258 _transient NSObject<ProgressDelegate> *delegate_;
1266 void setDelegate(id delegate) {
1267 delegate_ = delegate;
1270 virtual bool MediaChange(std::string media, std::string drive) {
1274 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1277 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1278 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1279 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1282 virtual void Done(pkgAcquire::ItemDesc &item) {
1285 virtual void Fail(pkgAcquire::ItemDesc &item) {
1287 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1288 item.Owner->Status == pkgAcquire::Item::StatDone
1292 std::string &error(item.Owner->ErrorText);
1296 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1297 NSArray *fields([description componentsSeparatedByString:@" "]);
1298 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1300 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1301 withObject:[NSArray arrayWithObjects:
1302 [NSString stringWithUTF8String:error.c_str()],
1309 virtual bool Pulse(pkgAcquire *Owner) {
1310 bool value = pkgAcquireStatus::Pulse(Owner);
1313 double(CurrentBytes + CurrentItems) /
1314 double(TotalBytes + TotalItems)
1317 [delegate_ setProgressPercent:percent];
1318 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1321 virtual void Start() {
1322 [delegate_ startProgress];
1325 virtual void Stop() {
1329 /* Progress Delegation {{{ */
1334 _transient id<ProgressDelegate> delegate_;
1337 virtual void Update() {
1338 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1339 [delegate_ setProgressPercent:(Percent / 100)];*/
1348 void setDelegate(id delegate) {
1349 delegate_ = delegate;
1352 virtual void Done() {
1353 //[delegate_ setProgressPercent:1];
1358 /* Database Interface {{{ */
1359 typedef std::map< unsigned long, _H<Source> > SourceMap;
1361 @interface Database : NSObject {
1367 pkgCacheFile cache_;
1368 pkgDepCache::Policy *policy_;
1369 pkgRecords *records_;
1370 pkgProblemResolver *resolver_;
1371 pkgAcquire *fetcher_;
1373 SPtr<pkgPackageManager> manager_;
1374 pkgSourceList *list_;
1377 NSMutableArray *packages_;
1379 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1388 + (Database *) sharedInstance;
1391 - (void) _readCydia:(NSNumber *)fd;
1392 - (void) _readStatus:(NSNumber *)fd;
1393 - (void) _readOutput:(NSNumber *)fd;
1397 - (Package *) packageWithName:(NSString *)name;
1399 - (pkgCacheFile &) cache;
1400 - (pkgDepCache::Policy *) policy;
1401 - (pkgRecords *) records;
1402 - (pkgProblemResolver *) resolver;
1403 - (pkgAcquire &) fetcher;
1404 - (pkgSourceList &) list;
1405 - (NSArray *) packages;
1406 - (NSArray *) sources;
1407 - (void) reloadData;
1415 - (void) setVisible;
1417 - (NSString *) updateWithStatus:(Status &)status;
1419 - (void) setDelegate:(id)delegate;
1420 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1424 /* Source Class {{{ */
1425 @interface Source : NSObject {
1426 CYString depiction_;
1427 CYString description_;
1433 CYString distribution_;
1439 CYString defaultIcon_;
1441 NSDictionary *record_;
1445 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1447 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1449 - (NSString *) depictionForPackage:(NSString *)package;
1450 - (NSString *) supportForPackage:(NSString *)package;
1452 - (NSDictionary *) record;
1456 - (NSString *) distribution;
1457 - (NSString *) type;
1459 - (NSString *) host;
1461 - (NSString *) name;
1462 - (NSString *) description;
1463 - (NSString *) label;
1464 - (NSString *) origin;
1465 - (NSString *) version;
1467 - (NSString *) defaultIcon;
1471 @implementation Source
1475 distribution_.clear();
1478 description_.clear();
1484 defaultIcon_.clear();
1486 if (record_ != nil) {
1496 if (authority_ != nil) {
1497 [authority_ release];
1507 + (NSArray *) _attributeKeys {
1508 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1511 - (NSArray *) attributeKeys {
1512 return [[self class] _attributeKeys];
1515 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1516 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1519 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1522 trusted_ = index->IsTrusted();
1524 uri_.set(pool, index->GetURI());
1525 distribution_.set(pool, index->GetDist());
1526 type_.set(pool, index->GetType());
1528 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1529 if (dindex != NULL) {
1531 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1534 pkgTagFile tags(&fd);
1536 pkgTagSection section;
1543 {"default-icon", &defaultIcon_},
1544 {"depiction", &depiction_},
1545 {"description", &description_},
1547 {"origin", &origin_},
1548 {"support", &support_},
1549 {"version", &version_},
1552 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1553 const char *start, *end;
1555 if (section.Find(names[i].name_, start, end)) {
1556 CYString &value(*names[i].value_);
1557 value.set(pool, start, end - start);
1563 record_ = [Sources_ objectForKey:[self key]];
1565 record_ = [record_ retain];
1567 NSURL *url([NSURL URLWithString:uri_]);
1571 host_ = [[host_ lowercaseString] retain];
1574 authority_ = [host_ retain];
1576 authority_ = [url path];
1579 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1580 if ((self = [super init]) != nil) {
1581 [self setMetaIndex:index inPool:pool];
1585 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1586 NSDictionary *lhr = [self record];
1587 NSDictionary *rhr = [source record];
1590 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1592 NSString *lhs = [self name];
1593 NSString *rhs = [source name];
1595 if ([lhs length] != 0 && [rhs length] != 0) {
1596 unichar lhc = [lhs characterAtIndex:0];
1597 unichar rhc = [rhs characterAtIndex:0];
1599 if (isalpha(lhc) && !isalpha(rhc))
1600 return NSOrderedAscending;
1601 else if (!isalpha(lhc) && isalpha(rhc))
1602 return NSOrderedDescending;
1605 return [lhs compare:rhs options:LaxCompareOptions_];
1608 - (NSString *) depictionForPackage:(NSString *)package {
1609 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1612 - (NSString *) supportForPackage:(NSString *)package {
1613 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1616 - (NSDictionary *) record {
1624 - (NSString *) uri {
1628 - (NSString *) distribution {
1629 return distribution_;
1632 - (NSString *) type {
1636 - (NSString *) key {
1637 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1640 - (NSString *) host {
1644 - (NSString *) name {
1645 return origin_.empty() ? authority_ : origin_;
1648 - (NSString *) description {
1649 return description_;
1652 - (NSString *) label {
1653 return label_.empty() ? authority_ : label_;
1656 - (NSString *) origin {
1660 - (NSString *) version {
1664 - (NSString *) defaultIcon {
1665 return defaultIcon_;
1670 /* Relationship Class {{{ */
1671 @interface Relationship : NSObject {
1676 - (NSString *) type;
1678 - (NSString *) name;
1682 @implementation Relationship
1690 - (NSString *) type {
1698 - (NSString *) name {
1705 /* Package Class {{{ */
1706 @interface Package : NSObject {
1710 pkgCache::VerIterator version_;
1711 pkgCache::PkgIterator iterator_;
1712 _transient Database *database_;
1713 pkgCache::VerFileIterator file_;
1720 NSString *section$_;
1726 CYString installed_;
1732 CYString depiction_;
1743 NSMutableArray *tags_;
1746 NSArray *relationships_;
1748 NSMutableDictionary *metadata_;
1749 _transient NSDate *firstSeen_;
1750 _transient NSDate *lastSeen_;
1754 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1755 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1757 - (pkgCache::PkgIterator) iterator;
1760 - (NSString *) section;
1761 - (NSString *) simpleSection;
1763 - (NSString *) longSection;
1764 - (NSString *) shortSection;
1768 - (Address *) maintainer;
1770 - (NSString *) longDescription;
1771 - (NSString *) shortDescription;
1774 - (NSMutableDictionary *) metadata;
1776 - (BOOL) subscribed;
1779 - (NSString *) latest;
1780 - (NSString *) installed;
1781 - (BOOL) uninstalled;
1784 - (BOOL) upgradableAndEssential:(BOOL)essential;
1787 - (BOOL) unfiltered;
1791 - (BOOL) halfConfigured;
1792 - (BOOL) halfInstalled;
1794 - (NSString *) mode;
1796 - (void) setVisible;
1799 - (NSString *) name;
1801 - (NSString *) homepage;
1802 - (NSString *) depiction;
1803 - (Address *) author;
1805 - (NSString *) support;
1807 - (NSArray *) files;
1808 - (NSArray *) relationships;
1809 - (NSArray *) warnings;
1810 - (NSArray *) applications;
1812 - (Source *) source;
1813 - (NSString *) role;
1815 - (BOOL) matches:(NSString *)text;
1817 - (bool) hasSupportingRole;
1818 - (BOOL) hasTag:(NSString *)tag;
1819 - (NSString *) primaryPurpose;
1820 - (NSArray *) purposes;
1821 - (bool) isCommercial;
1823 - (CYString &) cyname;
1825 - (uint32_t) compareBySection:(NSArray *)sections;
1827 - (uint32_t) compareForChanges;
1832 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1833 - (bool) isInstalledAndVisible:(NSNumber *)number;
1834 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1835 - (bool) isVisibleInSource:(Source *)source;
1839 uint32_t PackageChangesRadix(Package *self, void *) {
1844 uint32_t timestamp : 30;
1845 uint32_t ignored : 1;
1846 uint32_t upgradable : 1;
1850 bool upgradable([self upgradableAndEssential:YES]);
1851 value.bits.upgradable = upgradable ? 1 : 0;
1854 value.bits.timestamp = 0;
1855 value.bits.ignored = [self ignored] ? 0 : 1;
1856 value.bits.upgradable = 1;
1858 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1859 value.bits.ignored = 0;
1860 value.bits.upgradable = 0;
1863 return _not(uint32_t) - value.key;
1866 _finline static void Stifle(uint8_t &value) {
1869 uint32_t PackagePrefixRadix(Package *self, void *context) {
1870 size_t offset(reinterpret_cast<size_t>(context));
1871 CYString &name([self cyname]);
1873 size_t size(name.size());
1876 char *text(name.data());
1879 if (!isdigit(text[0]))
1883 while (size != digits && isdigit(text[digits]))
1893 if (offset == 0 && zeros != 0) {
1894 memset(data, '0', zeros);
1895 memcpy(data + zeros, text, 4 - zeros);
1897 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1898 if (size <= offset - zeros)
1901 text += offset - zeros;
1902 size -= offset - zeros;
1905 memcpy(data, text, 4);
1907 memcpy(data, text, size);
1908 memset(data + size, 0, 4 - size);
1911 for (size_t i(0); i != 4; ++i)
1912 if (isalpha(data[i]))
1917 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1919 /* XXX: ntohl may be more honest */
1920 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1923 CYString &(*PackageName)(Package *self, SEL sel);
1925 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1926 _profile(PackageNameCompare)
1927 CYString &lhi(PackageName(lhs, @selector(cyname)));
1928 CYString &rhi(PackageName(rhs, @selector(cyname)));
1929 CFStringRef lhn(lhi), rhn(rhi);
1931 _profile(PackageNameCompare$NumbersLast)
1932 if (!lhi.empty() && !rhi.empty()) {
1933 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1934 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1935 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1936 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1937 return lha ? NSOrderedAscending : NSOrderedDescending;
1941 CFIndex length = CFStringGetLength(lhn);
1943 _profile(PackageNameCompare$Compare)
1944 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1949 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1950 return PackageNameCompare(*lhs, *rhs, context);
1953 struct PackageNameOrdering :
1954 std::binary_function<Package *, Package *, bool>
1956 _finline bool operator ()(Package *lhs, Package *rhs) const {
1957 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1961 @implementation Package
1963 - (NSString *) description {
1964 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1970 if (section$_ != nil)
1971 [section$_ release];
1976 if (sponsor$_ != nil)
1977 [sponsor$_ release];
1978 if (author$_ != nil)
1985 if (relationships_ != nil)
1986 [relationships_ release];
1987 if (metadata_ != nil)
1988 [metadata_ release];
1993 + (NSString *) webScriptNameForSelector:(SEL)selector {
1994 if (selector == @selector(hasTag:))
2000 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2001 return [self webScriptNameForSelector:selector] == nil;
2004 + (NSArray *) _attributeKeys {
2005 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];
2008 - (NSArray *) attributeKeys {
2009 return [[self class] _attributeKeys];
2012 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2013 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2023 _profile(Package$parse)
2024 pkgRecords::Parser *parser;
2026 _profile(Package$parse$Lookup)
2027 parser = &[database_ records]->Lookup(file_);
2032 _profile(Package$parse$Find)
2038 {"depiction", &depiction_},
2039 {"homepage", &homepage_},
2040 {"website", &website},
2042 {"support", &support_},
2043 {"sponsor", &sponsor_},
2044 {"author", &author_},
2047 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2048 const char *start, *end;
2050 if (parser->Find(names[i].name_, start, end)) {
2051 CYString &value(*names[i].value_);
2052 _profile(Package$parse$Value)
2053 value.set(pool_, start, end - start);
2059 _profile(Package$parse$Tagline)
2060 const char *start, *end;
2061 if (parser->ShortDesc(start, end)) {
2062 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2065 while (stop != start && stop[-1] == '\r')
2067 tagline_.set(pool_, start, stop - start);
2071 _profile(Package$parse$Retain)
2072 if (homepage_.empty())
2073 homepage_ = website;
2074 if (homepage_ == depiction_)
2080 - (void) setVisible {
2081 visible_ = required_ && [self hasSupportingRole] && [self unfiltered];
2084 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2085 if ((self = [super init]) != nil) {
2086 _profile(Package$initWithVersion)
2087 @synchronized (database) {
2088 era_ = [database era];
2092 iterator_ = version.ParentPkg();
2093 database_ = database;
2095 _profile(Package$initWithVersion$Latest)
2096 latest_ = (NSString *) StripVersion(version_.VerStr());
2099 pkgCache::VerIterator current;
2100 _profile(Package$initWithVersion$Versions)
2101 current = iterator_.CurrentVer();
2103 installed_.set(pool_, StripVersion_(current.VerStr()));
2105 if (!version_.end())
2106 file_ = version_.FileList();
2108 pkgCache &cache([database_ cache]);
2109 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2113 _profile(Package$initWithVersion$Name)
2114 id_.set(pool_, iterator_.Name());
2115 name_.set(pool, iterator_.Display());
2119 _profile(Package$initWithVersion$Source)
2120 source_ = [database_ getSource:file_.File()];
2129 _profile(Package$initWithVersion$Tags)
2130 pkgCache::TagIterator tag(iterator_.TagList());
2132 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2134 const char *name(tag.Name());
2135 [tags_ addObject:(NSString *)CFCString(name)];
2136 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2137 role_ = (NSString *) CFCString(name + 6);
2138 if (required_ && strncmp(name, "require::", 9) == 0 && (
2143 } while (!tag.end());
2147 bool changed(false);
2148 NSString *key([id_ lowercaseString]);
2150 _profile(Package$initWithVersion$Metadata)
2151 metadata_ = [Packages_ objectForKey:key];
2153 if (metadata_ == nil) {
2156 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2157 firstSeen_, @"FirstSeen",
2158 latest_, @"LastVersion",
2163 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2164 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2166 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2167 subscribed_ = [subscribed boolValue];
2169 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2171 if (firstSeen_ == nil) {
2172 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2173 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2177 if (version == nil) {
2178 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2181 if (![version isEqualToString:latest_]) {
2182 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2184 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2189 metadata_ = [metadata_ retain];
2192 [Packages_ setObject:metadata_ forKey:key];
2197 _profile(Package$initWithVersion$Section)
2198 section_.set(pool_, iterator_.Section());
2201 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2203 } _end } return self;
2206 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2207 @synchronized ([Database class]) {
2208 pkgCache::VerIterator version;
2210 _profile(Package$packageWithIterator$GetCandidateVer)
2211 version = [database policy]->GetCandidateVer(iterator);
2217 return [[[Package alloc]
2218 initWithVersion:version
2225 - (pkgCache::PkgIterator) iterator {
2229 - (NSString *) section {
2230 if (section$_ == nil) {
2231 if (section_.empty())
2234 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2235 NSString *name(section_);
2238 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2239 if (NSString *rename = [value objectForKey:@"Rename"]) {
2244 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2248 - (NSString *) simpleSection {
2249 if (NSString *section = [self section])
2250 return Simplify(section);
2255 - (NSString *) longSection {
2256 return LocalizeSection([self section]);
2259 - (NSString *) shortSection {
2260 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2263 - (NSString *) uri {
2266 pkgIndexFile *index;
2267 pkgCache::PkgFileIterator file(file_.File());
2268 if (![database_ list].FindIndex(file, index))
2270 return [NSString stringWithUTF8String:iterator_->Path];
2271 //return [NSString stringWithUTF8String:file.Site()];
2272 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2276 - (Address *) maintainer {
2279 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2280 const std::string &maintainer(parser->Maintainer());
2281 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2285 return version_.end() ? 0 : version_->InstalledSize;
2288 - (NSString *) longDescription {
2291 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2292 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2294 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2295 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2296 if ([lines count] < 2)
2299 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2300 for (size_t i(1), e([lines count]); i != e; ++i) {
2301 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2302 [trimmed addObject:trim];
2305 return [trimmed componentsJoinedByString:@"\n"];
2308 - (NSString *) shortDescription {
2313 _profile(Package$index)
2314 CFStringRef name((CFStringRef) [self name]);
2315 if (CFStringGetLength(name) == 0)
2317 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2318 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2320 return toupper(character);
2324 - (NSMutableDictionary *) metadata {
2329 if (subscribed_ && lastSeen_ != nil)
2334 - (BOOL) subscribed {
2339 NSDictionary *metadata([self metadata]);
2340 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2341 return [ignored boolValue];
2346 - (NSString *) latest {
2350 - (NSString *) installed {
2354 - (BOOL) uninstalled {
2355 return installed_.empty();
2359 return !version_.end();
2362 - (BOOL) upgradableAndEssential:(BOOL)essential {
2363 _profile(Package$upgradableAndEssential)
2364 pkgCache::VerIterator current(iterator_.CurrentVer());
2366 return essential && essential_ && visible_;
2368 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2372 - (BOOL) essential {
2377 return [database_ cache][iterator_].InstBroken();
2380 - (BOOL) unfiltered {
2381 NSString *section([self section]);
2382 return section == nil || isSectionVisible(section);
2390 unsigned char current(iterator_->CurrentState);
2391 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2394 - (BOOL) halfConfigured {
2395 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2398 - (BOOL) halfInstalled {
2399 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2403 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2404 return state.Mode != pkgDepCache::ModeKeep;
2407 - (NSString *) mode {
2408 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2410 switch (state.Mode) {
2411 case pkgDepCache::ModeDelete:
2412 if ((state.iFlags & pkgDepCache::Purge) != 0)
2416 case pkgDepCache::ModeKeep:
2417 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2418 return @"REINSTALL";
2419 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2423 case pkgDepCache::ModeInstall:
2424 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2425 return @"REINSTALL";
2426 else*/ switch (state.Status) {
2428 return @"DOWNGRADE";
2434 return @"NEW_INSTALL";
2447 - (NSString *) name {
2448 return name_.empty() ? id_ : name_;
2451 - (UIImage *) icon {
2452 NSString *section = [self simpleSection];
2456 if ([icon_ hasPrefix:@"file:///"])
2457 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2458 if (icon == nil) if (section != nil)
2459 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2460 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2461 if ([dicon hasPrefix:@"file:///"])
2462 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2464 icon = [UIImage applicationImageNamed:@"unknown.png"];
2468 - (NSString *) homepage {
2472 - (NSString *) depiction {
2473 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2476 - (Address *) sponsor {
2477 if (sponsor$_ == nil) {
2478 if (sponsor_.empty())
2480 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2484 - (Address *) author {
2485 if (author$_ == nil) {
2486 if (author_.empty())
2488 author$_ = [[Address addressWithString:author_] retain];
2492 - (NSString *) support {
2493 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2496 - (NSArray *) files {
2497 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2498 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2501 fin.open([path UTF8String]);
2506 while (std::getline(fin, line))
2507 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2512 - (NSArray *) relationships {
2513 return relationships_;
2516 - (NSArray *) warnings {
2517 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2518 const char *name(iterator_.Name());
2520 size_t length(strlen(name));
2521 if (length < 2) invalid:
2522 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2523 else for (size_t i(0); i != length; ++i)
2525 /* XXX: technically this is not allowed */
2526 (name[i] < 'A' || name[i] > 'Z') &&
2527 (name[i] < 'a' || name[i] > 'z') &&
2528 (name[i] < '0' || name[i] > '9') &&
2529 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2532 if (strcmp(name, "cydia") != 0) {
2535 bool _private = false;
2538 bool repository = [[self section] isEqualToString:@"Repositories"];
2540 if (NSArray *files = [self files])
2541 for (NSString *file in files)
2542 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2544 else if (!user && [file isEqualToString:@"/User"])
2546 else if (!_private && [file isEqualToString:@"/private"])
2548 else if (!stash && [file isEqualToString:@"/var/stash"])
2551 /* XXX: this is not sensitive enough. only some folders are valid. */
2552 if (cydia && !repository)
2553 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2555 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2557 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2559 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2562 return [warnings count] == 0 ? nil : warnings;
2565 - (NSArray *) applications {
2566 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2568 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2570 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2571 if (NSArray *files = [self files])
2572 for (NSString *file in files)
2573 if (application_r(file)) {
2574 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2575 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2576 if ([id isEqualToString:me])
2579 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2581 display = application_r[1];
2583 NSString *bundle([file stringByDeletingLastPathComponent]);
2584 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2585 if (icon == nil || [icon length] == 0)
2587 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2589 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2590 [applications addObject:application];
2592 [application addObject:id];
2593 [application addObject:display];
2594 [application addObject:url];
2597 return [applications count] == 0 ? nil : applications;
2600 - (Source *) source {
2602 @synchronized (database_) {
2603 if ([database_ era] != era_ || file_.end())
2606 source_ = [database_ getSource:file_.File()];
2618 - (NSString *) role {
2622 - (BOOL) matches:(NSString *)text {
2628 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2629 if (range.location != NSNotFound)
2632 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2633 if (range.location != NSNotFound)
2636 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2637 if (range.location != NSNotFound)
2643 - (bool) hasSupportingRole {
2646 if ([role_ isEqualToString:@"enduser"])
2648 if ([Role_ isEqualToString:@"User"])
2650 if ([role_ isEqualToString:@"hacker"])
2652 if ([Role_ isEqualToString:@"Hacker"])
2654 if ([role_ isEqualToString:@"developer"])
2656 if ([Role_ isEqualToString:@"Developer"])
2661 - (BOOL) hasTag:(NSString *)tag {
2662 return tags_ == nil ? NO : [tags_ containsObject:tag];
2665 - (NSString *) primaryPurpose {
2666 for (NSString *tag in tags_)
2667 if ([tag hasPrefix:@"purpose::"])
2668 return [tag substringFromIndex:9];
2672 - (NSArray *) purposes {
2673 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2674 for (NSString *tag in tags_)
2675 if ([tag hasPrefix:@"purpose::"])
2676 [purposes addObject:[tag substringFromIndex:9]];
2677 return [purposes count] == 0 ? nil : purposes;
2680 - (bool) isCommercial {
2681 return [self hasTag:@"cydia::commercial"];
2684 - (CYString &) cyname {
2685 return name_.empty() ? id_ : name_;
2688 - (uint32_t) compareBySection:(NSArray *)sections {
2689 NSString *section([self section]);
2690 for (size_t i(0), e([sections count]); i != e; ++i) {
2691 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2695 return _not(uint32_t);
2698 - (uint32_t) compareForChanges {
2703 uint32_t timestamp : 30;
2704 uint32_t ignored : 1;
2705 uint32_t upgradable : 1;
2709 bool upgradable([self upgradableAndEssential:YES]);
2710 value.bits.upgradable = upgradable ? 1 : 0;
2713 value.bits.timestamp = 0;
2714 value.bits.ignored = [self ignored] ? 0 : 1;
2715 value.bits.upgradable = 1;
2717 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2718 value.bits.ignored = 0;
2719 value.bits.upgradable = 0;
2722 return _not(uint32_t) - value.key;
2726 pkgProblemResolver *resolver = [database_ resolver];
2727 resolver->Clear(iterator_);
2728 resolver->Protect(iterator_);
2732 pkgProblemResolver *resolver = [database_ resolver];
2733 resolver->Clear(iterator_);
2734 resolver->Protect(iterator_);
2735 pkgCacheFile &cache([database_ cache]);
2736 cache->MarkInstall(iterator_, false);
2737 pkgDepCache::StateCache &state((*cache)[iterator_]);
2738 if (!state.Install())
2739 cache->SetReInstall(iterator_, true);
2743 pkgProblemResolver *resolver = [database_ resolver];
2744 resolver->Clear(iterator_);
2745 resolver->Protect(iterator_);
2746 resolver->Remove(iterator_);
2747 [database_ cache]->MarkDelete(iterator_, true);
2750 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2751 _profile(Package$isUnfilteredAndSearchedForBy)
2754 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2755 value &= [self unfiltered];
2758 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2759 value &= [self matches:search];
2766 - (bool) isInstalledAndVisible:(NSNumber *)number {
2767 return (![number boolValue] || [self visible]) && ![self uninstalled];
2770 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2771 NSString *section = [self section];
2775 [self uninstalled] && (
2777 section == nil && [name length] == 0 ||
2778 [name isEqualToString:section]
2782 - (bool) isVisibleInSource:(Source *)source {
2783 return [self source] == source && [self visible];
2788 /* Section Class {{{ */
2789 @interface Section : NSObject {
2794 NSString *localized_;
2797 - (NSComparisonResult) compareByLocalized:(Section *)section;
2798 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2799 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2800 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2801 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2802 - (NSString *) name;
2809 - (void) addToCount;
2811 - (void) setCount:(size_t)count;
2812 - (NSString *) localized;
2816 @implementation Section
2820 if (localized_ != nil)
2821 [localized_ release];
2825 - (NSComparisonResult) compareByLocalized:(Section *)section {
2826 NSString *lhs(localized_);
2827 NSString *rhs([section localized]);
2829 /*if ([lhs length] != 0 && [rhs length] != 0) {
2830 unichar lhc = [lhs characterAtIndex:0];
2831 unichar rhc = [rhs characterAtIndex:0];
2833 if (isalpha(lhc) && !isalpha(rhc))
2834 return NSOrderedAscending;
2835 else if (!isalpha(lhc) && isalpha(rhc))
2836 return NSOrderedDescending;
2839 return [lhs compare:rhs options:LaxCompareOptions_];
2842 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2843 if ((self = [self initWithName:name localize:NO]) != nil) {
2844 if (localized != nil)
2845 localized_ = [localized retain];
2849 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2850 return [self initWithName:name row:0 localize:localize];
2853 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2854 if ((self = [super init]) != nil) {
2855 name_ = [name retain];
2859 localized_ = [LocalizeSection(name_) retain];
2863 /* XXX: localize the index thingees */
2864 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2865 if ((self = [super init]) != nil) {
2866 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2872 - (NSString *) name {
2892 - (void) addToCount {
2896 - (void) setCount:(size_t)count {
2900 - (NSString *) localized {
2908 static NSArray *Finishes_;
2910 /* Database Implementation {{{ */
2911 @implementation Database
2913 + (Database *) sharedInstance {
2914 static Database *instance;
2915 if (instance == nil)
2916 instance = [[Database alloc] init];
2926 NSRecycleZone(zone_);
2927 // XXX: malloc_destroy_zone(zone_);
2928 apr_pool_destroy(pool_);
2932 - (void) _readCydia:(NSNumber *)fd { _pooled
2933 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2934 std::istream is(&ib);
2937 static Pcre finish_r("^finish:([^:]*)$");
2939 while (std::getline(is, line)) {
2940 const char *data(line.c_str());
2941 size_t size = line.size();
2942 lprintf("C:%s\n", data);
2944 if (finish_r(data, size)) {
2945 NSString *finish = finish_r[1];
2946 int index = [Finishes_ indexOfObject:finish];
2947 if (index != INT_MAX && index > Finish_)
2955 - (void) _readStatus:(NSNumber *)fd { _pooled
2956 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2957 std::istream is(&ib);
2960 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2961 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2963 while (std::getline(is, line)) {
2964 const char *data(line.c_str());
2965 size_t size = line.size();
2966 lprintf("S:%s\n", data);
2968 if (conffile_r(data, size)) {
2969 [delegate_ setConfigurationData:conffile_r[1]];
2970 } else if (strncmp(data, "status: ", 8) == 0) {
2971 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2972 [delegate_ setProgressTitle:string];
2973 } else if (pmstatus_r(data, size)) {
2974 std::string type([pmstatus_r[1] UTF8String]);
2975 NSString *id = pmstatus_r[2];
2977 float percent([pmstatus_r[3] floatValue]);
2978 [delegate_ setProgressPercent:(percent / 100)];
2980 NSString *string = pmstatus_r[4];
2982 if (type == "pmerror")
2983 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2984 withObject:[NSArray arrayWithObjects:string, id, nil]
2987 else if (type == "pmstatus") {
2988 [delegate_ setProgressTitle:string];
2989 } else if (type == "pmconffile")
2990 [delegate_ setConfigurationData:string];
2991 else _assert(false);
2992 } else _assert(false);
2998 - (void) _readOutput:(NSNumber *)fd { _pooled
2999 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3000 std::istream is(&ib);
3003 while (std::getline(is, line)) {
3004 lprintf("O:%s\n", line.c_str());
3005 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3015 - (Package *) packageWithName:(NSString *)name {
3016 @synchronized ([Database class]) {
3017 if (static_cast<pkgDepCache *>(cache_) == NULL)
3019 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3020 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3023 - (Database *) init {
3024 if ((self = [super init]) != nil) {
3031 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3032 apr_pool_create(&pool_, NULL);
3034 packages_ = [[NSMutableArray alloc] init];
3038 _assert(pipe(fds) != -1);
3041 _config->Set("APT::Keep-Fds::", cydiafd_);
3042 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3045 detachNewThreadSelector:@selector(_readCydia:)
3047 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3050 _assert(pipe(fds) != -1);
3054 detachNewThreadSelector:@selector(_readStatus:)
3056 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3059 _assert(pipe(fds) != -1);
3060 _assert(dup2(fds[0], 0) != -1);
3061 _assert(close(fds[0]) != -1);
3063 input_ = fdopen(fds[1], "a");
3065 _assert(pipe(fds) != -1);
3066 _assert(dup2(fds[1], 1) != -1);
3067 _assert(close(fds[1]) != -1);
3070 detachNewThreadSelector:@selector(_readOutput:)
3072 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3077 - (pkgCacheFile &) cache {
3081 - (pkgDepCache::Policy *) policy {
3085 - (pkgRecords *) records {
3089 - (pkgProblemResolver *) resolver {
3093 - (pkgAcquire &) fetcher {
3097 - (pkgSourceList &) list {
3101 - (NSArray *) packages {
3105 - (NSArray *) sources {
3106 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3107 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3108 [sources addObject:i->second];
3112 - (NSArray *) issues {
3113 if (cache_->BrokenCount() == 0)
3116 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3118 for (Package *package in packages_) {
3119 if (![package broken])
3121 pkgCache::PkgIterator pkg([package iterator]);
3123 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3124 [entry addObject:[package name]];
3125 [issues addObject:entry];
3127 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3131 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3132 pkgCache::DepIterator start;
3133 pkgCache::DepIterator end;
3134 dep.GlobOr(start, end); // ++dep
3136 if (!cache_->IsImportantDep(end))
3138 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3141 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3142 [entry addObject:failure];
3143 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3145 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3146 if (Package *package = [self packageWithName:name])
3147 name = [package name];
3148 [failure addObject:name];
3150 pkgCache::PkgIterator target(start.TargetPkg());
3151 if (target->ProvidesList != 0)
3152 [failure addObject:@"?"];
3154 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3156 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3157 else if (!cache_[target].CandidateVerIter(cache_).end())
3158 [failure addObject:@"-"];
3159 else if (target->ProvidesList == 0)
3160 [failure addObject:@"!"];
3162 [failure addObject:@"%"];
3166 if (start.TargetVer() != 0)
3167 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3178 - (void) reloadData { _pooled
3179 @synchronized ([Database class]) {
3181 @synchronized (self) {
3185 [packages_ removeAllObjects];
3211 apr_pool_clear(pool_);
3212 NSRecycleZone(zone_);
3214 int chk(creat("/tmp/cydia.chk", 0644));
3219 if (!cache_.Open(progress_, true)) {
3221 if (!_error->PopMessage(error))
3224 lprintf("cache_.Open():[%s]\n", error.c_str());
3226 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3227 [delegate_ repairWithSelector:@selector(configure)];
3228 else if (error == "The package lists or status file could not be parsed or opened.")
3229 [delegate_ repairWithSelector:@selector(update)];
3230 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3231 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3232 // else if (error == "The list of sources could not be read.")
3233 else _assert(false);
3239 unlink("/tmp/cydia.chk");
3241 now_ = [[NSDate date] retain];
3243 policy_ = new pkgDepCache::Policy();
3244 records_ = new pkgRecords(cache_);
3245 resolver_ = new pkgProblemResolver(cache_);
3246 fetcher_ = new pkgAcquire(&status_);
3249 list_ = new pkgSourceList();
3250 _assert(list_->ReadMainList());
3252 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3253 _assert(pkgApplyStatus(cache_));
3255 if (cache_->BrokenCount() != 0) {
3256 _assert(pkgFixBroken(cache_));
3257 _assert(cache_->BrokenCount() == 0);
3258 _assert(pkgMinimizeUpgrade(cache_));
3263 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3264 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3265 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3266 // XXX: this could be more intelligent
3267 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3268 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3270 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3277 /*std::vector<Package *> packages;
3278 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3279 [packages_ release];
3284 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3285 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3286 //packages.push_back(package);
3287 [packages_ addObject:package];
3291 /*if (packages.empty())
3292 packages_ = [[NSArray alloc] init];
3294 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3297 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3298 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3299 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3307 /*if (!packages.empty())
3308 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3309 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3311 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3313 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3315 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3321 - (void) configure {
3322 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3323 system([dpkg UTF8String]);
3331 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3332 _assert(!_error->PendingError());
3335 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3338 public pkgArchiveCleaner
3341 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3346 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3348 while (_error->PopMessage(error))
3349 lprintf("ArchiveCleaner: %s\n", error.c_str());
3354 fetcher_->Shutdown();
3356 pkgRecords records(cache_);
3358 lock_ = new FileFd();
3359 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3360 _assert(!_error->PendingError());
3363 // XXX: explain this with an error message
3364 _assert(list.ReadMainList());
3366 manager_ = (_system->CreatePM(cache_));
3367 _assert(manager_->GetArchives(fetcher_, &list, &records));
3368 _assert(!_error->PendingError());
3372 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3374 _assert(list.ReadMainList());
3375 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3376 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3379 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3384 bool failed = false;
3385 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3386 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3388 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3391 std::string uri = (*item)->DescURI();
3392 std::string error = (*item)->ErrorText;
3394 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3397 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3398 withObject:[NSArray arrayWithObjects:
3399 [NSString stringWithUTF8String:error.c_str()],
3411 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3413 if (_error->PendingError()) {
3418 if (result == pkgPackageManager::Failed) {
3423 if (result != pkgPackageManager::Completed) {
3428 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3430 _assert(list.ReadMainList());
3431 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3432 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3435 if (![before isEqualToArray:after])
3440 _assert(pkgDistUpgrade(cache_));
3444 [self updateWithStatus:status_];
3447 - (void) setVisible {
3448 for (Package *package in packages_)
3449 [package setVisible];
3452 - (NSString *) updateWithStatus:(Status &)status {
3454 _assert(list.ReadMainList());
3457 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3459 if (_error->PendingError()) error: {
3461 if (!_error->PopMessage(error))
3464 return [NSString stringWithUTF8String:error.c_str()];
3467 if (!ListUpdate(status, list, PulseInterval_))
3470 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3476 - (void) setDelegate:(id)delegate {
3477 delegate_ = delegate;
3478 status_.setDelegate(delegate);
3479 progress_.setDelegate(delegate);
3482 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3483 SourceMap::const_iterator i(sources_.find(file->ID));
3484 return i == sources_.end() ? nil : i->second;
3490 /* PopUp Windows {{{ */
3491 @interface PopUpView : UIView {
3492 _transient id delegate_;
3493 UITransitionView *transition_;
3498 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3502 @implementation PopUpView
3505 [transition_ setDelegate:nil];
3506 [transition_ release];
3512 [transition_ transition:UITransitionPushFromTop toView:nil];
3515 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3516 if (from != nil && to == nil)
3517 [self removeFromSuperview];
3520 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3521 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3522 delegate_ = delegate;
3524 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3525 [self addSubview:transition_];
3527 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3529 [view addSubview:self];
3531 [transition_ setDelegate:self];
3533 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3534 [transition_ transition:UITransitionNone toView:blank];
3535 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3542 /* Confirmation View {{{ */
3543 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3544 if (!iterator.end())
3545 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3546 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3548 pkgCache::PkgIterator package(dep.TargetPkg());
3551 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3558 /* Web Scripting {{{ */
3559 @interface CydiaObject : NSObject {
3563 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3566 @implementation CydiaObject
3569 [indirect_ release];
3573 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3574 if ((self = [super init]) != nil) {
3575 indirect_ = [indirect retain];
3579 + (NSArray *) _attributeKeys {
3580 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3583 - (NSArray *) attributeKeys {
3584 return [[self class] _attributeKeys];
3587 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3588 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3591 - (NSString *) device {
3592 return [[UIDevice currentDevice] uniqueIdentifier];
3595 #if 0 // XXX: implement!
3596 - (NSString *) mac {
3597 if (![indirect_ promptForSensitive:@"Mac Address"])
3601 - (NSString *) serial {
3602 if (![indirect_ promptForSensitive:@"Serial #"])
3606 - (NSString *) firewire {
3607 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3611 - (NSString *) imei {
3612 if (![indirect_ promptForSensitive:@"IMEI"])
3617 + (NSString *) webScriptNameForSelector:(SEL)selector {
3618 if (selector == @selector(close))
3620 else if (selector == @selector(getPackageById:))
3621 return @"getPackageById";
3622 else if (selector == @selector(setAutoPopup:))
3623 return @"setAutoPopup";
3624 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3625 return @"setButtonImage";
3626 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3627 return @"setButtonTitle";
3628 else if (selector == @selector(setFinishHook:))
3629 return @"setFinishHook";
3630 else if (selector == @selector(setPopupHook:))
3631 return @"setPopupHook";
3632 else if (selector == @selector(setSpecial:))
3633 return @"setSpecial";
3634 else if (selector == @selector(setViewportWidth:))
3635 return @"setViewportWidth";
3636 else if (selector == @selector(supports:))
3638 else if (selector == @selector(stringWithFormat:arguments:))
3640 else if (selector == @selector(localizedStringForKey:value:table:))
3642 else if (selector == @selector(du:))
3644 else if (selector == @selector(statfs:))
3650 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3651 return [self webScriptNameForSelector:selector] == nil;
3654 - (BOOL) supports:(NSString *)feature {
3655 return [feature isEqualToString:@"window.open"];
3658 - (Package *) getPackageById:(NSString *)id {
3659 Package *package([[Database sharedInstance] packageWithName:id]);
3664 - (NSArray *) statfs:(NSString *)path {
3667 if (path == nil || statfs([path UTF8String], &stat) == -1)
3670 return [NSArray arrayWithObjects:
3671 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3672 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3673 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3677 - (NSNumber *) du:(NSString *)path {
3678 NSNumber *value(nil);
3681 _assert(pipe(fds) != -1);
3683 pid_t pid(ExecFork());
3685 _assert(dup2(fds[1], 1) != -1);
3686 _assert(close(fds[0]) != -1);
3687 _assert(close(fds[1]) != -1);
3688 /* XXX: this should probably not use du */
3689 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3694 _assert(close(fds[1]) != -1);
3696 if (FILE *du = fdopen(fds[0], "r")) {
3698 while (fgets(line, sizeof(line), du) != NULL) {
3699 size_t length(strlen(line));
3700 while (length != 0 && line[length - 1] == '\n')
3701 line[--length] = '\0';
3702 if (char *tab = strchr(line, '\t')) {
3704 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3709 } else _assert(close(fds[0]));
3713 if (waitpid(pid, &status, 0) == -1)
3716 else _assert(false);
3725 - (void) setAutoPopup:(BOOL)popup {
3726 [indirect_ setAutoPopup:popup];
3729 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3730 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3733 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3734 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3737 - (void) setSpecial:(id)function {
3738 [indirect_ setSpecial:function];
3741 - (void) setFinishHook:(id)function {
3742 [indirect_ setFinishHook:function];
3745 - (void) setPopupHook:(id)function {
3746 [indirect_ setPopupHook:function];
3749 - (void) setViewportWidth:(float)width {
3750 [indirect_ setViewportWidth:width];
3753 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3754 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3755 unsigned count([arguments count]);
3757 for (unsigned i(0); i != count; ++i)
3758 values[i] = [arguments objectAtIndex:i];
3759 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3762 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3763 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3765 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3767 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3773 @interface CydiaBrowserView : BrowserView {
3774 CydiaObject *cydia_;
3779 @implementation CydiaBrowserView
3786 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3787 [super webView:sender didClearWindowObject:window forFrame:frame];
3788 [window setValue:cydia_ forKey:@"cydia"];
3791 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3792 NSMutableURLRequest *copy = [request mutableCopy];
3794 if (Machine_ != NULL)
3795 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3796 if (UniqueID_ != nil)
3797 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
3800 [copy setValue:Role_ forHTTPHeaderField:@"X-Role"];
3805 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3806 if ((self = [super initWithBook:book forWidth:width ofClass:[CydiaBrowserView class]]) != nil) {
3807 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3809 WebView *webview([webview_ webView]);
3811 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3812 NSString *application = package == nil ? @"Cydia" : [NSString
3813 stringWithFormat:@"Cydia/%@",
3817 if (Product_ != nil)
3818 application = [NSString stringWithFormat:@"%@ Version/%@", application, Product_];
3820 application = [NSString stringWithFormat:@"%@ Mobile/%@", application, Build_];
3822 application = [NSString stringWithFormat:@"%@ Safari/%@", application, Safari_];
3824 [webview setApplicationNameForUserAgent:application];
3830 @protocol ConfirmationViewDelegate
3836 @interface ConfirmationView : CydiaBrowserView {
3837 _transient Database *database_;
3838 UIActionSheet *essential_;
3845 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3849 @implementation ConfirmationView
3856 if (essential_ != nil)
3857 [essential_ release];
3863 [book_ popFromSuperviewAnimated:YES];
3866 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3867 NSString *context([sheet context]);
3869 if ([context isEqualToString:@"remove"]) {
3877 [delegate_ confirm];
3884 } else if ([context isEqualToString:@"unable"]) {
3888 [super alertSheet:sheet buttonClicked:button];
3891 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3892 [super webView:sender didClearWindowObject:window forFrame:frame];
3893 [window setValue:changes_ forKey:@"changes"];
3894 [window setValue:issues_ forKey:@"issues"];
3895 [window setValue:sizes_ forKey:@"sizes"];
3898 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3899 if ((self = [super initWithBook:book]) != nil) {
3900 database_ = database;
3902 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3903 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3904 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3905 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3906 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3910 pkgDepCache::Policy *policy([database_ policy]);
3912 pkgCacheFile &cache([database_ cache]);
3913 NSArray *packages = [database_ packages];
3914 for (Package *package in packages) {
3915 pkgCache::PkgIterator iterator = [package iterator];
3916 pkgDepCache::StateCache &state(cache[iterator]);
3918 NSString *name([package name]);
3920 if (state.NewInstall())
3921 [installing addObject:name];
3922 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3923 [reinstalling addObject:name];
3924 else if (state.Upgrade())
3925 [upgrading addObject:name];
3926 else if (state.Downgrade())
3927 [downgrading addObject:name];
3928 else if (state.Delete()) {
3929 if ([package essential])
3931 [removing addObject:name];
3934 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3935 substrate_ |= DepSubstrate(iterator.CurrentVer());
3940 else if (Advanced_ || true) {
3941 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
3943 essential_ = [[UIActionSheet alloc]
3944 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
3945 buttons:[NSArray arrayWithObjects:
3946 [NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")],
3947 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
3949 defaultButtonIndex:0
3955 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3957 [essential_ setBodyText:UCLocalize("REMOVING_ESSENTIALS_EX")];
3959 essential_ = [[UIActionSheet alloc]
3960 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
3961 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
3962 defaultButtonIndex:0
3967 [essential_ setBodyText:UCLocalize("UNABLE_TO_COMPLY_EX")];
3970 changes_ = [[NSArray alloc] initWithObjects:
3978 issues_ = [database_ issues];
3980 issues_ = [issues_ retain];
3982 sizes_ = [[NSArray alloc] initWithObjects:
3983 SizeString([database_ fetcher].FetchNeeded()),
3984 SizeString([database_ fetcher].PartialPresent()),
3985 SizeString([database_ cache]->UsrSize()),
3988 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3992 - (NSString *) backButtonTitle {
3993 return UCLocalize("CONFIRM");
3996 - (NSString *) leftButtonTitle {
3997 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
4000 - (id) rightButtonTitle {
4001 return issues_ != nil ? nil : [super rightButtonTitle];
4004 - (id) _rightButtonTitle {
4005 #if AlwaysReload || IgnoreInstall
4006 return [super _rightButtonTitle];
4008 return UCLocalize("CONFIRM");
4012 - (void) _leftButtonClicked {
4017 - (void) _rightButtonClicked {
4019 return [super _rightButtonClicked];
4021 if (essential_ != nil)
4022 [essential_ popupAlertAnimated:YES];
4026 [delegate_ confirm];
4034 /* Progress Data {{{ */
4035 @interface ProgressData : NSObject {
4041 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4048 @implementation ProgressData
4050 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4051 if ((self = [super init]) != nil) {
4052 selector_ = selector;
4072 /* Progress View {{{ */
4073 @interface ProgressView : UIView <
4074 ConfigurationDelegate,
4077 _transient Database *database_;
4079 UIView *background_;
4080 UITransitionView *transition_;
4082 UINavigationBar *navbar_;
4083 UIProgressBar *progress_;
4084 UITextView *output_;
4085 UITextLabel *status_;
4086 UIPushButton *close_;
4089 SHA1SumValue springlist_;
4090 SHA1SumValue notifyconf_;
4091 SHA1SumValue sandplate_;
4094 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
4096 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4097 - (void) setContentView:(UIView *)view;
4100 - (void) _retachThread;
4101 - (void) _detachNewThreadData:(ProgressData *)data;
4102 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4108 @protocol ProgressViewDelegate
4109 - (void) progressViewIsComplete:(ProgressView *)sender;
4112 @implementation ProgressView
4115 [transition_ setDelegate:nil];
4116 [navbar_ setDelegate:nil];
4119 if (background_ != nil)
4120 [background_ release];
4121 [transition_ release];
4124 [progress_ release];
4131 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
4132 if (bootstrap_ && from == overlay_ && to == view_)
4136 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4137 if ((self = [super initWithFrame:frame]) != nil) {
4138 database_ = database;
4139 delegate_ = delegate;
4141 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4142 [transition_ setDelegate:self];
4144 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4147 [overlay_ setBackgroundColor:[UIColor blackColor]];
4149 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4150 [background_ setBackgroundColor:[UIColor blackColor]];
4151 [self addSubview:background_];
4154 [self addSubview:transition_];
4156 CGSize navsize = [UINavigationBar defaultSize];
4157 CGRect navrect = {{0, 0}, navsize};
4159 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4160 [overlay_ addSubview:navbar_];
4162 [navbar_ setBarStyle:1];
4163 [navbar_ setDelegate:self];
4165 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4166 [navbar_ pushNavigationItem:navitem];
4168 CGRect bounds = [overlay_ bounds];
4169 CGSize prgsize = [UIProgressBar defaultSize];
4172 (bounds.size.width - prgsize.width) / 2,
4173 bounds.size.height - prgsize.height - 20
4176 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4177 [progress_ setStyle:0];
4179 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4181 bounds.size.height - prgsize.height - 50,
4182 bounds.size.width - 20,
4186 [status_ setColor:[UIColor whiteColor]];
4187 [status_ setBackgroundColor:[UIColor clearColor]];
4189 [status_ setCentersHorizontally:YES];
4190 //[status_ setFont:font];
4193 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4195 navrect.size.height + 20,
4196 bounds.size.width - 20,
4197 bounds.size.height - navsize.height - 62 - navrect.size.height
4201 //[output_ setTextFont:@"Courier New"];
4202 [output_ setTextSize:12];
4204 [output_ setTextColor:[UIColor whiteColor]];
4205 [output_ setBackgroundColor:[UIColor clearColor]];
4207 [output_ setMarginTop:0];
4208 [output_ setAllowsRubberBanding:YES];
4209 [output_ setEditable:NO];
4211 [overlay_ addSubview:output_];
4213 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4215 bounds.size.height - prgsize.height - 50,
4216 bounds.size.width - 20,
4220 [close_ setAutosizesToFit:NO];
4221 [close_ setDrawsShadow:YES];
4222 [close_ setStretchBackground:YES];
4223 [close_ setEnabled:YES];
4225 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4226 [close_ setTitleFont:bold];
4228 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
4229 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4230 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4234 - (void) setContentView:(UIView *)view {
4235 view_ = [view retain];
4238 - (void) resetView {
4239 [transition_ transition:6 toView:view_];
4242 - (void) _checkError {
4243 if (_error->PendingError()) {
4245 if (!_error->PopMessage(error))
4248 UIActionSheet *sheet = [[[UIActionSheet alloc]
4249 initWithTitle:UCLocalize("ERROR")
4250 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4251 defaultButtonIndex:0
4256 [sheet setBodyText:[NSString stringWithUTF8String:error.c_str()]];
4257 [sheet popupAlertAnimated:YES];
4262 [delegate_ progressViewIsComplete:self];
4266 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4269 MMap mmap(file, MMap::ReadOnly);
4271 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4272 if (!(notifyconf_ == sha1.Result()))
4279 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4282 MMap mmap(file, MMap::ReadOnly);
4284 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4285 if (!(springlist_ == sha1.Result()))
4291 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4292 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4293 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4294 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4295 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4298 #define ListCache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4299 #define IconCache_ "/User/Library/Caches/com.apple.springboard-imagecache-icons.plist"
4303 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ListCache_]) {
4304 [cache autorelease];
4306 NSFileManager *manager = [NSFileManager defaultManager];
4307 NSError *error = nil;
4309 id system = [cache objectForKey:@"System"];
4314 if (stat(ListCache_, &info) == -1)
4317 [system removeAllObjects];
4319 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4320 for (NSString *app in apps)
4321 if ([app hasSuffix:@".app"]) {
4322 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4323 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4324 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4326 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4327 [info setObject:path forKey:@"Path"];
4328 [info setObject:@"System" forKey:@"ApplicationType"];
4329 [system addInfoDictionary:info];
4335 [cache writeToFile:@ListCache_ atomically:YES];
4337 if (chown(ListCache_, info.st_uid, info.st_gid) == -1)
4339 if (chmod(ListCache_, info.st_mode) == -1)
4343 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4346 notify_post("com.apple.mobile.application_installed");
4348 [delegate_ setStatusBarShowsProgress:NO];
4351 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4352 NSString *context([sheet context]);
4354 if ([context isEqualToString:@"error"])
4356 else if ([context isEqualToString:@"_error"]) {
4359 } else if ([context isEqualToString:@"conffile"]) {
4360 FILE *input = [database_ input];
4364 fprintf(input, "N\n");
4368 fprintf(input, "Y\n");
4379 - (void) closeButtonPushed {
4388 [delegate_ suspendWithAnimation:YES];
4392 system("launchctl stop com.apple.SpringBoard");
4396 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4405 - (void) _retachThread {
4406 UINavigationItem *item = [navbar_ topItem];
4407 [item setTitle:UCLocalize("COMPLETE")];
4409 [overlay_ addSubview:close_];
4410 [progress_ removeFromSuperview];
4411 [status_ removeFromSuperview];
4416 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4417 [[data target] performSelector:[data selector] withObject:[data object]];
4420 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4423 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4424 UINavigationItem *item = [navbar_ topItem];
4425 [item setTitle:title];
4427 [status_ setText:nil];
4428 [output_ setText:@""];
4429 [progress_ setProgress:0];
4431 [close_ removeFromSuperview];
4432 [overlay_ addSubview:progress_];
4433 [overlay_ addSubview:status_];
4435 [delegate_ setStatusBarShowsProgress:YES];
4440 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4443 MMap mmap(file, MMap::ReadOnly);
4445 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4446 notifyconf_ = sha1.Result();
4452 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4455 MMap mmap(file, MMap::ReadOnly);
4457 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4458 springlist_ = sha1.Result();
4462 [transition_ transition:6 toView:overlay_];
4465 detachNewThreadSelector:@selector(_detachNewThreadData:)
4467 withObject:[[ProgressData alloc]
4468 initWithSelector:selector
4475 - (void) repairWithSelector:(SEL)selector {
4477 detachNewThreadSelector:selector
4480 title:UCLocalize("REPAIRING")
4484 - (void) setConfigurationData:(NSString *)data {
4486 performSelectorOnMainThread:@selector(_setConfigurationData:)
4492 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4493 Package *package = id == nil ? nil : [database_ packageWithName:id];
4495 UIActionSheet *sheet = [[[UIActionSheet alloc]
4496 initWithTitle:(package == nil ? id : [package name])
4497 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4498 defaultButtonIndex:0
4503 [sheet setBodyText:error];
4504 [sheet popupAlertAnimated:YES];
4507 - (void) setProgressTitle:(NSString *)title {
4509 performSelectorOnMainThread:@selector(_setProgressTitle:)
4515 - (void) setProgressPercent:(float)percent {
4517 performSelectorOnMainThread:@selector(_setProgressPercent:)
4518 withObject:[NSNumber numberWithFloat:percent]
4523 - (void) startProgress {
4526 - (void) addProgressOutput:(NSString *)output {
4528 performSelectorOnMainThread:@selector(_addProgressOutput:)
4534 - (bool) isCancelling:(size_t)received {
4538 - (void) _setConfigurationData:(NSString *)data {
4539 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4541 _assert(conffile_r(data));
4543 NSString *ofile = conffile_r[1];
4544 //NSString *nfile = conffile_r[2];
4546 UIActionSheet *sheet = [[[UIActionSheet alloc]
4547 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4548 buttons:[NSArray arrayWithObjects:
4549 UCLocalize("KEEP_OLD_COPY"),
4550 UCLocalize("ACCEPT_NEW_COPY"),
4551 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4553 defaultButtonIndex:0
4558 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4559 [sheet popupAlertAnimated:YES];
4562 - (void) _setProgressTitle:(NSString *)title {
4563 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4564 for (size_t i(0), e([words count]); i != e; ++i) {
4565 NSString *word([words objectAtIndex:i]);
4566 if (Package *package = [database_ packageWithName:word])
4567 [words replaceObjectAtIndex:i withObject:[package name]];
4570 [status_ setText:[words componentsJoinedByString:@" "]];
4573 - (void) _setProgressPercent:(NSNumber *)percent {
4574 [progress_ setProgress:[percent floatValue]];
4577 - (void) _addProgressOutput:(NSString *)output {
4578 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4579 CGSize size = [output_ contentSize];
4580 CGRect rect = {{0, size.height}, {size.width, 0}};
4581 [output_ scrollRectToVisible:rect animated:YES];
4584 - (BOOL) isRunning {
4591 /* Package Cell {{{ */
4592 @interface ContentView : UIView {
4593 _transient id delegate_;
4598 @interface PackageCell : UITableViewCell {
4601 NSString *description_;
4607 ContentView *content_;
4612 - (PackageCell *) init;
4613 - (void) setPackage:(Package *)package;
4615 + (int) heightForPackage:(Package *)package;
4616 - (void) drawContentRect:(CGRect)rect;
4620 @implementation ContentView
4622 - (id) initWithFrame:(CGRect)frame {
4623 if ((self = [super initWithFrame:frame]) != nil) {
4627 - (void) setDelegate:(id)delegate {
4628 delegate_ = delegate;
4631 - (void) drawRect:(CGRect)rect {
4632 [super drawRect:rect];
4633 [delegate_ drawContentRect:rect];
4638 @implementation PackageCell
4640 - (void) clearPackage {
4651 if (description_ != nil) {
4652 [description_ release];
4656 if (source_ != nil) {
4661 if (badge_ != nil) {
4671 [self clearPackage];
4678 return faded_ ? [self selectionPercent] : fade_;
4681 - (PackageCell *) init {
4682 CGRect frame(CGRectMake(0, 0, 320, 74));
4683 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4684 UIView *content([self contentView]);
4685 CGRect bounds([content bounds]);
4686 content_ = [[ContentView alloc] initWithFrame:bounds];
4687 [content_ setDelegate:self];
4688 [content_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
4689 [content_ setOpaque:YES];
4690 [content addSubview:content_];
4691 if ([self respondsToSelector:@selector(selectionPercent)])
4696 - (void) _setBackgroundColor {
4698 if (NSString *mode = [package_ mode]) {
4699 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4700 color = remove ? RemovingColor_ : InstallingColor_;
4702 color = [UIColor whiteColor];
4704 [content_ setBackgroundColor:color];
4705 [self setNeedsDisplay];
4708 - (void) setPackage:(Package *)package {
4709 [self clearPackage];
4712 Source *source = [package source];
4714 icon_ = [[package icon] retain];
4715 name_ = [[package name] retain];
4716 description_ = [[package shortDescription] retain];
4717 commercial_ = [package isCommercial];
4719 package_ = [package retain];
4721 NSString *label = nil;
4722 bool trusted = false;
4724 if (source != nil) {
4725 label = [source label];
4726 trusted = [source trusted];
4727 } else if ([[package id] isEqualToString:@"firmware"])
4728 label = UCLocalize("APPLE");
4730 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4732 NSString *from(label);
4734 NSString *section = [package simpleSection];
4735 if (section != nil && ![section isEqualToString:label]) {
4736 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4737 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4740 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4741 source_ = [from retain];
4743 if (NSString *purpose = [package primaryPurpose])
4744 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4745 badge_ = [badge_ retain];
4747 [self _setBackgroundColor];
4748 [content_ setNeedsDisplay];
4751 - (void) drawContentRect:(CGRect)rect {
4752 bool selected([self isSelected]);
4755 CGContextRef context(UIGraphicsGetCurrentContext());
4756 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4757 CGContextFillRect(context, rect);
4762 rect.size = [icon_ size];
4764 rect.size.width /= 2;
4765 rect.size.height /= 2;
4767 rect.origin.x = 25 - rect.size.width / 2;
4768 rect.origin.y = 25 - rect.size.height / 2;
4770 [icon_ drawInRect:rect];
4773 if (badge_ != nil) {
4774 CGSize size = [badge_ size];
4776 [badge_ drawAtPoint:CGPointMake(
4777 36 - size.width / 2,
4778 36 - size.height / 2
4786 UISetColor(commercial_ ? Purple_ : Black_);
4787 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4788 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4791 UISetColor(commercial_ ? Purplish_ : Gray_);
4792 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4795 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4796 //[self _setBackgroundColor];
4797 [super setSelected:selected animated:fade];
4798 [content_ setNeedsDisplay];
4801 + (int) heightForPackage:(Package *)package {
4807 /* Section Cell {{{ */
4808 @interface SectionCell : UISimpleTableCell {
4813 _UISwitchSlider *switch_;
4818 - (void) setSection:(Section *)section editing:(BOOL)editing;
4822 @implementation SectionCell
4824 - (void) clearSection {
4825 if (section_ != nil) {
4835 if (count_ != nil) {
4842 [self clearSection];
4849 if ((self = [super init]) != nil) {
4850 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4852 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4853 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4857 - (void) onSwitch:(id)sender {
4858 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4859 if (metadata == nil) {
4860 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4861 [Sections_ setObject:metadata forKey:section_];
4865 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4868 - (void) setSection:(Section *)section editing:(BOOL)editing {
4869 if (editing != editing_) {
4871 [switch_ removeFromSuperview];
4873 [self addSubview:switch_];
4877 [self clearSection];
4879 if (section == nil) {
4880 name_ = [UCLocalize("ALL_PACKAGES") retain];
4883 section_ = [section localized];
4884 if (section_ != nil)
4885 section_ = [section_ retain];
4886 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4887 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4890 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4894 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4895 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4902 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4904 CGSize size = [count_ sizeWithFont:Font14_];
4908 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4910 [super drawContentInRect:rect selected:selected];
4916 /* File Table {{{ */
4917 @interface FileTable : RVPage {
4918 _transient Database *database_;
4921 NSMutableArray *files_;
4925 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4926 - (void) setPackage:(Package *)package;
4930 @implementation FileTable
4933 if (package_ != nil)
4942 - (int) numberOfRowsInTable:(UITable *)table {
4943 return files_ == nil ? 0 : [files_ count];
4946 - (float) table:(UITable *)table heightForRow:(int)row {
4950 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4951 if (reusing == nil) {
4952 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4953 UIFont *font = [UIFont systemFontOfSize:16];
4954 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4956 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4960 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4964 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4965 if ((self = [super initWithBook:book]) != nil) {
4966 database_ = database;
4968 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4970 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4971 [self addSubview:list_];
4973 UITableColumn *column = [[[UITableColumn alloc]
4974 initWithTitle:UCLocalize("NAME")
4976 width:[self frame].size.width
4979 [list_ setDataSource:self];
4980 [list_ setSeparatorStyle:1];
4981 [list_ addTableColumn:column];
4982 [list_ setDelegate:self];
4983 [list_ setReusesTableCells:YES];
4987 - (void) setPackage:(Package *)package {
4988 if (package_ != nil) {
4989 [package_ autorelease];
4998 [files_ removeAllObjects];
5000 if (package != nil) {
5001 package_ = [package retain];
5002 name_ = [[package id] retain];
5004 if (NSArray *files = [package files])
5005 [files_ addObjectsFromArray:files];
5007 if ([files_ count] != 0) {
5008 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5009 [files_ removeObjectAtIndex:0];
5010 [files_ sortUsingSelector:@selector(compareByPath:)];
5012 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5013 [stack addObject:@"/"];
5015 for (int i(0), e([files_ count]); i != e; ++i) {
5016 NSString *file = [files_ objectAtIndex:i];
5017 while (![file hasPrefix:[stack lastObject]])
5018 [stack removeLastObject];
5019 NSString *directory = [stack lastObject];
5020 [stack addObject:[file stringByAppendingString:@"/"]];
5021 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5022 ([stack count] - 2) * 3, "",
5023 [file substringFromIndex:[directory length]]
5032 - (void) resetViewAnimated:(BOOL)animated {
5033 [list_ resetViewAnimated:animated];
5036 - (void) reloadData {
5037 [self setPackage:[database_ packageWithName:name_]];
5038 [self reloadButtons];
5041 - (NSString *) title {
5042 return UCLocalize("INSTALLED_FILES");
5045 - (NSString *) backButtonTitle {
5046 return UCLocalize("FILES");
5051 /* Package View {{{ */
5052 @interface PackageView : CydiaBrowserView {
5053 _transient Database *database_;
5057 NSMutableArray *buttons_;
5060 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5061 - (void) setPackage:(Package *)package;
5065 @implementation PackageView
5068 if (package_ != nil)
5077 if ([self retainCount] == 1)
5078 [delegate_ setPackageView:self];
5082 /* XXX: this is not safe at all... localization of /fail/ */
5083 - (void) _clickButtonWithName:(NSString *)name {
5084 if ([name isEqualToString:UCLocalize("CLEAR")])
5085 [delegate_ clearPackage:package_];
5086 else if ([name isEqualToString:UCLocalize("INSTALL")])
5087 [delegate_ installPackage:package_];
5088 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5089 [delegate_ installPackage:package_];
5090 else if ([name isEqualToString:UCLocalize("REMOVE")])
5091 [delegate_ removePackage:package_];
5092 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5093 [delegate_ installPackage:package_];
5094 else _assert(false);
5097 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5098 NSString *context([sheet context]);
5100 if ([context isEqualToString:@"modify"]) {
5101 int count = [buttons_ count];
5102 _assert(count != 0);
5103 _assert(button <= count + 1);
5105 if (count != button - 1)
5106 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
5110 [super alertSheet:sheet buttonClicked:button];
5113 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5114 return [super webView:sender didFinishLoadForFrame:frame];
5117 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5118 [super webView:sender didClearWindowObject:window forFrame:frame];
5119 [window setValue:package_ forKey:@"package"];
5122 - (bool) _allowJavaScriptPanel {
5127 - (void) __rightButtonClicked {
5128 int count = [buttons_ count];
5129 _assert(count != 0);
5132 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5134 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
5135 [buttons addObjectsFromArray:buttons_];
5136 [buttons addObject:UCLocalize("CANCEL")];
5138 [delegate_ slideUp:[[[UIActionSheet alloc]
5141 defaultButtonIndex:([buttons count] - 1)
5148 - (void) _rightButtonClicked {
5150 [super _rightButtonClicked];
5152 [self __rightButtonClicked];
5156 - (id) _rightButtonTitle {
5157 int count = [buttons_ count];
5158 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5161 - (NSString *) backButtonTitle {
5165 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5166 if ((self = [super initWithBook:book]) != nil) {
5167 database_ = database;
5168 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5169 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5173 - (void) setPackage:(Package *)package {
5174 if (package_ != nil) {
5175 [package_ autorelease];
5184 [buttons_ removeAllObjects];
5186 if (package != nil) {
5189 package_ = [package retain];
5190 name_ = [[package id] retain];
5191 commercial_ = [package isCommercial];
5193 if ([package_ mode] != nil)
5194 [buttons_ addObject:UCLocalize("CLEAR")];
5195 if ([package_ source] == nil);
5196 else if ([package_ upgradableAndEssential:NO])
5197 [buttons_ addObject:UCLocalize("UPGRADE")];
5198 else if ([package_ uninstalled])
5199 [buttons_ addObject:UCLocalize("INSTALL")];
5201 [buttons_ addObject:UCLocalize("REINSTALL")];
5202 if (![package_ uninstalled])
5203 [buttons_ addObject:UCLocalize("REMOVE")];
5205 if (special_ != NULL) {
5206 CGRect frame([webview_ frame]);
5207 frame.size.width = 320;
5208 frame.size.height = 0;
5209 [webview_ setFrame:frame];
5211 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5214 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5216 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5218 [self setFinishHook:nil];
5219 [self setPopupHook:nil];
5222 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5223 [super callFunction:special_];
5227 [self reloadButtons];
5230 - (bool) isLoading {
5231 return commercial_ ? [super isLoading] : false;
5234 - (void) reloadData {
5235 [self setPackage:[database_ packageWithName:name_]];
5240 /* Package Table {{{ */
5241 @interface PackageTable : RVPage {
5242 _transient Database *database_;
5244 NSMutableArray *packages_;
5245 NSMutableArray *sections_;
5247 NSMutableArray *index_;
5248 NSMutableDictionary *indices_;
5251 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5253 - (void) setDelegate:(id)delegate;
5255 - (void) reloadData;
5256 - (void) resetCursor;
5258 - (UITableView *) list;
5260 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5264 @implementation PackageTable
5267 [list_ setDataSource:nil];
5270 [packages_ release];
5271 [sections_ release];
5278 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5279 NSInteger count([sections_ count]);
5280 return count == 0 ? 1 : count;
5283 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5284 if ([sections_ count] == 0)
5286 return [[sections_ objectAtIndex:section] name];
5289 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5290 if ([sections_ count] == 0)
5292 return [[sections_ objectAtIndex:section] count];
5295 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5296 Section *section([sections_ objectAtIndex:[path section]]);
5297 NSInteger row([path row]);
5298 Package *package([packages_ objectAtIndex:([section row] + row)]);
5302 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5303 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5305 cell = [[[PackageCell alloc] init] autorelease];
5306 [cell setPackage:[self packageAtIndexPath:path]];
5310 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5312 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5315 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5316 Package *package([self packageAtIndexPath:path]);
5317 package = [database_ packageWithName:[package id]];
5318 PackageView *view([delegate_ packageView]);
5319 [view setPackage:package];
5320 [view setDelegate:delegate_];
5321 [book_ pushPage:view];
5325 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5326 return [packages_ count] > 20 ? index_ : nil;
5329 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5333 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5334 if ((self = [super initWithBook:book]) != nil) {
5335 database_ = database;
5336 title_ = [title retain];
5338 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5339 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5341 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5342 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5344 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5345 [list_ setDataSource:self];
5346 [list_ setDelegate:self];
5348 [self addSubview:list_];
5350 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5351 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5355 - (void) setDelegate:(id)delegate {
5356 delegate_ = delegate;
5359 - (bool) hasPackage:(Package *)package {
5363 - (void) reloadData {
5364 NSArray *packages = [database_ packages];
5366 [packages_ removeAllObjects];
5367 [sections_ removeAllObjects];
5369 _profile(PackageTable$reloadData$Filter)
5370 for (Package *package in packages)
5371 if ([self hasPackage:package])
5372 [packages_ addObject:package];
5375 [index_ removeAllObjects];
5376 [indices_ removeAllObjects];
5378 Section *section = nil;
5380 _profile(PackageTable$reloadData$Section)
5381 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5385 _profile(PackageTable$reloadData$Section$Package)
5386 package = [packages_ objectAtIndex:offset];
5387 index = [package index];
5390 if (section == nil || [section index] != index) {
5391 _profile(PackageTable$reloadData$Section$Allocate)
5392 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5395 [index_ addObject:[section name]];
5396 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5398 _profile(PackageTable$reloadData$Section$Add)
5399 [sections_ addObject:section];
5403 [section addToCount];
5407 _profile(PackageTable$reloadData$List)
5412 - (NSString *) title {
5416 - (void) resetViewAnimated:(BOOL)animated {
5417 [list_ resetViewAnimated:animated];
5420 - (void) resetCursor {
5421 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5424 - (UITableView *) list {
5428 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5429 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5434 /* Filtered Package Table {{{ */
5435 @interface FilteredPackageTable : PackageTable {
5441 - (void) setObject:(id)object;
5443 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5447 @implementation FilteredPackageTable
5455 - (void) setObject:(id)object {
5461 object_ = [object retain];
5464 - (bool) hasPackage:(Package *)package {
5465 _profile(FilteredPackageTable$hasPackage)
5466 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5470 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5471 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5473 object_ = object == nil ? nil : [object retain];
5475 /* XXX: this is an unsafe optimization of doomy hell */
5476 Method method = class_getInstanceMethod([Package class], filter);
5477 _assert(method != NULL);
5478 imp_ = method_getImplementation(method);
5479 _assert(imp_ != NULL);
5488 /* Add Source View {{{ */
5489 @interface AddSourceView : RVPage {
5490 _transient Database *database_;
5493 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5497 @implementation AddSourceView
5499 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5500 if ((self = [super initWithBook:book]) != nil) {
5501 database_ = database;
5507 /* Source Cell {{{ */
5508 @interface SourceCell : UITableCell {
5511 NSString *description_;
5517 - (SourceCell *) initWithSource:(Source *)source;
5521 @implementation SourceCell
5526 [description_ release];
5531 - (SourceCell *) initWithSource:(Source *)source {
5532 if ((self = [super init]) != nil) {
5534 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5536 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5537 icon_ = [icon_ retain];
5539 origin_ = [[source name] retain];
5540 label_ = [[source uri] retain];
5541 description_ = [[source description] retain];
5545 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5547 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5554 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5558 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5562 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5564 [super drawContentInRect:rect selected:selected];
5569 /* Source Table {{{ */
5570 @interface SourceTable : RVPage {
5571 _transient Database *database_;
5572 UISectionList *list_;
5573 NSMutableArray *sources_;
5574 UIActionSheet *alert_;
5578 UIProgressHUD *hud_;
5581 //NSURLConnection *installer_;
5582 NSURLConnection *trivial_bz2_;
5583 NSURLConnection *trivial_gz_;
5584 //NSURLConnection *automatic_;
5589 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5593 @implementation SourceTable
5595 - (void) _deallocConnection:(NSURLConnection *)connection {
5596 if (connection != nil) {
5597 [connection cancel];
5598 //[connection setDelegate:nil];
5599 [connection release];
5604 [[list_ table] setDelegate:nil];
5605 [list_ setDataSource:nil];
5614 //[self _deallocConnection:installer_];
5615 [self _deallocConnection:trivial_gz_];
5616 [self _deallocConnection:trivial_bz2_];
5617 //[self _deallocConnection:automatic_];
5624 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5625 return offset_ == 0 ? 1 : 2;
5628 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5629 switch (section + (offset_ == 0 ? 1 : 0)) {
5630 case 0: return UCLocalize("ENTERED_BY_USER");
5631 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5639 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5640 switch (section + (offset_ == 0 ? 1 : 0)) {
5642 case 1: return offset_;
5650 - (int) numberOfRowsInTable:(UITable *)table {
5651 return [sources_ count];
5654 - (float) table:(UITable *)table heightForRow:(int)row {
5655 Source *source = [sources_ objectAtIndex:row];
5656 return [source description] == nil ? 56 : 73;
5659 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5660 Source *source = [sources_ objectAtIndex:row];
5661 // XXX: weird warning, stupid selectors ;P
5662 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5665 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5669 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5673 - (void) tableRowSelected:(NSNotification*)notification {
5674 UITable *table([list_ table]);
5675 int row([table selectedRow]);
5679 Source *source = [sources_ objectAtIndex:row];
5681 PackageTable *packages = [[[FilteredPackageTable alloc]
5684 title:[source label]
5685 filter:@selector(isVisibleInSource:)
5689 [packages setDelegate:delegate_];
5691 [book_ pushPage:packages];
5694 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5695 Source *source = [sources_ objectAtIndex:row];
5696 return [source record] != nil;
5699 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5700 [[list_ table] setDeleteConfirmationRow:row];
5703 - (void) table:(UITable *)table deleteRow:(int)row {
5704 Source *source = [sources_ objectAtIndex:row];
5705 [Sources_ removeObjectForKey:[source key]];
5706 [delegate_ syncData];
5710 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5713 @"./", @"Distribution",
5714 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5716 [delegate_ syncData];
5719 - (NSString *) getWarning {
5720 NSString *href(href_);
5721 NSRange colon([href rangeOfString:@"://"]);
5722 if (colon.location != NSNotFound)
5723 href = [href substringFromIndex:(colon.location + 3)];
5724 href = [href stringByAddingPercentEscapes];
5725 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5726 href = [href stringByCachingURLWithCurrentCDN];
5728 NSURL *url([NSURL URLWithString:href]);
5730 NSStringEncoding encoding;
5731 NSError *error(nil);
5733 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5734 return [warning length] == 0 ? nil : warning;
5738 - (void) _endConnection:(NSURLConnection *)connection {
5739 NSURLConnection **field = NULL;
5740 if (connection == trivial_bz2_)
5741 field = &trivial_bz2_;
5742 else if (connection == trivial_gz_)
5743 field = &trivial_gz_;
5744 _assert(field != NULL);
5745 [connection release];
5749 trivial_bz2_ == nil &&
5755 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5758 UIActionSheet *sheet = [[[UIActionSheet alloc]
5759 initWithTitle:UCLocalize("SOURCE_WARNING")
5760 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5761 defaultButtonIndex:0
5766 [sheet setNumberOfRows:1];
5768 [sheet setBodyText:warning];
5769 [sheet popupAlertAnimated:YES];
5772 } else if (error_ != nil) {
5773 UIActionSheet *sheet = [[[UIActionSheet alloc]
5774 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5775 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5776 defaultButtonIndex:0
5781 [sheet setBodyText:[error_ localizedDescription]];
5782 [sheet popupAlertAnimated:YES];
5784 UIActionSheet *sheet = [[[UIActionSheet alloc]
5785 initWithTitle:UCLocalize("NOT_REPOSITORY")
5786 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5787 defaultButtonIndex:0
5792 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5793 [sheet popupAlertAnimated:YES];
5796 [delegate_ setStatusBarShowsProgress:NO];
5797 [delegate_ removeProgressHUD:hud_];
5807 if (error_ != nil) {
5814 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5815 switch ([response statusCode]) {
5821 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5822 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5824 error_ = [error retain];
5825 [self _endConnection:connection];
5828 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5829 [self _endConnection:connection];
5832 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5833 NSMutableURLRequest *request = [NSMutableURLRequest
5834 requestWithURL:[NSURL URLWithString:href]
5835 cachePolicy:NSURLRequestUseProtocolCachePolicy
5836 timeoutInterval:20.0
5839 [request setHTTPMethod:method];
5841 if (Machine_ != NULL)
5842 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5843 if (UniqueID_ != nil)
5844 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5847 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5849 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5852 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5853 NSString *context([sheet context]);
5855 if ([context isEqualToString:@"source"]) {
5858 NSString *href = [[sheet textField] text];
5860 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5862 if (![href hasSuffix:@"/"])
5863 href_ = [href stringByAppendingString:@"/"];
5866 href_ = [href_ retain];
5868 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
5869 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5870 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5871 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5875 hud_ = [[delegate_ addProgressHUD] retain];
5876 [hud_ setText:UCLocalize("VERIFYING_URL")];
5887 } else if ([context isEqualToString:@"trivial"])
5889 else if ([context isEqualToString:@"urlerror"])
5891 else if ([context isEqualToString:@"warning"]) {
5911 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5912 if ((self = [super initWithBook:book]) != nil) {
5913 database_ = database;
5914 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5916 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5917 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5918 [list_ setShouldHideHeaderInShortLists:NO];
5920 [self addSubview:list_];
5921 [list_ setDataSource:self];
5923 UITableColumn *column = [[UITableColumn alloc]
5924 initWithTitle:UCLocalize("NAME")
5926 width:[self frame].size.width
5929 UITable *table = [list_ table];
5930 [table setSeparatorStyle:1];
5931 [table addTableColumn:column];
5932 [table setDelegate:self];
5936 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5937 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5941 - (void) reloadData {
5943 _assert(list.ReadMainList());
5945 [sources_ removeAllObjects];
5946 [sources_ addObjectsFromArray:[database_ sources]];
5948 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5951 int count = [sources_ count];
5952 for (offset_ = 0; offset_ != count; ++offset_) {
5953 Source *source = [sources_ objectAtIndex:offset_];
5954 if ([source record] == nil)
5961 - (void) resetViewAnimated:(BOOL)animated {
5962 [list_ resetViewAnimated:animated];
5965 - (void) _leftButtonClicked {
5966 /*[book_ pushPage:[[[AddSourceView alloc]
5971 UIActionSheet *sheet = [[[UIActionSheet alloc]
5972 initWithTitle:UCLocalize("ENTER_APT_URL")
5973 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
5974 defaultButtonIndex:0
5979 [sheet setNumberOfRows:1];
5981 [sheet addTextFieldWithValue:@"http://" label:@""];
5983 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5984 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5985 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5986 [traits setKeyboardType:UIKeyboardTypeURL];
5987 // XXX: UIReturnKeyDone
5988 [traits setReturnKeyType:UIReturnKeyNext];
5990 [sheet popupAlertAnimated:YES];
5993 - (void) _rightButtonClicked {
5994 UITable *table = [list_ table];
5995 BOOL editing = [table isRowDeletionEnabled];
5996 [table enableRowDeletion:!editing animated:YES];
5997 [book_ reloadButtonsForPage:self];
6000 - (NSString *) title {
6001 return UCLocalize("SOURCES");
6004 - (NSString *) leftButtonTitle {
6005 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
6008 - (id) rightButtonTitle {
6009 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
6012 - (UINavigationButtonStyle) rightButtonStyle {
6013 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6019 /* Installed View {{{ */
6020 @interface InstalledView : RVPage {
6021 _transient Database *database_;
6022 FilteredPackageTable *packages_;
6026 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6030 @implementation InstalledView
6033 [packages_ release];
6037 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6038 if ((self = [super initWithBook:book]) != nil) {
6039 database_ = database;
6041 packages_ = [[FilteredPackageTable alloc]
6045 filter:@selector(isInstalledAndVisible:)
6046 with:[NSNumber numberWithBool:YES]
6049 [self addSubview:packages_];
6051 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6052 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6056 - (void) resetViewAnimated:(BOOL)animated {
6057 [packages_ resetViewAnimated:animated];
6060 - (void) reloadData {
6061 [packages_ reloadData];
6064 - (void) _rightButtonClicked {
6065 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6066 [packages_ reloadData];
6068 [book_ reloadButtonsForPage:self];
6071 - (NSString *) title {
6072 return UCLocalize("INSTALLED");
6075 - (NSString *) backButtonTitle {
6076 return UCLocalize("PACKAGES");
6079 - (id) rightButtonTitle {
6080 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6083 - (UINavigationButtonStyle) rightButtonStyle {
6084 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6087 - (void) setDelegate:(id)delegate {
6088 [super setDelegate:delegate];
6089 [packages_ setDelegate:delegate];
6096 @interface HomeView : CydiaBrowserView {
6101 @implementation HomeView
6103 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6104 NSString *context([sheet context]);
6106 if ([context isEqualToString:@"about"])
6109 [super alertSheet:sheet buttonClicked:button];
6112 - (void) _leftButtonClicked {
6113 UIActionSheet *sheet = [[[UIActionSheet alloc]
6114 initWithTitle:UCLocalize("ABOUT_CYDIA")
6115 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6116 defaultButtonIndex:0
6122 @"Copyright (C) 2008-2009\n"
6123 "Jay Freeman (saurik)\n"
6124 "saurik@saurik.com\n"
6125 "http://www.saurik.com/\n"
6128 "http://www.theokorigroup.com/\n"
6130 "College of Creative Studies,\n"
6131 "University of California,\n"
6133 "http://www.ccs.ucsb.edu/"
6136 [sheet popupAlertAnimated:YES];
6139 - (NSString *) leftButtonTitle {
6140 return UCLocalize("ABOUT");
6145 /* Manage View {{{ */
6146 @interface ManageView : CydiaBrowserView {
6151 @implementation ManageView
6153 - (NSString *) title {
6154 return UCLocalize("MANAGE");
6157 - (void) _leftButtonClicked {
6158 [delegate_ askForSettings];
6161 - (NSString *) leftButtonTitle {
6162 return UCLocalize("SETTINGS");
6166 - (id) _rightButtonTitle {
6167 return Queuing_ ? UCLocalize("QUEUE") : nil;
6170 - (UINavigationButtonStyle) rightButtonStyle {
6171 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6174 - (void) _rightButtonClicked {
6179 - (bool) isLoading {
6186 /* Cydia Book {{{ */
6187 @interface CYBook : RVBook <
6190 _transient Database *database_;
6191 UINavigationBar *overlay_;
6192 UINavigationBar *underlay_;
6193 UIProgressIndicator *indicator_;
6194 UITextLabel *prompt_;
6195 UIProgressBar *progress_;
6196 UINavigationButton *cancel_;
6200 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6206 @implementation CYBook
6210 [indicator_ release];
6212 [progress_ release];
6217 - (NSString *) getTitleForPage:(RVPage *)page {
6218 return [super getTitleForPage:page];
6226 [UIView beginAnimations:nil context:NULL];
6228 CGRect ovrframe = [overlay_ frame];
6229 ovrframe.origin.y = 0;
6230 [overlay_ setFrame:ovrframe];
6232 CGRect barframe = [navbar_ frame];
6233 barframe.origin.y += ovrframe.size.height;
6234 [navbar_ setFrame:barframe];
6236 CGRect trnframe = [transition_ frame];
6237 trnframe.origin.y += ovrframe.size.height;
6238 trnframe.size.height -= ovrframe.size.height;
6239 [transition_ setFrame:trnframe];
6241 [UIView endAnimations];
6243 [indicator_ startAnimation];
6244 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6245 [progress_ setProgress:0];
6248 [overlay_ addSubview:cancel_];
6251 detachNewThreadSelector:@selector(_update)
6257 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6258 NSString *context([sheet context]);
6260 if ([context isEqualToString:@"refresh"])
6264 - (void) _update_:(NSString *)error {
6267 [indicator_ stopAnimation];
6269 [UIView beginAnimations:nil context:NULL];
6271 CGRect ovrframe = [overlay_ frame];
6272 ovrframe.origin.y = -ovrframe.size.height;
6273 [overlay_ setFrame:ovrframe];
6275 CGRect barframe = [navbar_ frame];
6276 barframe.origin.y -= ovrframe.size.height;
6277 [navbar_ setFrame:barframe];
6279 CGRect trnframe = [transition_ frame];
6280 trnframe.origin.y -= ovrframe.size.height;
6281 trnframe.size.height += ovrframe.size.height;
6282 [transition_ setFrame:trnframe];
6284 [UIView commitAnimations];
6287 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6289 UIActionSheet *sheet = [[[UIActionSheet alloc]
6290 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6291 buttons:[NSArray arrayWithObjects:
6294 defaultButtonIndex:0
6299 [sheet setBodyText:error];
6300 [sheet popupAlertAnimated:YES];
6302 [self reloadButtons];
6306 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6307 if ((self = [super initWithFrame:frame]) != nil) {
6308 database_ = database;
6310 CGRect ovrrect = [navbar_ bounds];
6311 ovrrect.size.height = [UINavigationBar defaultSize].height;
6312 ovrrect.origin.y = -ovrrect.size.height;
6314 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6315 [self addSubview:overlay_];
6317 ovrrect.origin.y = frame.size.height;
6318 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6319 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6320 [self addSubview:underlay_];
6322 [overlay_ setBarStyle:1];
6323 [underlay_ setBarStyle:1];
6325 int barstyle = [overlay_ _barStyle:NO];
6326 bool ugly = barstyle == 0;
6328 UIProgressIndicatorStyle style = ugly ?
6329 UIProgressIndicatorStyleMediumBrown :
6330 UIProgressIndicatorStyleMediumWhite;
6332 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
6333 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6334 CGRect indrect = {{indoffset, indoffset}, indsize};
6336 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6337 [indicator_ setStyle:style];
6338 [overlay_ addSubview:indicator_];
6340 CGSize prmsize = {215, indsize.height + 4};
6343 indoffset * 2 + indsize.width,
6347 unsigned(ovrrect.size.height - prmsize.height) / 2
6350 UIFont *font = [UIFont systemFontOfSize:15];
6352 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6354 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6355 [prompt_ setBackgroundColor:[UIColor clearColor]];
6356 [prompt_ setFont:font];
6358 [overlay_ addSubview:prompt_];
6360 CGSize prgsize = {75, 100};
6363 ovrrect.size.width - prgsize.width - 10,
6364 (ovrrect.size.height - prgsize.height) / 2
6367 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6368 [progress_ setStyle:0];
6369 [overlay_ addSubview:progress_];
6371 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6372 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6374 CGRect frame = [cancel_ frame];
6375 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6376 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6377 [cancel_ setFrame:frame];
6379 [cancel_ setBarStyle:barstyle];
6383 - (void) _onCancel {
6385 [cancel_ removeFromSuperview];
6388 - (void) _update { _pooled
6390 status.setDelegate(self);
6392 NSString *error([database_ updateWithStatus:status]);
6395 performSelectorOnMainThread:@selector(_update_:)
6401 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6402 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6405 - (void) setProgressTitle:(NSString *)title {
6407 performSelectorOnMainThread:@selector(_setProgressTitle:)
6413 - (void) setProgressPercent:(float)percent {
6415 performSelectorOnMainThread:@selector(_setProgressPercent:)
6416 withObject:[NSNumber numberWithFloat:percent]
6421 - (void) startProgress {
6424 - (void) addProgressOutput:(NSString *)output {
6426 performSelectorOnMainThread:@selector(_addProgressOutput:)
6432 - (bool) isCancelling:(size_t)received {
6436 - (void) _setProgressTitle:(NSString *)title {
6437 [prompt_ setText:title];
6440 - (void) _setProgressPercent:(NSNumber *)percent {
6441 [progress_ setProgress:[percent floatValue]];
6444 - (void) _addProgressOutput:(NSString *)output {
6449 /* Cydia:// Protocol {{{ */
6450 @interface CydiaURLProtocol : NSURLProtocol {
6455 @implementation CydiaURLProtocol
6457 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6458 NSURL *url([request URL]);
6461 NSString *scheme([[url scheme] lowercaseString]);
6462 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6467 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6471 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6472 id<NSURLProtocolClient> client([self client]);
6474 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6476 NSData *data(UIImagePNGRepresentation(icon));
6478 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6479 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6480 [client URLProtocol:self didLoadData:data];
6481 [client URLProtocolDidFinishLoading:self];
6485 - (void) startLoading {
6486 id<NSURLProtocolClient> client([self client]);
6487 NSURLRequest *request([self request]);
6489 NSURL *url([request URL]);
6490 NSString *href([url absoluteString]);
6492 NSString *path([href substringFromIndex:8]);
6493 NSRange slash([path rangeOfString:@"/"]);
6496 if (slash.location == NSNotFound) {
6500 command = [path substringToIndex:slash.location];
6501 path = [path substringFromIndex:(slash.location + 1)];
6504 Database *database([Database sharedInstance]);
6506 if ([command isEqualToString:@"package-icon"]) {
6509 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6510 Package *package([database packageWithName:path]);
6513 UIImage *icon([package icon]);
6514 [self _returnPNGWithImage:icon forRequest:request];
6515 } else if ([command isEqualToString:@"source-icon"]) {
6518 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6519 NSString *source(Simplify(path));
6520 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6522 icon = [UIImage applicationImageNamed:@"unknown.png"];
6523 [self _returnPNGWithImage:icon forRequest:request];
6524 } else if ([command isEqualToString:@"uikit-image"]) {
6527 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6528 UIImage *icon(_UIImageWithName(path));
6529 [self _returnPNGWithImage:icon forRequest:request];
6530 } else if ([command isEqualToString:@"section-icon"]) {
6533 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6534 NSString *section(Simplify(path));
6535 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6537 icon = [UIImage applicationImageNamed:@"unknown.png"];
6538 [self _returnPNGWithImage:icon forRequest:request];
6540 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6544 - (void) stopLoading {
6550 /* Sections View {{{ */
6551 @interface SectionsView : RVPage {
6552 _transient Database *database_;
6553 NSMutableArray *sections_;
6554 NSMutableArray *filtered_;
6555 UITransitionView *transition_;
6561 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6562 - (void) reloadData;
6567 @implementation SectionsView
6570 [list_ setDataSource:nil];
6571 [list_ setDelegate:nil];
6573 [sections_ release];
6574 [filtered_ release];
6575 [transition_ release];
6577 [accessory_ release];
6581 - (int) numberOfRowsInTable:(UITable *)table {
6582 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6585 - (float) table:(UITable *)table heightForRow:(int)row {
6589 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6591 reusing = [[[SectionCell alloc] init] autorelease];
6592 [(SectionCell *)reusing setSection:(editing_ ?
6593 [sections_ objectAtIndex:row] :
6594 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6595 ) editing:editing_];
6599 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6603 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6607 - (void) tableRowSelected:(NSNotification *)notification {
6608 int row = [[notification object] selectedRow];
6619 title = UCLocalize("ALL_PACKAGES");
6621 section = [filtered_ objectAtIndex:(row - 1)];
6622 name = [section name];
6625 name = [NSString stringWithString:name];
6626 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6629 title = UCLocalize("NO_SECTION");
6633 PackageTable *table = [[[FilteredPackageTable alloc]
6637 filter:@selector(isVisiblyUninstalledInSection:)
6641 [table setDelegate:delegate_];
6643 [book_ pushPage:table];
6646 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6647 if ((self = [super initWithBook:book]) != nil) {
6648 database_ = database;
6650 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6651 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6653 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6654 [self addSubview:transition_];
6656 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6657 [transition_ transition:0 toView:list_];
6659 UITableColumn *column = [[[UITableColumn alloc]
6660 initWithTitle:UCLocalize("NAME")
6662 width:[self frame].size.width
6665 [list_ setDataSource:self];
6666 [list_ setSeparatorStyle:1];
6667 [list_ addTableColumn:column];
6668 [list_ setDelegate:self];
6669 [list_ setReusesTableCells:YES];
6673 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6674 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6678 - (void) reloadData {
6679 NSArray *packages = [database_ packages];
6681 [sections_ removeAllObjects];
6682 [filtered_ removeAllObjects];
6685 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6686 SectionMap sections;
6687 sections.resize(64);
6689 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6693 for (Package *package in packages) {
6694 NSString *name([package section]);
6695 NSString *key(name == nil ? @"" : name);
6700 _profile(SectionsView$reloadData$Section)
6701 section = §ions[key];
6702 if (*section == nil) {
6703 _profile(SectionsView$reloadData$Section$Allocate)
6704 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6709 [*section addToCount];
6711 _profile(SectionsView$reloadData$Filter)
6712 if (![package valid] || ![package uninstalled] || ![package visible])
6716 [*section addToRow];
6720 _profile(SectionsView$reloadData$Section)
6721 section = [sections objectForKey:key];
6722 if (section == nil) {
6723 _profile(SectionsView$reloadData$Section$Allocate)
6724 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6725 [sections setObject:section forKey:key];
6730 [section addToCount];
6732 _profile(SectionsView$reloadData$Filter)
6733 if (![package valid] || ![package uninstalled] || ![package visible])
6743 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6744 [sections_ addObject:i->second];
6746 [sections_ addObjectsFromArray:[sections allValues]];
6749 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6751 for (Section *section in sections_) {
6752 size_t count([section row]);
6756 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6757 [section setCount:count];
6758 [filtered_ addObject:section];
6765 - (void) resetView {
6767 [self _rightButtonClicked];
6770 - (void) resetViewAnimated:(BOOL)animated {
6771 [list_ resetViewAnimated:animated];
6774 - (void) _rightButtonClicked {
6775 if ((editing_ = !editing_))
6778 [delegate_ updateData];
6779 [book_ reloadTitleForPage:self];
6780 [book_ reloadButtonsForPage:self];
6783 - (NSString *) title {
6784 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("INSTALL_BY_SECTION");
6787 - (NSString *) backButtonTitle {
6788 return UCLocalize("SECTIONS");
6791 - (id) rightButtonTitle {
6792 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6795 - (UINavigationButtonStyle) rightButtonStyle {
6796 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6799 - (UIView *) accessoryView {
6805 /* Changes View {{{ */
6806 @interface ChangesView : RVPage {
6807 _transient Database *database_;
6808 NSMutableArray *packages_;
6809 NSMutableArray *sections_;
6814 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6815 - (void) reloadData;
6819 @implementation ChangesView
6822 [list_ setDelegate:nil];
6823 [list_ setDataSource:nil];
6825 [packages_ release];
6826 [sections_ release];
6831 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6832 NSInteger count([sections_ count]);
6833 return count == 0 ? 1 : count;
6836 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6837 if ([sections_ count] == 0)
6839 return [[sections_ objectAtIndex:section] name];
6842 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6843 if ([sections_ count] == 0)
6845 return [[sections_ objectAtIndex:section] count];
6848 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6849 Section *section([sections_ objectAtIndex:[path section]]);
6850 NSInteger row([path row]);
6851 return [packages_ objectAtIndex:([section row] + row)];
6854 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6855 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6857 cell = [[[PackageCell alloc] init] autorelease];
6858 [cell setPackage:[self packageAtIndexPath:path]];
6862 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6864 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6867 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6868 Package *package([self packageAtIndexPath:path]);
6869 PackageView *view([delegate_ packageView]);
6870 [view setDelegate:delegate_];
6871 [view setPackage:package];
6872 [book_ pushPage:view];
6876 - (void) _leftButtonClicked {
6877 [(CYBook *)book_ update];
6878 [self reloadButtons];
6881 - (void) _rightButtonClicked {
6882 [delegate_ distUpgrade];
6885 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6886 if ((self = [super initWithBook:book]) != nil) {
6887 database_ = database;
6889 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6890 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6892 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
6893 [self addSubview:list_];
6895 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
6896 [list_ setDataSource:self];
6897 [list_ setDelegate:self];
6898 //[list_ setSectionListStyle:1];
6902 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6903 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6907 - (void) reloadData {
6908 NSArray *packages = [database_ packages];
6910 [packages_ removeAllObjects];
6911 [sections_ removeAllObjects];
6914 for (Package *package in packages)
6916 [package uninstalled] && [package valid] && [package visible] ||
6917 [package upgradableAndEssential:YES]
6919 [packages_ addObject:package];
6922 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6925 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6926 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6927 Section *section = nil;
6931 bool unseens = false;
6933 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6935 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6936 Package *package = [packages_ objectAtIndex:offset];
6938 BOOL uae = [package upgradableAndEssential:YES];
6944 _profile(ChangesView$reloadData$Remember)
6945 seen = [package seen];
6948 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6953 name = UCLocalize("UNKNOWN");
6955 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6959 _profile(ChangesView$reloadData$Allocate)
6960 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
6961 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6962 [sections_ addObject:section];
6966 [section addToCount];
6967 } else if ([package ignored])
6968 [ignored addToCount];
6971 [upgradable addToCount];
6976 CFRelease(formatter);
6979 Section *last = [sections_ lastObject];
6980 size_t count = [last count];
6981 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6982 [sections_ removeLastObject];
6985 if ([ignored count] != 0)
6986 [sections_ insertObject:ignored atIndex:0];
6988 [sections_ insertObject:upgradable atIndex:0];
6991 [self reloadButtons];
6994 - (void) resetViewAnimated:(BOOL)animated {
6995 [list_ resetViewAnimated:animated];
6998 - (NSString *) leftButtonTitle {
6999 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
7002 - (id) rightButtonTitle {
7003 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
7006 - (NSString *) title {
7007 return UCLocalize("CHANGES");
7012 /* Search View {{{ */
7013 @protocol SearchViewDelegate
7014 - (void) showKeyboard:(BOOL)show;
7017 @interface SearchView : RVPage {
7019 UISearchField *field_;
7020 UITransitionView *transition_;
7021 FilteredPackageTable *table_;
7022 UIPreferencesTable *advanced_;
7028 - (id) initWithBook:(RVBook *)book database:(Database *)database;
7029 - (void) reloadData;
7033 @implementation SearchView
7036 [field_ setDelegate:nil];
7038 [accessory_ release];
7040 [transition_ release];
7042 [advanced_ release];
7047 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7051 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7053 case 0: return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("ADVANCED_SEARCH"), UCLocalize("COMING_SOON")];
7055 default: _assert(false);
7059 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7063 default: _assert(false);
7067 - (void) _showKeyboard:(BOOL)show {
7068 CGSize keysize = [UIKeyboard defaultSize];
7069 CGRect keydown = [book_ pageBounds];
7070 CGRect keyup = keydown;
7071 keyup.size.height -= keysize.height - ButtonBarHeight_;
7073 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7075 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7076 [animation setSignificantRectFields:8];
7079 [animation setStartFrame:keydown];
7080 [animation setEndFrame:keyup];
7082 [animation setStartFrame:keyup];
7083 [animation setEndFrame:keydown];
7086 UIAnimator *animator = [UIAnimator sharedAnimator];
7089 addAnimations:[NSArray arrayWithObjects:animation, nil]
7090 withDuration:(KeyboardTime_ - delay)
7095 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7097 [delegate_ showKeyboard:show];
7100 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7101 [self _showKeyboard:YES];
7104 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7105 [self _showKeyboard:NO];
7108 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7110 NSString *text([field_ text]);
7111 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7117 - (void) textFieldClearButtonPressed:(UITextField *)field {
7121 - (void) keyboardInputShouldDelete:(id)input {
7125 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7126 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7130 [field_ resignFirstResponder];
7135 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7136 if ((self = [super initWithBook:book]) != nil) {
7137 CGRect pageBounds = [book_ pageBounds];
7139 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
7140 [self addSubview:transition_];
7142 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
7144 [advanced_ setReusesTableCells:YES];
7145 [advanced_ setDataSource:self];
7146 [advanced_ reloadData];
7148 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
7149 CGColor dimmed(space_, 0, 0, 0, 0.5);
7150 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
7152 table_ = [[FilteredPackageTable alloc]
7156 filter:@selector(isUnfilteredAndSearchedForBy:)
7160 [table_ setShouldHideHeaderInShortLists:NO];
7161 [transition_ transition:0 toView:table_];
7170 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
7177 [self bounds].size.width - area.origin.x - 18;
7179 area.size.height = [UISearchField defaultHeight];
7181 field_ = [[UISearchField alloc] initWithFrame:area];
7183 UIFont *font = [UIFont systemFontOfSize:16];
7184 [field_ setFont:font];
7186 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7187 [field_ setDelegate:self];
7189 [field_ setPaddingTop:5];
7191 UITextInputTraits *traits([field_ textInputTraits]);
7192 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7193 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7194 [traits setReturnKeyType:UIReturnKeySearch];
7196 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7198 accessory_ = [[UIView alloc] initWithFrame:accrect];
7199 [accessory_ addSubview:field_];
7201 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
7202 [configure setShowPressFeedback:YES];
7203 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
7204 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
7205 [accessory_ addSubview:configure];*/
7207 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7208 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7214 LKAnimation *animation = [LKTransition animation];
7215 [animation setType:@"oglFlip"];
7216 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
7217 [animation setFillMode:@"extended"];
7218 [animation setTransitionFlags:3];
7219 [animation setDuration:10];
7220 [animation setSpeed:0.35];
7221 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
7222 [[transition_ _layer] addAnimation:animation forKey:0];
7223 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
7224 flipped_ = !flipped_;
7228 - (void) configurePushed {
7229 [field_ resignFirstResponder];
7233 - (void) resetViewAnimated:(BOOL)animated {
7236 [table_ resetViewAnimated:animated];
7239 - (void) _reloadData {
7242 - (void) reloadData {
7245 [table_ setObject:[field_ text]];
7246 _profile(SearchView$reloadData)
7247 [table_ reloadData];
7250 [table_ resetCursor];
7253 - (UIView *) accessoryView {
7257 - (NSString *) title {
7261 - (NSString *) backButtonTitle {
7262 return UCLocalize("SEARCH");
7265 - (void) setDelegate:(id)delegate {
7266 [table_ setDelegate:delegate];
7267 [super setDelegate:delegate];
7273 @interface SettingsView : RVPage {
7274 _transient Database *database_;
7277 UIPreferencesTable *table_;
7278 _UISwitchSlider *subscribedSwitch_;
7279 _UISwitchSlider *ignoredSwitch_;
7280 UIPreferencesControlTableCell *subscribedCell_;
7281 UIPreferencesControlTableCell *ignoredCell_;
7284 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7288 @implementation SettingsView
7291 [table_ setDataSource:nil];
7294 if (package_ != nil)
7297 [subscribedSwitch_ release];
7298 [ignoredSwitch_ release];
7299 [subscribedCell_ release];
7300 [ignoredCell_ release];
7304 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7305 if (package_ == nil)
7311 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7312 if (package_ == nil)
7319 default: _assert(false);
7325 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7326 if (package_ == nil)
7333 default: _assert(false);
7339 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7340 if (package_ == nil)
7347 default: _assert(false);
7353 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7354 if (package_ == nil)
7357 _UISwitchSlider *slider([cell control]);
7358 BOOL value([slider value] != 0);
7359 NSMutableDictionary *metadata([package_ metadata]);
7362 if (NSNumber *number = [metadata objectForKey:key])
7363 before = [number boolValue];
7367 if (value != before) {
7368 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7370 [delegate_ updateData];
7374 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7375 [self onSomething:cell withKey:@"IsSubscribed"];
7378 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7379 [self onSomething:cell withKey:@"IsIgnored"];
7382 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7383 if (package_ == nil)
7387 case 0: switch (row) {
7389 return subscribedCell_;
7391 return ignoredCell_;
7392 default: _assert(false);
7395 case 1: switch (row) {
7397 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7398 [cell setShowSelection:NO];
7399 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7403 default: _assert(false);
7406 default: _assert(false);
7412 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7413 if ((self = [super initWithBook:book])) {
7414 database_ = database;
7415 name_ = [package retain];
7417 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7418 [self addSubview:table_];
7420 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7421 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
7423 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7424 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
7426 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7427 [subscribedCell_ setShowSelection:NO];
7428 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7429 [subscribedCell_ setControl:subscribedSwitch_];
7431 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7432 [ignoredCell_ setShowSelection:NO];
7433 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7434 [ignoredCell_ setControl:ignoredSwitch_];
7436 [table_ setDataSource:self];
7441 - (void) resetViewAnimated:(BOOL)animated {
7442 [table_ resetViewAnimated:animated];
7445 - (void) reloadData {
7446 if (package_ != nil)
7447 [package_ autorelease];
7448 package_ = [database_ packageWithName:name_];
7449 if (package_ != nil) {
7451 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7452 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7455 [table_ reloadData];
7458 - (NSString *) title {
7459 return UCLocalize("SETTINGS");
7464 /* Signature View {{{ */
7465 @interface SignatureView : CydiaBrowserView {
7466 _transient Database *database_;
7470 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7474 @implementation SignatureView
7481 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7483 [super webView:sender didClearWindowObject:window forFrame:frame];
7486 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7487 if ((self = [super initWithBook:book]) != nil) {
7488 database_ = database;
7489 package_ = [package retain];
7494 - (void) resetViewAnimated:(BOOL)animated {
7497 - (void) reloadData {
7498 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7504 @interface Cydia : UIApplication <
7505 ConfirmationViewDelegate,
7506 ProgressViewDelegate,
7515 UIToolbar *buttonbar_;
7519 NSMutableArray *essential_;
7520 NSMutableArray *broken_;
7522 Database *database_;
7523 ProgressView *progress_;
7527 UIKeyboard *keyboard_;
7528 UIProgressHUD *hud_;
7530 SectionsView *sections_;
7531 ChangesView *changes_;
7532 ManageView *manage_;
7533 SearchView *search_;
7535 #if RecyclePackageViews
7536 NSMutableArray *details_;
7542 @implementation Cydia
7545 if ([broken_ count] != 0) {
7546 int count = [broken_ count];
7548 UIActionSheet *sheet = [[[UIActionSheet alloc]
7549 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7550 buttons:[NSArray arrayWithObjects:
7551 UCLocalize("FORCIBLY_CLEAR"),
7552 UCLocalize("TEMPORARY_IGNORE"),
7554 defaultButtonIndex:0
7559 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7560 [sheet popupAlertAnimated:YES];
7561 } else if (!Ignored_ && [essential_ count] != 0) {
7562 int count = [essential_ count];
7564 UIActionSheet *sheet = [[[UIActionSheet alloc]
7565 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7566 buttons:[NSArray arrayWithObjects:
7567 UCLocalize("UPGRADE_ESSENTIAL"),
7568 UCLocalize("COMPLETE_UPGRADE"),
7569 UCLocalize("TEMPORARY_IGNORE"),
7571 defaultButtonIndex:0
7576 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7577 [sheet popupAlertAnimated:YES];
7581 - (void) _saveConfig {
7584 NSString *error(nil);
7585 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7587 NSError *error(nil);
7588 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7589 NSLog(@"failure to save metadata data: %@", error);
7592 NSLog(@"failure to serialize metadata: %@", error);
7600 - (void) _updateData {
7603 /* XXX: this is just stupid */
7604 if (tag_ != 2 && sections_ != nil)
7605 [sections_ reloadData];
7606 if (tag_ != 3 && changes_ != nil)
7607 [changes_ reloadData];
7608 if (tag_ != 5 && search_ != nil)
7609 [search_ reloadData];
7614 - (void) _reloadData {
7617 static bool loaded(false);
7618 UIProgressHUD *hud([self addProgressHUD]);
7619 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7622 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7625 [self removeProgressHUD:hud];
7629 [essential_ removeAllObjects];
7630 [broken_ removeAllObjects];
7632 NSArray *packages = [database_ packages];
7633 for (Package *package in packages) {
7635 [broken_ addObject:package];
7636 if ([package upgradableAndEssential:NO]) {
7637 if ([package essential])
7638 [essential_ addObject:package];
7644 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7645 [buttonbar_ setBadgeValue:badge forButton:3];
7646 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7647 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7648 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7649 [self setApplicationBadge:badge];
7651 [self setApplicationBadgeString:badge];
7653 [buttonbar_ setBadgeValue:nil forButton:3];
7654 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7655 [buttonbar_ setBadgeAnimated:NO forButton:3];
7656 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7657 [self removeApplicationBadge];
7658 else // XXX: maybe use setApplicationBadgeString also?
7659 [self setApplicationIconBadgeNumber:0];
7663 [buttonbar_ setBadgeValue:nil forButton:4];
7667 // XXX: what is this line of code for?
7668 if ([packages count] == 0);
7669 else if (Loaded_ || ManualRefresh) loaded:
7674 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7675 NSTimeInterval interval([update timeIntervalSinceNow]);
7676 if (interval <= 0 && interval > -600)
7684 - (void) updateData {
7685 [database_ setVisible];
7694 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7695 _assert(file != NULL);
7697 NSArray *keys = [Sources_ allKeys];
7699 for (NSString *key in keys) {
7700 NSDictionary *source = [Sources_ objectForKey:key];
7702 fprintf(file, "%s %s %s\n",
7703 [[source objectForKey:@"Type"] UTF8String],
7704 [[source objectForKey:@"URI"] UTF8String],
7705 [[source objectForKey:@"Distribution"] UTF8String]
7714 detachNewThreadSelector:@selector(update_)
7717 title:UCLocalize("UPDATING_SOURCES")
7721 - (void) reloadData {
7722 @synchronized (self) {
7723 if (confirm_ == nil)
7729 pkgProblemResolver *resolver = [database_ resolver];
7731 resolver->InstallProtect();
7732 if (!resolver->Resolve(true))
7736 - (void) popUpBook:(RVBook *)book {
7737 [underlay_ popSubview:book];
7740 - (CGRect) popUpBounds {
7741 return [underlay_ bounds];
7745 [database_ prepare];
7747 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7748 [confirm_ setDelegate:self];
7750 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7751 [page setDelegate:self];
7753 [confirm_ setPage:page];
7754 [self popUpBook:confirm_];
7758 @synchronized (self) {
7763 - (void) clearPackage:(Package *)package {
7764 @synchronized (self) {
7771 - (void) installPackage:(Package *)package {
7772 @synchronized (self) {
7779 - (void) removePackage:(Package *)package {
7780 @synchronized (self) {
7787 - (void) distUpgrade {
7788 @synchronized (self) {
7789 [database_ upgrade];
7795 [self slideUp:[[[UIActionSheet alloc]
7797 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7798 defaultButtonIndex:1
7805 @synchronized (self) {
7808 if (confirm_ != nil) {
7816 [overlay_ removeFromSuperview];
7820 detachNewThreadSelector:@selector(perform)
7823 title:UCLocalize("RUNNING")
7827 - (void) bootstrap_ {
7829 [database_ upgrade];
7830 [database_ prepare];
7831 [database_ perform];
7834 /* XXX: replace and localize */
7835 - (void) bootstrap {
7837 detachNewThreadSelector:@selector(bootstrap_)
7840 title:@"Bootstrap Install"
7844 - (void) progressViewIsComplete:(ProgressView *)progress {
7845 if (confirm_ != nil) {
7846 [underlay_ addSubview:overlay_];
7847 [confirm_ popFromSuperviewAnimated:NO];
7853 - (void) setPage:(RVPage *)page {
7854 [page resetViewAnimated:NO];
7855 [page setDelegate:self];
7856 [book_ setPage:page];
7859 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7860 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7861 [browser loadURL:url];
7865 - (void) _setHomePage {
7866 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7869 - (SectionsView *) sectionsView {
7870 if (sections_ == nil)
7871 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7875 - (void) buttonBarItemTapped:(id)sender {
7876 unsigned tag = [sender tag];
7878 [book_ resetViewAnimated:YES];
7880 } else if (tag_ == 2 && tag != 2)
7881 [[self sectionsView] resetView];
7884 case 1: [self _setHomePage]; break;
7886 case 2: [self setPage:[self sectionsView]]; break;
7887 case 3: [self setPage:changes_]; break;
7888 case 4: [self setPage:manage_]; break;
7889 case 5: [self setPage:search_]; break;
7891 default: _assert(false);
7897 - (void) applicationWillSuspend {
7899 [super applicationWillSuspend];
7902 - (void) askForSettings {
7903 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7905 UIActionSheet *role = [[[UIActionSheet alloc]
7906 initWithTitle:UCLocalize("WHO_ARE_YOU")
7907 buttons:[NSArray arrayWithObjects:
7908 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7909 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7910 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7912 defaultButtonIndex:-1
7917 [role setBodyText:UCLocalize("ROLE_EX")];
7918 [role popupAlertAnimated:YES];
7921 - (void) setPackageView:(PackageView *)view {
7923 [view setPackage:nil];
7924 #if RecyclePackageViews
7925 if ([details_ count] < 3)
7926 [details_ addObject:view];
7931 - (PackageView *) _packageView {
7932 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7935 - (PackageView *) packageView {
7936 #if RecyclePackageViews
7938 size_t count([details_ count]);
7941 view = [self _packageView];
7943 [details_ addObject:[self _packageView]];
7945 view = [[[details_ lastObject] retain] autorelease];
7946 [details_ removeLastObject];
7953 return [self _packageView];
7959 [self setStatusBarShowsProgress:NO];
7960 [self removeProgressHUD:hud_];
7965 pid_t pid = ExecFork();
7967 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7968 perror("launchctl stop");
7975 [self askForSettings];
7980 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7982 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7983 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7984 0, 0, screenrect.size.width, screenrect.size.height - 48
7985 ) database:database_];
7987 [book_ setDelegate:self];
7989 [overlay_ addSubview:book_];
7991 NSArray *buttonitems = [NSArray arrayWithObjects:
7992 [NSDictionary dictionaryWithObjectsAndKeys:
7993 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7994 @"home-up.png", kUIButtonBarButtonInfo,
7995 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7996 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7997 self, kUIButtonBarButtonTarget,
7998 @"Cydia", kUIButtonBarButtonTitle,
7999 @"0", kUIButtonBarButtonType,
8002 [NSDictionary dictionaryWithObjectsAndKeys:
8003 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8004 @"install-up.png", kUIButtonBarButtonInfo,
8005 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
8006 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
8007 self, kUIButtonBarButtonTarget,
8008 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
8009 @"0", kUIButtonBarButtonType,
8012 [NSDictionary dictionaryWithObjectsAndKeys:
8013 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8014 @"changes-up.png", kUIButtonBarButtonInfo,
8015 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
8016 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
8017 self, kUIButtonBarButtonTarget,
8018 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
8019 @"0", kUIButtonBarButtonType,
8022 [NSDictionary dictionaryWithObjectsAndKeys:
8023 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8024 @"manage-up.png", kUIButtonBarButtonInfo,
8025 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
8026 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
8027 self, kUIButtonBarButtonTarget,
8028 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
8029 @"0", kUIButtonBarButtonType,
8032 [NSDictionary dictionaryWithObjectsAndKeys:
8033 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8034 @"search-up.png", kUIButtonBarButtonInfo,
8035 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
8036 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
8037 self, kUIButtonBarButtonTarget,
8038 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
8039 @"0", kUIButtonBarButtonType,
8043 buttonbar_ = [[UIToolbar alloc]
8045 withFrame:CGRectMake(
8046 0, screenrect.size.height - ButtonBarHeight_,
8047 screenrect.size.width, ButtonBarHeight_
8049 withItemList:buttonitems
8052 [buttonbar_ setDelegate:self];
8053 [buttonbar_ setBarStyle:1];
8054 [buttonbar_ setButtonBarTrackingMode:2];
8056 int buttons[5] = {1, 2, 3, 4, 5};
8057 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
8058 [buttonbar_ showButtonGroup:0 withDuration:0];
8060 for (int i = 0; i != 5; ++i)
8061 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
8062 i * 64 + 2, 1, 60, ButtonBarHeight_
8065 [buttonbar_ showSelectionForButton:1];
8066 [overlay_ addSubview:buttonbar_];
8068 [UIKeyboard initImplementationNow];
8069 CGSize keysize = [UIKeyboard defaultSize];
8070 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8071 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8072 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
8073 [overlay_ addSubview:keyboard_];
8076 [underlay_ addSubview:overlay_];
8080 [self sectionsView];
8081 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
8082 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
8084 manage_ = (ManageView *) [[self
8085 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8086 withClass:[ManageView class]
8089 #if RecyclePackageViews
8090 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8091 [details_ addObject:[self _packageView]];
8092 [details_ addObject:[self _packageView]];
8100 [self _setHomePage];
8103 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
8104 NSString *context([sheet context]);
8106 if ([context isEqualToString:@"missing"])
8108 else if ([context isEqualToString:@"cancel"]) {
8126 @synchronized (self) {
8131 [buttonbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
8135 if (confirm_ != nil) {
8140 } else if ([context isEqualToString:@"fixhalf"]) {
8143 @synchronized (self) {
8144 for (Package *broken in broken_) {
8147 NSString *id = [broken id];
8148 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8149 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8150 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8151 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8160 [broken_ removeAllObjects];
8169 } else if ([context isEqualToString:@"role"]) {
8171 case 1: Role_ = @"User"; break;
8172 case 2: Role_ = @"Hacker"; break;
8173 case 3: Role_ = @"Developer"; break;
8180 bool reset = Settings_ != nil;
8182 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8186 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8196 } else if ([context isEqualToString:@"upgrade"]) {
8199 @synchronized (self) {
8200 for (Package *essential in essential_)
8201 [essential install];
8224 - (void) reorganize { _pooled
8225 system("/usr/libexec/cydia/free.sh");
8226 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
8229 - (void) applicationSuspend:(__GSEvent *)event {
8230 if (hud_ == nil && ![progress_ isRunning])
8231 [super applicationSuspend:event];
8234 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8236 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8239 - (void) _setSuspended:(BOOL)value {
8241 [super _setSuspended:value];
8244 - (UIProgressHUD *) addProgressHUD {
8245 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8246 [window_ setUserInteractionEnabled:NO];
8248 [progress_ addSubview:hud];
8252 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8254 [hud removeFromSuperview];
8255 [window_ setUserInteractionEnabled:YES];
8258 - (RVPage *) pageForPackage:(NSString *)name {
8259 if (Package *package = [database_ packageWithName:name]) {
8260 PackageView *view([self packageView]);
8261 [view setPackage:package];
8264 UIActionSheet *sheet = [[[UIActionSheet alloc]
8265 initWithTitle:UCLocalize("CANNOT_LOCATE_PACKAGE")
8266 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
8267 defaultButtonIndex:0
8272 [sheet setBodyText:[NSString stringWithFormat:UCLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
8274 [sheet popupAlertAnimated:YES];
8279 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8283 NSString *href([url absoluteString]);
8284 if ([href hasPrefix:@"apptapp://package/"])
8285 return [self pageForPackage:[href substringFromIndex:18]];
8287 NSString *scheme([[url scheme] lowercaseString]);
8288 if (![scheme isEqualToString:@"cydia"])
8290 NSString *path([url absoluteString]);
8291 if ([path length] < 8)
8293 path = [path substringFromIndex:8];
8294 if (![path hasPrefix:@"/"])
8295 path = [@"/" stringByAppendingString:path];
8297 if ([path isEqualToString:@"/add-source"])
8298 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8299 else if ([path isEqualToString:@"/storage"])
8300 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8301 else if ([path isEqualToString:@"/sources"])
8302 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8303 else if ([path isEqualToString:@"/packages"])
8304 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8305 else if ([path hasPrefix:@"/url/"])
8306 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8307 else if ([path hasPrefix:@"/launch/"])
8308 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8309 else if ([path hasPrefix:@"/package-settings/"])
8310 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8311 else if ([path hasPrefix:@"/package-signature/"])
8312 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8313 else if ([path hasPrefix:@"/package/"])
8314 return [self pageForPackage:[path substringFromIndex:9]];
8315 else if ([path hasPrefix:@"/files/"]) {
8316 NSString *name = [path substringFromIndex:7];
8318 if (Package *package = [database_ packageWithName:name]) {
8319 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8320 [files setPackage:package];
8328 - (void) applicationOpenURL:(NSURL *)url {
8329 [super applicationOpenURL:url];
8331 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8332 [self setPage:page];
8333 [buttonbar_ showSelectionForButton:tag];
8338 - (void) applicationDidFinishLaunching:(id)unused {
8339 [BrowserView _initialize];
8342 Font12_ = [[UIFont systemFontOfSize:12] retain];
8343 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8344 Font14_ = [[UIFont systemFontOfSize:14] retain];
8345 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8346 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8350 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8351 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8353 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8355 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8356 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
8358 [window_ orderFront:self];
8359 [window_ makeKey:self];
8360 [window_ setHidden:NO];
8362 database_ = [Database sharedInstance];
8363 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8364 [database_ setDelegate:progress_];
8365 [window_ setContentView:progress_];
8367 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8368 [progress_ setContentView:underlay_];
8370 [progress_ resetView];
8373 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8374 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8375 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL /*||
8376 readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL*/ ||
8377 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8378 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8379 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8380 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
8381 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
8383 [self setIdleTimerDisabled:YES];
8385 hud_ = [[self addProgressHUD] retain];
8386 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8388 [self setStatusBarShowsProgress:YES];
8391 detachNewThreadSelector:@selector(reorganize)
8399 - (void) showKeyboard:(BOOL)show {
8400 CGSize keysize = [UIKeyboard defaultSize];
8401 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8402 CGRect keyup = keydown;
8403 keyup.origin.y -= keysize.height;
8405 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8406 [animation setSignificantRectFields:2];
8409 [animation setStartFrame:keydown];
8410 [animation setEndFrame:keyup];
8411 [keyboard_ activate];
8413 [animation setStartFrame:keyup];
8414 [animation setEndFrame:keydown];
8415 [keyboard_ deactivate];
8418 [[UIAnimator sharedAnimator]
8419 addAnimations:[NSArray arrayWithObjects:animation, nil]
8420 withDuration:KeyboardTime_
8425 - (void) slideUp:(UIActionSheet *)alert {
8427 [alert presentSheetFromButtonBar:buttonbar_];
8429 [alert presentSheetInView:overlay_];
8434 void AddPreferences(NSString *plist) { _pooled
8435 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8436 _assert(settings != NULL);
8437 NSMutableArray *items = [settings objectForKey:@"items"];
8441 for (NSMutableDictionary *item in items) {
8442 NSString *label = [item objectForKey:@"label"];
8443 if (label != nil && [label isEqualToString:@"Cydia"]) {
8450 for (size_t i(0); i != [items count]; ++i) {
8451 NSDictionary *item([items objectAtIndex:i]);
8452 NSString *label = [item objectForKey:@"label"];
8453 if (label != nil && [label isEqualToString:@"General"]) {
8454 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8455 @"CydiaSettings", @"bundle",
8456 @"PSLinkCell", @"cell",
8457 [NSNumber numberWithBool:YES], @"hasIcon",
8458 [NSNumber numberWithBool:YES], @"isController",
8460 nil] atIndex:(i + 1)];
8466 _assert([settings writeToFile:plist atomically:YES] == YES);
8471 id Alloc_(id self, SEL selector) {
8472 id object = alloc_(self, selector);
8473 lprintf("[%s]A-%p\n", self->isa->name, object);
8478 id Dealloc_(id self, SEL selector) {
8479 id object = dealloc_(self, selector);
8480 lprintf("[%s]D-%p\n", self->isa->name, object);
8484 Class $WebDefaultUIKitDelegate;
8486 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8488 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8489 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8490 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8491 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8494 int main(int argc, char *argv[]) { _pooled
8497 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8499 /* Library Hacks {{{ */
8500 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8502 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8503 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8504 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8505 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8506 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8509 /* Set Locale {{{ */
8510 Locale_ = CFLocaleCopyCurrent();
8511 Languages_ = [NSLocale preferredLanguages];
8512 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8513 //NSLog(@"%@", [Languages_ description]);
8515 if (Languages_ == nil || [Languages_ count] == 0)
8518 lang = [[Languages_ objectAtIndex:0] UTF8String];
8519 setenv("LANG", lang, true);
8520 //std::setlocale(LC_ALL, lang);
8521 NSLog(@"Setting Language: %s", lang);
8524 // XXX: apr_app_initialize?
8527 /* Parse Arguments {{{ */
8528 bool substrate(false);
8534 for (int argi(1); argi != argc; ++argi)
8535 if (strcmp(argv[argi], "--") == 0) {
8537 argv[argi] = argv[0];
8543 for (int argi(1); argi != arge; ++argi)
8544 if (strcmp(args[argi], "--bootstrap") == 0)
8546 else if (strcmp(args[argi], "--substrate") == 0)
8549 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8554 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8555 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8556 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8557 Sounds_Keyboard_ = [keyboard boolValue];
8560 App_ = [[NSBundle mainBundle] bundlePath];
8561 Home_ = NSHomeDirectory();
8566 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8567 alloc_ = alloc->method_imp;
8568 alloc->method_imp = (IMP) &Alloc_;*/
8570 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8571 dealloc_ = dealloc->method_imp;
8572 dealloc->method_imp = (IMP) &Dealloc_;*/
8577 size = sizeof(maxproc);
8578 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8579 perror("sysctlbyname(\"kern.maxproc\", ?)");
8580 else if (maxproc < 64) {
8582 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8583 perror("sysctlbyname(\"kern.maxproc\", #)");
8586 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8587 char *machine = new char[size];
8588 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8589 perror("sysctlbyname(\"hw.machine\", ?)");
8593 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8595 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8596 Build_ = [system objectForKey:@"ProductBuildVersion"];
8597 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8598 Product_ = [info objectForKey:@"SafariProductVersion"];
8599 Safari_ = [info objectForKey:@"CFBundleVersion"];
8602 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8603 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8605 /* Load Database {{{ */
8607 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8609 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8612 if (Metadata_ == NULL)
8613 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8615 Settings_ = [Metadata_ objectForKey:@"Settings"];
8617 Packages_ = [Metadata_ objectForKey:@"Packages"];
8618 Sections_ = [Metadata_ objectForKey:@"Sections"];
8619 Sources_ = [Metadata_ objectForKey:@"Sources"];
8622 if (Settings_ != nil)
8623 Role_ = [Settings_ objectForKey:@"Role"];
8625 if (Packages_ == nil) {
8626 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8627 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8630 if (Sections_ == nil) {
8631 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8632 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8635 if (Sources_ == nil) {
8636 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8637 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8642 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8645 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8646 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8647 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8648 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8650 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8651 unlink("/tmp/.cydia.fw");
8653 } else if (access("/User", F_OK) != 0) {
8656 system("/usr/libexec/cydia/firmware.sh");
8660 _assert([[NSFileManager defaultManager]
8661 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8662 withIntermediateDirectories:YES
8667 if (access("/tmp/cydia.chk", F_OK) == 0) {
8668 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8669 _assert(errno == ENOENT);
8670 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8671 _assert(errno == ENOENT);
8674 _assert(pkgInitConfig(*_config));
8675 _assert(pkgInitSystem(*_config, _system));
8678 _config->Set("APT::Acquire::Translation", lang);
8679 _config->Set("Acquire::http::Timeout", 15);
8680 _config->Set("Acquire::http::MaxParallel", 3);
8682 /* Color Choices {{{ */
8683 space_ = CGColorSpaceCreateDeviceRGB();
8685 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8686 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8687 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8688 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8689 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8690 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8691 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8692 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8693 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8694 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8695 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8696 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8697 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8698 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8699 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8702 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8703 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8706 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8708 /* UIKit Configuration {{{ */
8709 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8710 if ($GSFontSetUseLegacyFontMetrics != NULL)
8711 $GSFontSetUseLegacyFontMetrics(YES);
8713 UIKeyboardDisableAutomaticAppearance();
8717 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8719 CGColorSpaceRelease(space_);