1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #import "UICaboodle/UCPlatform.h"
45 #import "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <GraphicsServices/GraphicsServices.h>
52 #include <Foundation/Foundation.h>
55 #define DEPLOYMENT_TARGET_MACOSX 1
56 #define CF_BUILDING_CF 1
57 #include <CoreFoundation/CFInternal.h>
60 #include <CoreFoundation/CFPriv.h>
61 #include <CoreFoundation/CFUniChar.h>
63 #import <UIKit/UIKit.h>
65 #include <WebCore/WebCoreThread.h>
66 #import <WebKit/WebDefaultUIKitDelegate.h>
73 #include <ext/stdio_filebuf.h>
77 #include <apt-pkg/acquire.h>
78 #include <apt-pkg/acquire-item.h>
79 #include <apt-pkg/algorithms.h>
80 #include <apt-pkg/cachefile.h>
81 #include <apt-pkg/clean.h>
82 #include <apt-pkg/configuration.h>
83 #include <apt-pkg/debindexfile.h>
84 #include <apt-pkg/debmetaindex.h>
85 #include <apt-pkg/error.h>
86 #include <apt-pkg/init.h>
87 #include <apt-pkg/mmap.h>
88 #include <apt-pkg/pkgrecords.h>
89 #include <apt-pkg/sha1.h>
90 #include <apt-pkg/sourcelist.h>
91 #include <apt-pkg/sptr.h>
92 #include <apt-pkg/strutl.h>
93 #include <apt-pkg/tagfile.h>
95 #include <apr-1/apr_pools.h>
97 #include <sys/types.h>
99 #include <sys/sysctl.h>
100 #include <sys/param.h>
101 #include <sys/mount.h>
107 #include <mach-o/nlist.h>
117 #include <ext/hash_map>
119 #import "UICaboodle/BrowserView.h"
120 #import "UICaboodle/ResetView.h"
122 #import "substrate.h"
129 #define _timestamp ({ \
131 gettimeofday(&tv, NULL); \
132 tv.tv_sec * 1000000 + tv.tv_usec; \
135 typedef std::vector<class ProfileTime *> TimeList;
145 ProfileTime(const char *name) :
149 times_.push_back(this);
152 void AddTime(uint64_t time) {
159 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
171 ProfileTimer(ProfileTime &time) :
178 time_.AddTime(_timestamp - start_);
183 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
185 std::cerr << "========" << std::endl;
188 #define _profile(name) { \
189 static ProfileTime name(#name); \
190 ProfileTimer _ ## name(name);
195 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
197 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
199 void NSLogPoint(const char *fix, const CGPoint &point) {
200 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
203 void NSLogRect(const char *fix, const CGRect &rect) {
204 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
207 static _finline NSString *CydiaURL(NSString *path) {
209 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
210 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
211 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
212 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
213 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
214 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
217 /* [NSObject yieldToSelector:(withObject:)] {{{*/
218 @interface NSObject (Cydia)
219 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
220 - (id) yieldToSelector:(SEL)selector;
223 @implementation NSObject (Cydia)
228 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
229 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
230 id object([[context objectAtIndex:1] nonretainedObjectValue]);
231 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
233 /* XXX: deal with exceptions */
234 id value([self performSelector:selector withObject:object]);
236 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
237 [context removeAllObjects];
238 if ([signature methodReturnLength] != 0 && value != nil)
239 [context addObject:value];
244 performSelectorOnMainThread:@selector(doNothing)
250 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
251 /*return [self performSelector:selector withObject:object];*/
253 volatile bool stopped(false);
255 NSMutableArray *context([NSMutableArray arrayWithObjects:
256 [NSValue valueWithPointer:selector],
257 [NSValue valueWithNonretainedObject:object],
258 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
261 NSThread *thread([[[NSThread alloc]
263 selector:@selector(_yieldToContext:)
269 NSRunLoop *loop([NSRunLoop currentRunLoop]);
270 NSDate *future([NSDate distantFuture]);
272 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
274 return [context count] == 0 ? nil : [context objectAtIndex:0];
277 - (id) yieldToSelector:(SEL)selector {
278 return [self yieldToSelector:selector withObject:nil];
284 @interface CYActionSheet : UIAlertView {
288 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
291 @implementation CYActionSheet
293 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
294 if ((self = [super init])) {
295 [self setDelegate:self];
296 for (NSString *button in buttons) [self addButtonWithTitle:button];
297 [self setCancelButtonIndex:index];
301 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
302 button_ = buttonIndex + 1;
305 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
307 [self popupAlertAnimated:animated];
308 NSRunLoop *loop([NSRunLoop currentRunLoop]);
309 NSDate *future([NSDate distantFuture]);
310 while (button_ == 0 && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
316 /* NSForcedOrderingSearch doesn't work on the iPhone */
317 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
318 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
319 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
321 /* Information Dictionaries {{{ */
322 @interface NSMutableArray (Cydia)
323 - (void) addInfoDictionary:(NSDictionary *)info;
326 @implementation NSMutableArray (Cydia)
328 - (void) addInfoDictionary:(NSDictionary *)info {
329 [self addObject:info];
334 @interface NSMutableDictionary (Cydia)
335 - (void) addInfoDictionary:(NSDictionary *)info;
338 @implementation NSMutableDictionary (Cydia)
340 - (void) addInfoDictionary:(NSDictionary *)info {
341 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
346 /* Pop Transitions {{{ */
347 @interface PopTransitionView : UITransitionView {
352 @implementation PopTransitionView
354 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
355 if (from != nil && to == nil)
356 [self removeFromSuperview];
361 @implementation UIView (PopUpView)
363 - (void) popFromSuperviewAnimated:(BOOL)animated {
364 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
367 - (void) popSubview:(UIView *)view {
368 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
369 [transition setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
370 [self addSubview:transition];
372 [transition setDelegate:transition];
374 UIView *blank([[[UIView alloc] initWithFrame:[transition bounds]] autorelease]);
375 [blank setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
377 [transition transition:UITransitionNone toView:blank];
378 [transition transition:UITransitionPushFromBottom toView:view];
384 #define lprintf(args...) fprintf(stderr, args)
387 #define TraceLogging (1 && !ForRelease)
388 #define HistogramInsertionSort (0 && !ForRelease)
389 #define ProfileTimes (0 && !ForRelease)
390 #define ForSaurik (0 && !ForRelease)
391 #define LogBrowser (0 && !ForRelease)
392 #define TrackResize (0 && !ForRelease)
393 #define ManualRefresh (0 && !ForRelease)
394 #define ShowInternals (0 && !ForRelease)
395 #define IgnoreInstall (0 && !ForRelease)
396 #define RecycleWebViews 0
397 #define RecyclePackageViews (1 && ForRelease)
398 #define AlwaysReload (1 && !ForRelease)
402 #define _trace(args...)
407 #define _profile(name) {
410 #define PrintTimes() do {} while (false)
414 typedef uint32_t (*SKRadixFunction)(id, void *);
416 @interface NSMutableArray (Radix)
417 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
418 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
426 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
427 struct RadixItem_ *lhs(swap), *rhs(swap + count);
429 static const size_t width = 32;
430 static const size_t bits = 11;
431 static const size_t slots = 1 << bits;
432 static const size_t passes = (width + (bits - 1)) / bits;
434 size_t *hist(new size_t[slots]);
436 for (size_t pass(0); pass != passes; ++pass) {
437 memset(hist, 0, sizeof(size_t) * slots);
439 for (size_t i(0); i != count; ++i) {
440 uint32_t key(lhs[i].key);
442 key &= _not(uint32_t) >> width - bits;
447 for (size_t i(0); i != slots; ++i) {
448 size_t local(offset);
453 for (size_t i(0); i != count; ++i) {
454 uint32_t key(lhs[i].key);
456 key &= _not(uint32_t) >> width - bits;
457 rhs[hist[key]++] = lhs[i];
460 RadixItem_ *tmp(lhs);
467 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
468 for (size_t i(0); i != count; ++i)
469 [values addObject:[self objectAtIndex:lhs[i].index]];
470 [self setArray:values];
475 @implementation NSMutableArray (Radix)
477 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
478 size_t count([self count]);
483 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
484 [invocation setSelector:selector];
485 [invocation setArgument:&object atIndex:2];
487 /* XXX: this is an unsafe optimization of doomy hell */
488 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
489 _assert(method != NULL);
490 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
491 _assert(imp != NULL);
494 struct RadixItem_ *swap(new RadixItem_[count * 2]);
496 for (size_t i(0); i != count; ++i) {
497 RadixItem_ &item(swap[i]);
500 id object([self objectAtIndex:i]);
503 [invocation setTarget:object];
505 [invocation getReturnValue:&item.key];
507 item.key = imp(object, selector, object);
511 RadixSort_(self, count, swap);
514 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
515 size_t count([self count]);
516 struct RadixItem_ *swap(new RadixItem_[count * 2]);
518 for (size_t i(0); i != count; ++i) {
519 RadixItem_ &item(swap[i]);
522 id object([self objectAtIndex:i]);
523 item.key = function(object, argument);
526 RadixSort_(self, count, swap);
531 /* Insertion Sort {{{ */
533 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
534 const char *ptr = (const char *)list;
536 CFIndex half = count / 2;
537 const char *probe = ptr + elementSize * half;
538 CFComparisonResult cr = comparator(element, probe, context);
539 if (0 == cr) return (probe - (const char *)list) / elementSize;
540 ptr = (cr < 0) ? ptr : probe + elementSize;
541 count = (cr < 0) ? half : (half + (count & 1) - 1);
543 return (ptr - (const char *)list) / elementSize;
546 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
547 const char *ptr = (const char *)list;
549 CFIndex half = count / 2;
550 const char *probe = ptr + elementSize * half;
551 CFComparisonResult cr = comparator(element, probe, context);
552 if (0 == cr) return (probe - (const char *)list) / elementSize;
553 ptr = (cr < 0) ? ptr : probe + elementSize;
554 count = (cr < 0) ? half : (half + (count & 1) - 1);
556 return (ptr - (const char *)list) / elementSize;
559 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
560 if (range.length == 0)
562 const void **values(new const void *[range.length]);
563 CFArrayGetValues(array, range, values);
565 #if HistogramInsertionSort
566 uint32_t total(0), *offsets(new uint32_t[range.length]);
569 for (CFIndex index(1); index != range.length; ++index) {
570 const void *value(values[index]);
571 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
572 CFIndex correct(index);
573 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
576 if (correct != index) {
577 size_t offset(index - correct);
578 #if HistogramInsertionSort
582 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
584 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
585 values[correct] = value;
589 CFArrayReplaceValues(array, range, values, range.length);
592 #if HistogramInsertionSort
593 for (CFIndex index(0); index != range.length; ++index)
594 if (offsets[index] != 0)
595 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
596 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
603 /* Apple Bug Fixes {{{ */
604 @implementation UIWebDocumentView (Cydia)
606 - (void) _setScrollerOffset:(CGPoint)offset {
607 UIScroller *scroller([self _scroller]);
609 CGSize size([scroller contentSize]);
610 CGSize bounds([scroller bounds].size);
613 max.x = size.width - bounds.width;
614 max.y = size.height - bounds.height;
622 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
623 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
625 [scroller setOffset:offset];
631 NSUInteger WebScriptObject$countByEnumeratingWithState$objects$count$(WebScriptObject *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
632 size_t length([self count] - state->state);
635 else if (length > count)
637 for (size_t i(0); i != length; ++i)
638 objects[i] = [self objectAtIndex:state->state++];
639 state->itemsPtr = objects;
640 state->mutationsPtr = (unsigned long *) self;
644 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
645 size_t length([self length] - state->state);
648 else if (length > count)
650 for (size_t i(0); i != length; ++i)
651 objects[i] = [self item:state->state++];
652 state->itemsPtr = objects;
653 state->mutationsPtr = (unsigned long *) self;
657 @interface NSString (UIKit)
658 - (NSString *) stringByAddingPercentEscapes;
661 /* Cydia NSString Additions {{{ */
662 @interface NSString (Cydia)
663 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
664 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
665 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
666 - (NSComparisonResult) compareByPath:(NSString *)other;
667 - (NSString *) stringByCachingURLWithCurrentCDN;
668 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
671 @implementation NSString (Cydia)
673 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
674 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
677 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
678 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
679 memcpy(data, bytes, length);
680 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
683 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
684 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
687 - (NSComparisonResult) compareByPath:(NSString *)other {
688 NSString *prefix = [self commonPrefixWithString:other options:0];
689 size_t length = [prefix length];
691 NSRange lrange = NSMakeRange(length, [self length] - length);
692 NSRange rrange = NSMakeRange(length, [other length] - length);
694 lrange = [self rangeOfString:@"/" options:0 range:lrange];
695 rrange = [other rangeOfString:@"/" options:0 range:rrange];
697 NSComparisonResult value;
699 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
700 value = NSOrderedSame;
701 else if (lrange.location == NSNotFound)
702 value = NSOrderedAscending;
703 else if (rrange.location == NSNotFound)
704 value = NSOrderedDescending;
706 value = NSOrderedSame;
708 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
709 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
710 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
711 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
713 NSComparisonResult result = [lpath compare:rpath];
714 return result == NSOrderedSame ? value : result;
717 - (NSString *) stringByCachingURLWithCurrentCDN {
719 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
720 withString:@"://cache.cydia.saurik.com/"
724 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
725 return [(id)CFURLCreateStringByAddingPercentEscapes(
730 kCFStringEncodingUTF8
737 /* C++ NSString Wrapper Cache {{{ */
744 _finline void clear_() {
745 if (cache_ != NULL) {
752 _finline bool empty() const {
756 _finline size_t size() const {
760 _finline char *data() const {
764 _finline void clear() {
769 _finline CYString() :
776 _finline ~CYString() {
780 void operator =(const CYString &rhs) {
784 if (rhs.cache_ == nil)
787 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
790 void set(apr_pool_t *pool, const char *data, size_t size) {
796 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
797 memcpy(temp, data, size);
804 _finline void set(apr_pool_t *pool, const char *data) {
805 set(pool, data, data == NULL ? 0 : strlen(data));
808 _finline void set(apr_pool_t *pool, const std::string &rhs) {
809 set(pool, rhs.data(), rhs.size());
812 bool operator ==(const CYString &rhs) const {
813 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
816 operator CFStringRef() {
817 if (cache_ == NULL) {
820 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
822 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
826 _finline operator id() {
827 return (NSString *) static_cast<CFStringRef>(*this);
831 /* C++ NSString Algorithm Adapters {{{ */
833 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
836 struct NSStringMapHash :
837 std::unary_function<NSString *, size_t>
839 _finline size_t operator ()(NSString *value) const {
840 return CFStringHashNSString((CFStringRef) value);
844 struct NSStringMapLess :
845 std::binary_function<NSString *, NSString *, bool>
847 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
848 return [lhs compare:rhs] == NSOrderedAscending;
852 struct NSStringMapEqual :
853 std::binary_function<NSString *, NSString *, bool>
855 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
856 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
857 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
858 //[lhs isEqualToString:rhs];
863 /* Perl-Compatible RegEx {{{ */
873 Pcre(const char *regex) :
878 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
881 lprintf("%d:%s\n", offset, error);
885 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
886 matches_ = new int[(capture_ + 1) * 3];
894 NSString *operator [](size_t match) {
895 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
898 bool operator ()(NSString *data) {
899 // XXX: length is for characters, not for bytes
900 return operator ()([data UTF8String], [data length]);
903 bool operator ()(const char *data, size_t size) {
905 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
909 /* Mime Addresses {{{ */
910 @interface Address : NSObject {
916 - (NSString *) address;
918 - (void) setAddress:(NSString *)address;
920 + (Address *) addressWithString:(NSString *)string;
921 - (Address *) initWithString:(NSString *)string;
924 @implementation Address
933 - (NSString *) name {
937 - (NSString *) address {
941 - (void) setAddress:(NSString *)address {
943 [address_ autorelease];
947 address_ = [address retain];
950 + (Address *) addressWithString:(NSString *)string {
951 return [[[Address alloc] initWithString:string] autorelease];
954 + (NSArray *) _attributeKeys {
955 return [NSArray arrayWithObjects:@"address", @"name", nil];
958 - (NSArray *) attributeKeys {
959 return [[self class] _attributeKeys];
962 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
963 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
966 - (Address *) initWithString:(NSString *)string {
967 if ((self = [super init]) != nil) {
968 const char *data = [string UTF8String];
969 size_t size = [string length];
971 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
973 if (address_r(data, size)) {
974 name_ = [address_r[1] retain];
975 address_ = [address_r[2] retain];
977 name_ = [string retain];
985 /* CoreGraphics Primitives {{{ */
996 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
999 Set(space, red, green, blue, alpha);
1004 CGColorRelease(color_);
1011 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1013 float color[] = {red, green, blue, alpha};
1014 color_ = CGColorCreate(space, color);
1017 operator CGColorRef() {
1023 /* Random Global Variables {{{ */
1024 static const int PulseInterval_ = 50000;
1025 static const int ButtonBarWidth_ = 60;
1026 static const int ButtonBarHeight_ = 48;
1027 static const float KeyboardTime_ = 0.3f;
1030 static NSArray *Finishes_;
1032 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1033 #define NotifyConfig_ "/etc/notify.conf"
1035 static bool Queuing_;
1037 static CGColor Blue_;
1038 static CGColor Blueish_;
1039 static CGColor Black_;
1040 static CGColor Off_;
1041 static CGColor White_;
1042 static CGColor Gray_;
1043 static CGColor Green_;
1044 static CGColor Purple_;
1045 static CGColor Purplish_;
1047 static UIColor *InstallingColor_;
1048 static UIColor *RemovingColor_;
1050 static NSString *App_;
1051 static NSString *Home_;
1053 static BOOL Advanced_;
1054 static BOOL Ignored_;
1056 static UIFont *Font12_;
1057 static UIFont *Font12Bold_;
1058 static UIFont *Font14_;
1059 static UIFont *Font18Bold_;
1060 static UIFont *Font22Bold_;
1062 static const char *Machine_ = NULL;
1063 static const NSString *System_ = NULL;
1064 static const NSString *SerialNumber_ = nil;
1065 static const NSString *ChipID_ = nil;
1066 static const NSString *Token_ = nil;
1067 static const NSString *UniqueID_ = nil;
1068 static const NSString *Build_ = nil;
1069 static const NSString *Product_ = nil;
1070 static const NSString *Safari_ = nil;
1072 static CFLocaleRef Locale_;
1073 static NSArray *Languages_;
1074 static CGColorSpaceRef space_;
1076 static bool reload_;
1078 static NSDictionary *SectionMap_;
1079 static NSMutableDictionary *Metadata_;
1080 static _transient NSMutableDictionary *Settings_;
1081 static _transient NSString *Role_;
1082 static _transient NSMutableDictionary *Packages_;
1083 static _transient NSMutableDictionary *Sections_;
1084 static _transient NSMutableDictionary *Sources_;
1085 static bool Changed_;
1086 static NSDate *now_;
1088 static bool IsWildcat_;
1091 static NSMutableArray *Documents_;
1095 /* Display Helpers {{{ */
1096 inline float Interpolate(float begin, float end, float fraction) {
1097 return (end - begin) * fraction + begin;
1100 /* XXX: localize this! */
1101 NSString *SizeString(double size) {
1102 bool negative = size < 0;
1107 while (size > 1024) {
1112 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1114 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1117 static _finline CFStringRef CFCString(const char *value) {
1118 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1121 const char *StripVersion_(const char *version) {
1122 const char *colon(strchr(version, ':'));
1124 version = colon + 1;
1128 CFStringRef StripVersion(const char *version) {
1129 const char *colon(strchr(version, ':'));
1131 version = colon + 1;
1132 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1134 return CFCString(version);
1137 NSString *LocalizeSection(NSString *section) {
1138 static Pcre title_r("^(.*?) \\((.*)\\)$");
1139 if (title_r(section)) {
1140 NSString *parent(title_r[1]);
1141 NSString *child(title_r[2]);
1143 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1144 LocalizeSection(parent),
1145 LocalizeSection(child)
1149 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1152 NSString *Simplify(NSString *title) {
1153 const char *data = [title UTF8String];
1154 size_t size = [title length];
1156 static Pcre square_r("^\\[(.*)\\]$");
1157 if (square_r(data, size))
1158 return Simplify(square_r[1]);
1160 static Pcre paren_r("^\\((.*)\\)$");
1161 if (paren_r(data, size))
1162 return Simplify(paren_r[1]);
1164 static Pcre title_r("^(.*?) \\((.*)\\)$");
1165 if (title_r(data, size))
1166 return Simplify(title_r[1]);
1172 NSString *GetLastUpdate() {
1173 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1176 return UCLocalize("NEVER_OR_UNKNOWN");
1178 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1179 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1181 CFRelease(formatter);
1183 return [(NSString *) formatted autorelease];
1186 bool isSectionVisible(NSString *section) {
1187 NSDictionary *metadata([Sections_ objectForKey:section]);
1188 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1189 return hidden == nil || ![hidden boolValue];
1192 /* Delegate Prototypes {{{ */
1196 @interface NSObject (ProgressDelegate)
1199 @protocol ProgressDelegate
1200 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1201 - (void) setProgressTitle:(NSString *)title;
1202 - (void) setProgressPercent:(float)percent;
1203 - (void) startProgress;
1204 - (void) addProgressOutput:(NSString *)output;
1205 - (bool) isCancelling:(size_t)received;
1208 @protocol ConfigurationDelegate
1209 - (void) repairWithSelector:(SEL)selector;
1210 - (void) setConfigurationData:(NSString *)data;
1215 @protocol CydiaDelegate
1216 - (void) setPackageView:(PackageView *)view;
1217 - (void) clearPackage:(Package *)package;
1218 - (void) installPackage:(Package *)package;
1219 - (void) installPackages:(NSArray *)packages;
1220 - (void) removePackage:(Package *)package;
1221 - (void) slideUp:(UIActionSheet *)alert;
1222 - (void) distUpgrade;
1223 - (void) updateData;
1225 - (void) askForSettings;
1226 - (UIProgressHUD *) addProgressHUD;
1227 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1228 - (RVPage *) pageForPackage:(NSString *)name;
1229 - (PackageView *) packageView;
1233 /* Status Delegation {{{ */
1235 public pkgAcquireStatus
1238 _transient NSObject<ProgressDelegate> *delegate_;
1246 void setDelegate(id delegate) {
1247 delegate_ = delegate;
1250 NSObject<ProgressDelegate> *getDelegate() const {
1254 virtual bool MediaChange(std::string media, std::string drive) {
1258 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1261 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1262 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1263 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1266 virtual void Done(pkgAcquire::ItemDesc &item) {
1269 virtual void Fail(pkgAcquire::ItemDesc &item) {
1271 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1272 item.Owner->Status == pkgAcquire::Item::StatDone
1276 std::string &error(item.Owner->ErrorText);
1280 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1281 NSArray *fields([description componentsSeparatedByString:@" "]);
1282 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1284 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1285 withObject:[NSArray arrayWithObjects:
1286 [NSString stringWithUTF8String:error.c_str()],
1293 virtual bool Pulse(pkgAcquire *Owner) {
1294 bool value = pkgAcquireStatus::Pulse(Owner);
1297 double(CurrentBytes + CurrentItems) /
1298 double(TotalBytes + TotalItems)
1301 [delegate_ setProgressPercent:percent];
1302 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1305 virtual void Start() {
1306 [delegate_ startProgress];
1309 virtual void Stop() {
1313 /* Progress Delegation {{{ */
1318 _transient id<ProgressDelegate> delegate_;
1322 virtual void Update() {
1323 /*if (abs(Percent - percent_) > 2)
1324 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1328 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1329 [delegate_ setProgressPercent:(Percent / 100)];*/
1339 void setDelegate(id delegate) {
1340 delegate_ = delegate;
1343 id getDelegate() const {
1347 virtual void Done() {
1349 //[delegate_ setProgressPercent:1];
1354 /* Database Interface {{{ */
1355 typedef std::map< unsigned long, _H<Source> > SourceMap;
1357 @interface Database : NSObject {
1363 pkgCacheFile cache_;
1364 pkgDepCache::Policy *policy_;
1365 pkgRecords *records_;
1366 pkgProblemResolver *resolver_;
1367 pkgAcquire *fetcher_;
1369 SPtr<pkgPackageManager> manager_;
1370 pkgSourceList *list_;
1373 NSMutableArray *packages_;
1375 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1384 + (Database *) sharedInstance;
1387 - (void) _readCydia:(NSNumber *)fd;
1388 - (void) _readStatus:(NSNumber *)fd;
1389 - (void) _readOutput:(NSNumber *)fd;
1393 - (Package *) packageWithName:(NSString *)name;
1395 - (pkgCacheFile &) cache;
1396 - (pkgDepCache::Policy *) policy;
1397 - (pkgRecords *) records;
1398 - (pkgProblemResolver *) resolver;
1399 - (pkgAcquire &) fetcher;
1400 - (pkgSourceList &) list;
1401 - (NSArray *) packages;
1402 - (NSArray *) sources;
1403 - (void) reloadData;
1411 - (void) setVisible;
1413 - (void) updateWithStatus:(Status &)status;
1415 - (void) setDelegate:(id)delegate;
1416 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1419 /* Delegate Helpers {{{ */
1420 @implementation NSObject(ProgressDelegate)
1422 - (void) _setProgressErrorPackage:(NSArray *)args {
1423 [self performSelector:@selector(setProgressError:forPackage:)
1424 withObject:[args objectAtIndex:0]
1425 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1429 - (void) _setProgressErrorTitle:(NSArray *)args {
1430 [self performSelector:@selector(setProgressError:withTitle:)
1431 withObject:[args objectAtIndex:0]
1432 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1436 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1437 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1438 withObject:[NSArray arrayWithObjects:error, title, nil]
1443 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1444 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1445 // XXX: holy typecast batman!
1446 [(id<ProgressDelegate>)self setProgressError:error withTitle:(package == nil ? id : [package name])];
1452 /* Source Class {{{ */
1453 @interface Source : NSObject {
1454 CYString depiction_;
1455 CYString description_;
1461 CYString distribution_;
1466 NSString *authority_;
1468 CYString defaultIcon_;
1470 NSDictionary *record_;
1474 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1476 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1478 - (NSString *) depictionForPackage:(NSString *)package;
1479 - (NSString *) supportForPackage:(NSString *)package;
1481 - (NSDictionary *) record;
1485 - (NSString *) distribution;
1486 - (NSString *) type;
1488 - (NSString *) host;
1490 - (NSString *) name;
1491 - (NSString *) description;
1492 - (NSString *) label;
1493 - (NSString *) origin;
1494 - (NSString *) version;
1496 - (NSString *) defaultIcon;
1500 @implementation Source
1504 distribution_.clear();
1507 description_.clear();
1513 defaultIcon_.clear();
1515 if (record_ != nil) {
1525 if (authority_ != nil) {
1526 [authority_ release];
1536 + (NSArray *) _attributeKeys {
1537 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1540 - (NSArray *) attributeKeys {
1541 return [[self class] _attributeKeys];
1544 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1545 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1548 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1551 trusted_ = index->IsTrusted();
1553 uri_.set(pool, index->GetURI());
1554 distribution_.set(pool, index->GetDist());
1555 type_.set(pool, index->GetType());
1557 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1558 if (dindex != NULL) {
1560 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1563 pkgTagFile tags(&fd);
1565 pkgTagSection section;
1572 {"default-icon", &defaultIcon_},
1573 {"depiction", &depiction_},
1574 {"description", &description_},
1576 {"origin", &origin_},
1577 {"support", &support_},
1578 {"version", &version_},
1581 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1582 const char *start, *end;
1584 if (section.Find(names[i].name_, start, end)) {
1585 CYString &value(*names[i].value_);
1586 value.set(pool, start, end - start);
1592 record_ = [Sources_ objectForKey:[self key]];
1594 record_ = [record_ retain];
1596 NSURL *url([NSURL URLWithString:uri_]);
1600 host_ = [[host_ lowercaseString] retain];
1605 authority_ = [url path];
1607 if (authority_ != nil)
1608 authority_ = [authority_ retain];
1611 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1612 if ((self = [super init]) != nil) {
1613 [self setMetaIndex:index inPool:pool];
1617 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1618 NSDictionary *lhr = [self record];
1619 NSDictionary *rhr = [source record];
1622 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1624 NSString *lhs = [self name];
1625 NSString *rhs = [source name];
1627 if ([lhs length] != 0 && [rhs length] != 0) {
1628 unichar lhc = [lhs characterAtIndex:0];
1629 unichar rhc = [rhs characterAtIndex:0];
1631 if (isalpha(lhc) && !isalpha(rhc))
1632 return NSOrderedAscending;
1633 else if (!isalpha(lhc) && isalpha(rhc))
1634 return NSOrderedDescending;
1637 return [lhs compare:rhs options:LaxCompareOptions_];
1640 - (NSString *) depictionForPackage:(NSString *)package {
1641 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1644 - (NSString *) supportForPackage:(NSString *)package {
1645 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1648 - (NSDictionary *) record {
1656 - (NSString *) uri {
1660 - (NSString *) distribution {
1661 return distribution_;
1664 - (NSString *) type {
1668 - (NSString *) key {
1669 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1672 - (NSString *) host {
1676 - (NSString *) name {
1677 return origin_.empty() ? authority_ : origin_;
1680 - (NSString *) description {
1681 return description_;
1684 - (NSString *) label {
1685 return label_.empty() ? authority_ : label_;
1688 - (NSString *) origin {
1692 - (NSString *) version {
1696 - (NSString *) defaultIcon {
1697 return defaultIcon_;
1702 /* Relationship Class {{{ */
1703 @interface Relationship : NSObject {
1708 - (NSString *) type;
1710 - (NSString *) name;
1714 @implementation Relationship
1722 - (NSString *) type {
1730 - (NSString *) name {
1737 /* Package Class {{{ */
1738 @interface Package : NSObject {
1742 pkgCache::VerIterator version_;
1743 pkgCache::PkgIterator iterator_;
1744 _transient Database *database_;
1745 pkgCache::VerFileIterator file_;
1752 NSString *section$_;
1759 CYString installed_;
1765 CYString depiction_;
1776 NSMutableArray *tags_;
1779 NSArray *relationships_;
1781 NSMutableDictionary *metadata_;
1782 _transient NSDate *firstSeen_;
1783 _transient NSDate *lastSeen_;
1787 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1788 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1790 - (pkgCache::PkgIterator) iterator;
1793 - (NSString *) section;
1794 - (NSString *) simpleSection;
1796 - (NSString *) longSection;
1797 - (NSString *) shortSection;
1801 - (Address *) maintainer;
1803 - (NSString *) longDescription;
1804 - (NSString *) shortDescription;
1807 - (NSMutableDictionary *) metadata;
1809 - (BOOL) subscribed;
1812 - (NSString *) latest;
1813 - (NSString *) installed;
1814 - (BOOL) uninstalled;
1817 - (BOOL) upgradableAndEssential:(BOOL)essential;
1820 - (BOOL) unfiltered;
1824 - (BOOL) halfConfigured;
1825 - (BOOL) halfInstalled;
1827 - (NSString *) mode;
1829 - (void) setVisible;
1832 - (NSString *) name;
1834 - (NSString *) homepage;
1835 - (NSString *) depiction;
1836 - (Address *) author;
1838 - (NSString *) support;
1840 - (NSArray *) files;
1841 - (NSArray *) relationships;
1842 - (NSArray *) warnings;
1843 - (NSArray *) applications;
1845 - (Source *) source;
1846 - (NSString *) role;
1848 - (BOOL) matches:(NSString *)text;
1850 - (bool) hasSupportingRole;
1851 - (BOOL) hasTag:(NSString *)tag;
1852 - (NSString *) primaryPurpose;
1853 - (NSArray *) purposes;
1854 - (bool) isCommercial;
1856 - (CYString &) cyname;
1858 - (uint32_t) compareBySection:(NSArray *)sections;
1860 - (uint32_t) compareForChanges;
1865 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1866 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1867 - (bool) isInstalledAndVisible:(NSNumber *)number;
1868 - (bool) isVisibleInSection:(NSString *)section;
1869 - (bool) isVisibleInSource:(Source *)source;
1873 uint32_t PackageChangesRadix(Package *self, void *) {
1878 uint32_t timestamp : 30;
1879 uint32_t ignored : 1;
1880 uint32_t upgradable : 1;
1884 bool upgradable([self upgradableAndEssential:YES]);
1885 value.bits.upgradable = upgradable ? 1 : 0;
1888 value.bits.timestamp = 0;
1889 value.bits.ignored = [self ignored] ? 0 : 1;
1890 value.bits.upgradable = 1;
1892 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1893 value.bits.ignored = 0;
1894 value.bits.upgradable = 0;
1897 return _not(uint32_t) - value.key;
1900 _finline static void Stifle(uint8_t &value) {
1903 uint32_t PackagePrefixRadix(Package *self, void *context) {
1904 size_t offset(reinterpret_cast<size_t>(context));
1905 CYString &name([self cyname]);
1907 size_t size(name.size());
1910 char *text(name.data());
1913 if (!isdigit(text[0]))
1917 while (size != digits && isdigit(text[digits]))
1927 if (offset == 0 && zeros != 0) {
1928 memset(data, '0', zeros);
1929 memcpy(data + zeros, text, 4 - zeros);
1931 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1932 if (size <= offset - zeros)
1935 text += offset - zeros;
1936 size -= offset - zeros;
1939 memcpy(data, text, 4);
1941 memcpy(data, text, size);
1942 memset(data + size, 0, 4 - size);
1945 for (size_t i(0); i != 4; ++i)
1946 if (isalpha(data[i]))
1951 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1953 /* XXX: ntohl may be more honest */
1954 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1957 CYString &(*PackageName)(Package *self, SEL sel);
1959 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1960 _profile(PackageNameCompare)
1961 CYString &lhi(PackageName(lhs, @selector(cyname)));
1962 CYString &rhi(PackageName(rhs, @selector(cyname)));
1963 CFStringRef lhn(lhi), rhn(rhi);
1966 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1967 else if (rhn == NULL)
1968 return NSOrderedDescending;
1970 _profile(PackageNameCompare$NumbersLast)
1971 if (!lhi.empty() && !rhi.empty()) {
1972 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1973 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1974 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1975 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1976 return lha ? NSOrderedAscending : NSOrderedDescending;
1980 CFIndex length = CFStringGetLength(lhn);
1982 _profile(PackageNameCompare$Compare)
1983 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1988 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1989 return PackageNameCompare(*lhs, *rhs, context);
1992 struct PackageNameOrdering :
1993 std::binary_function<Package *, Package *, bool>
1995 _finline bool operator ()(Package *lhs, Package *rhs) const {
1996 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2000 @implementation Package
2002 - (NSString *) description {
2003 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2009 if (section$_ != nil)
2010 [section$_ release];
2015 if (sponsor$_ != nil)
2016 [sponsor$_ release];
2017 if (author$_ != nil)
2024 if (relationships_ != nil)
2025 [relationships_ release];
2026 if (metadata_ != nil)
2027 [metadata_ release];
2032 + (NSString *) webScriptNameForSelector:(SEL)selector {
2033 if (selector == @selector(hasTag:))
2039 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2040 return [self webScriptNameForSelector:selector] == nil;
2043 + (NSArray *) _attributeKeys {
2044 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];
2047 - (NSArray *) attributeKeys {
2048 return [[self class] _attributeKeys];
2051 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2052 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2062 _profile(Package$parse)
2063 pkgRecords::Parser *parser;
2065 _profile(Package$parse$Lookup)
2066 parser = &[database_ records]->Lookup(file_);
2071 _profile(Package$parse$Find)
2077 {"depiction", &depiction_},
2078 {"homepage", &homepage_},
2079 {"website", &website},
2081 {"support", &support_},
2082 {"sponsor", &sponsor_},
2083 {"author", &author_},
2086 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2087 const char *start, *end;
2089 if (parser->Find(names[i].name_, start, end)) {
2090 CYString &value(*names[i].value_);
2091 _profile(Package$parse$Value)
2092 value.set(pool_, start, end - start);
2098 _profile(Package$parse$Tagline)
2099 const char *start, *end;
2100 if (parser->ShortDesc(start, end)) {
2101 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2104 while (stop != start && stop[-1] == '\r')
2106 tagline_.set(pool_, start, stop - start);
2110 _profile(Package$parse$Retain)
2111 if (homepage_.empty())
2112 homepage_ = website;
2113 if (homepage_ == depiction_)
2119 - (void) setVisible {
2120 visible_ = required_ && [self unfiltered];
2123 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2124 if ((self = [super init]) != nil) {
2125 _profile(Package$initWithVersion)
2126 @synchronized (database) {
2127 era_ = [database era];
2131 iterator_ = version.ParentPkg();
2132 database_ = database;
2134 _profile(Package$initWithVersion$Latest)
2135 latest_ = (NSString *) StripVersion(version_.VerStr());
2138 pkgCache::VerIterator current;
2139 _profile(Package$initWithVersion$Versions)
2140 current = iterator_.CurrentVer();
2142 installed_.set(pool_, StripVersion_(current.VerStr()));
2144 if (!version_.end())
2145 file_ = version_.FileList();
2147 pkgCache &cache([database_ cache]);
2148 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2152 _profile(Package$initWithVersion$Name)
2153 id_.set(pool_, iterator_.Name());
2154 name_.set(pool, iterator_.Display());
2158 _profile(Package$initWithVersion$Source)
2159 source_ = [database_ getSource:file_.File()];
2168 _profile(Package$initWithVersion$Tags)
2169 pkgCache::TagIterator tag(iterator_.TagList());
2171 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2173 const char *name(tag.Name());
2174 [tags_ addObject:(NSString *)CFCString(name)];
2175 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2176 role_ = (NSString *) CFCString(name + 6);
2177 if (required_ && strncmp(name, "require::", 9) == 0 && (
2182 } while (!tag.end());
2186 bool changed(false);
2187 NSString *key([id_ lowercaseString]);
2189 _profile(Package$initWithVersion$Metadata)
2190 metadata_ = [Packages_ objectForKey:key];
2192 if (metadata_ == nil) {
2195 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2196 firstSeen_, @"FirstSeen",
2197 latest_, @"LastVersion",
2202 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2203 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2205 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2206 subscribed_ = [subscribed boolValue];
2208 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2210 if (firstSeen_ == nil) {
2211 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2212 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2216 if (version == nil) {
2217 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2219 } else if (![version isEqualToString:latest_]) {
2220 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2222 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2227 metadata_ = [metadata_ retain];
2230 [Packages_ setObject:metadata_ forKey:key];
2235 _profile(Package$initWithVersion$Section)
2236 section_.set(pool_, iterator_.Section());
2239 obsolete_ = [self hasTag:@"cydia::obsolete"];
2240 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2242 } _end } return self;
2245 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2246 @synchronized ([Database class]) {
2247 pkgCache::VerIterator version;
2249 _profile(Package$packageWithIterator$GetCandidateVer)
2250 version = [database policy]->GetCandidateVer(iterator);
2256 return [[[Package alloc]
2257 initWithVersion:version
2264 - (pkgCache::PkgIterator) iterator {
2268 - (NSString *) section {
2269 if (section$_ == nil) {
2270 if (section_.empty())
2273 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2274 NSString *name(section_);
2277 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2278 if (NSString *rename = [value objectForKey:@"Rename"]) {
2283 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2287 - (NSString *) simpleSection {
2288 if (NSString *section = [self section])
2289 return Simplify(section);
2294 - (NSString *) longSection {
2295 return LocalizeSection([self section]);
2298 - (NSString *) shortSection {
2299 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2302 - (NSString *) uri {
2305 pkgIndexFile *index;
2306 pkgCache::PkgFileIterator file(file_.File());
2307 if (![database_ list].FindIndex(file, index))
2309 return [NSString stringWithUTF8String:iterator_->Path];
2310 //return [NSString stringWithUTF8String:file.Site()];
2311 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2315 - (Address *) maintainer {
2318 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2319 const std::string &maintainer(parser->Maintainer());
2320 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2324 return version_.end() ? 0 : version_->InstalledSize;
2327 - (NSString *) longDescription {
2330 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2331 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2333 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2334 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2335 if ([lines count] < 2)
2338 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2339 for (size_t i(1), e([lines count]); i != e; ++i) {
2340 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2341 [trimmed addObject:trim];
2344 return [trimmed componentsJoinedByString:@"\n"];
2347 - (NSString *) shortDescription {
2352 _profile(Package$index)
2353 CFStringRef name((CFStringRef) [self name]);
2354 if (CFStringGetLength(name) == 0)
2356 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2357 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2359 return toupper(character);
2363 - (NSMutableDictionary *) metadata {
2368 if (subscribed_ && lastSeen_ != nil)
2373 - (BOOL) subscribed {
2378 NSDictionary *metadata([self metadata]);
2379 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2380 return [ignored boolValue];
2385 - (NSString *) latest {
2389 - (NSString *) installed {
2393 - (BOOL) uninstalled {
2394 return installed_.empty();
2398 return !version_.end();
2401 - (BOOL) upgradableAndEssential:(BOOL)essential {
2402 _profile(Package$upgradableAndEssential)
2403 pkgCache::VerIterator current(iterator_.CurrentVer());
2405 return essential && essential_ && visible_;
2407 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2411 - (BOOL) essential {
2416 return [database_ cache][iterator_].InstBroken();
2419 - (BOOL) unfiltered {
2420 NSString *section([self section]);
2421 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2429 unsigned char current(iterator_->CurrentState);
2430 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2433 - (BOOL) halfConfigured {
2434 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2437 - (BOOL) halfInstalled {
2438 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2442 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2443 return state.Mode != pkgDepCache::ModeKeep;
2446 - (NSString *) mode {
2447 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2449 switch (state.Mode) {
2450 case pkgDepCache::ModeDelete:
2451 if ((state.iFlags & pkgDepCache::Purge) != 0)
2455 case pkgDepCache::ModeKeep:
2456 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2457 return @"REINSTALL";
2458 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2462 case pkgDepCache::ModeInstall:
2463 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2464 return @"REINSTALL";
2465 else*/ switch (state.Status) {
2467 return @"DOWNGRADE";
2473 return @"NEW_INSTALL";
2484 - (NSString *) name {
2485 return name_.empty() ? id_ : name_;
2488 - (UIImage *) icon {
2489 NSString *section = [self simpleSection];
2493 if ([icon_ hasPrefix:@"file:///"])
2494 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2495 if (icon == nil) if (section != nil)
2496 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2497 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2498 if ([dicon hasPrefix:@"file:///"])
2499 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2501 icon = [UIImage applicationImageNamed:@"unknown.png"];
2505 - (NSString *) homepage {
2509 - (NSString *) depiction {
2510 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2513 - (Address *) sponsor {
2514 if (sponsor$_ == nil) {
2515 if (sponsor_.empty())
2517 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2521 - (Address *) author {
2522 if (author$_ == nil) {
2523 if (author_.empty())
2525 author$_ = [[Address addressWithString:author_] retain];
2529 - (NSString *) support {
2530 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2533 - (NSArray *) files {
2534 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2535 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2538 fin.open([path UTF8String]);
2543 while (std::getline(fin, line))
2544 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2549 - (NSArray *) relationships {
2550 return relationships_;
2553 - (NSArray *) warnings {
2554 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2555 const char *name(iterator_.Name());
2557 size_t length(strlen(name));
2558 if (length < 2) invalid:
2559 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2560 else for (size_t i(0); i != length; ++i)
2562 /* XXX: technically this is not allowed */
2563 (name[i] < 'A' || name[i] > 'Z') &&
2564 (name[i] < 'a' || name[i] > 'z') &&
2565 (name[i] < '0' || name[i] > '9') &&
2566 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2569 if (strcmp(name, "cydia") != 0) {
2572 bool _private = false;
2575 bool repository = [[self section] isEqualToString:@"Repositories"];
2577 if (NSArray *files = [self files])
2578 for (NSString *file in files)
2579 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2581 else if (!user && [file isEqualToString:@"/User"])
2583 else if (!_private && [file isEqualToString:@"/private"])
2585 else if (!stash && [file isEqualToString:@"/var/stash"])
2588 /* XXX: this is not sensitive enough. only some folders are valid. */
2589 if (cydia && !repository)
2590 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2592 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2594 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2596 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2599 return [warnings count] == 0 ? nil : warnings;
2602 - (NSArray *) applications {
2603 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2605 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2607 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2608 if (NSArray *files = [self files])
2609 for (NSString *file in files)
2610 if (application_r(file)) {
2611 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2612 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2613 if ([id isEqualToString:me])
2616 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2618 display = application_r[1];
2620 NSString *bundle([file stringByDeletingLastPathComponent]);
2621 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2622 if (icon == nil || [icon length] == 0)
2624 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2626 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2627 [applications addObject:application];
2629 [application addObject:id];
2630 [application addObject:display];
2631 [application addObject:url];
2634 return [applications count] == 0 ? nil : applications;
2637 - (Source *) source {
2639 @synchronized (database_) {
2640 if ([database_ era] != era_ || file_.end())
2643 source_ = [database_ getSource:file_.File()];
2655 - (NSString *) role {
2659 - (BOOL) matches:(NSString *)text {
2665 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2666 if (range.location != NSNotFound)
2669 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2670 if (range.location != NSNotFound)
2673 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2674 if (range.location != NSNotFound)
2680 - (bool) hasSupportingRole {
2683 if ([role_ isEqualToString:@"enduser"])
2685 if ([Role_ isEqualToString:@"User"])
2687 if ([role_ isEqualToString:@"hacker"])
2689 if ([Role_ isEqualToString:@"Hacker"])
2691 if ([role_ isEqualToString:@"developer"])
2693 if ([Role_ isEqualToString:@"Developer"])
2698 - (BOOL) hasTag:(NSString *)tag {
2699 return tags_ == nil ? NO : [tags_ containsObject:tag];
2702 - (NSString *) primaryPurpose {
2703 for (NSString *tag in tags_)
2704 if ([tag hasPrefix:@"purpose::"])
2705 return [tag substringFromIndex:9];
2709 - (NSArray *) purposes {
2710 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2711 for (NSString *tag in tags_)
2712 if ([tag hasPrefix:@"purpose::"])
2713 [purposes addObject:[tag substringFromIndex:9]];
2714 return [purposes count] == 0 ? nil : purposes;
2717 - (bool) isCommercial {
2718 return [self hasTag:@"cydia::commercial"];
2721 - (CYString &) cyname {
2722 return name_.empty() ? id_ : name_;
2725 - (uint32_t) compareBySection:(NSArray *)sections {
2726 NSString *section([self section]);
2727 for (size_t i(0), e([sections count]); i != e; ++i) {
2728 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2732 return _not(uint32_t);
2735 - (uint32_t) compareForChanges {
2740 uint32_t timestamp : 30;
2741 uint32_t ignored : 1;
2742 uint32_t upgradable : 1;
2746 bool upgradable([self upgradableAndEssential:YES]);
2747 value.bits.upgradable = upgradable ? 1 : 0;
2750 value.bits.timestamp = 0;
2751 value.bits.ignored = [self ignored] ? 0 : 1;
2752 value.bits.upgradable = 1;
2754 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2755 value.bits.ignored = 0;
2756 value.bits.upgradable = 0;
2759 return _not(uint32_t) - value.key;
2763 pkgProblemResolver *resolver = [database_ resolver];
2764 resolver->Clear(iterator_);
2765 resolver->Protect(iterator_);
2769 pkgProblemResolver *resolver = [database_ resolver];
2770 resolver->Clear(iterator_);
2771 resolver->Protect(iterator_);
2772 pkgCacheFile &cache([database_ cache]);
2773 cache->MarkInstall(iterator_, false);
2774 pkgDepCache::StateCache &state((*cache)[iterator_]);
2775 if (!state.Install())
2776 cache->SetReInstall(iterator_, true);
2780 pkgProblemResolver *resolver = [database_ resolver];
2781 resolver->Clear(iterator_);
2782 resolver->Protect(iterator_);
2783 resolver->Remove(iterator_);
2784 [database_ cache]->MarkDelete(iterator_, true);
2787 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2788 _profile(Package$isUnfilteredAndSearchedForBy)
2791 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2792 value &= [self unfiltered];
2795 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2796 value &= [self matches:search];
2803 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2804 if ([search length] == 0)
2807 _profile(Package$isUnfilteredAndSelectedForBy)
2810 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2811 value &= [self unfiltered];
2814 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2815 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2822 - (bool) isInstalledAndVisible:(NSNumber *)number {
2823 return (![number boolValue] || [self visible]) && ![self uninstalled];
2826 - (bool) isVisibleInSection:(NSString *)name {
2827 NSString *section = [self section];
2832 section == nil && [name length] == 0 ||
2833 [name isEqualToString:section]
2837 - (bool) isVisibleInSource:(Source *)source {
2838 return [self source] == source && [self visible];
2843 /* Section Class {{{ */
2844 @interface Section : NSObject {
2849 NSString *localized_;
2852 - (NSComparisonResult) compareByLocalized:(Section *)section;
2853 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2854 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2855 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2856 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2857 - (NSString *) name;
2864 - (void) addToCount;
2866 - (void) setCount:(size_t)count;
2867 - (NSString *) localized;
2871 @implementation Section
2875 if (localized_ != nil)
2876 [localized_ release];
2880 - (NSComparisonResult) compareByLocalized:(Section *)section {
2881 NSString *lhs(localized_);
2882 NSString *rhs([section localized]);
2884 /*if ([lhs length] != 0 && [rhs length] != 0) {
2885 unichar lhc = [lhs characterAtIndex:0];
2886 unichar rhc = [rhs characterAtIndex:0];
2888 if (isalpha(lhc) && !isalpha(rhc))
2889 return NSOrderedAscending;
2890 else if (!isalpha(lhc) && isalpha(rhc))
2891 return NSOrderedDescending;
2894 return [lhs compare:rhs options:LaxCompareOptions_];
2897 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2898 if ((self = [self initWithName:name localize:NO]) != nil) {
2899 if (localized != nil)
2900 localized_ = [localized retain];
2904 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2905 return [self initWithName:name row:0 localize:localize];
2908 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2909 if ((self = [super init]) != nil) {
2910 name_ = [name retain];
2914 localized_ = [LocalizeSection(name_) retain];
2918 /* XXX: localize the index thingees */
2919 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2920 if ((self = [super init]) != nil) {
2921 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2927 - (NSString *) name {
2947 - (void) addToCount {
2951 - (void) setCount:(size_t)count {
2955 - (NSString *) localized {
2962 static NSString *Colon_;
2963 static NSString *Error_;
2964 static NSString *Warning_;
2966 /* Database Implementation {{{ */
2967 @implementation Database
2969 + (Database *) sharedInstance {
2970 static Database *instance;
2971 if (instance == nil)
2972 instance = [[Database alloc] init];
2982 NSRecycleZone(zone_);
2983 // XXX: malloc_destroy_zone(zone_);
2984 apr_pool_destroy(pool_);
2988 - (void) _readCydia:(NSNumber *)fd { _pooled
2989 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2990 std::istream is(&ib);
2993 static Pcre finish_r("^finish:([^:]*)$");
2995 while (std::getline(is, line)) {
2996 const char *data(line.c_str());
2997 size_t size = line.size();
2998 lprintf("C:%s\n", data);
3000 if (finish_r(data, size)) {
3001 NSString *finish = finish_r[1];
3002 int index = [Finishes_ indexOfObject:finish];
3003 if (index != INT_MAX && index > Finish_)
3011 - (void) _readStatus:(NSNumber *)fd { _pooled
3012 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3013 std::istream is(&ib);
3016 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3017 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3019 while (std::getline(is, line)) {
3020 const char *data(line.c_str());
3021 size_t size(line.size());
3022 lprintf("S:%s\n", data);
3024 if (conffile_r(data, size)) {
3025 [delegate_ setConfigurationData:conffile_r[1]];
3026 } else if (strncmp(data, "status: ", 8) == 0) {
3027 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3028 [delegate_ setProgressTitle:string];
3029 } else if (pmstatus_r(data, size)) {
3030 std::string type([pmstatus_r[1] UTF8String]);
3031 NSString *id = pmstatus_r[2];
3033 float percent([pmstatus_r[3] floatValue]);
3034 [delegate_ setProgressPercent:(percent / 100)];
3036 NSString *string = pmstatus_r[4];
3038 if (type == "pmerror")
3039 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3040 withObject:[NSArray arrayWithObjects:string, id, nil]
3043 else if (type == "pmstatus") {
3044 [delegate_ setProgressTitle:string];
3045 } else if (type == "pmconffile")
3046 [delegate_ setConfigurationData:string];
3048 lprintf("E:unknown pmstatus\n");
3050 lprintf("E:unknown status\n");
3056 - (void) _readOutput:(NSNumber *)fd { _pooled
3057 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3058 std::istream is(&ib);
3061 while (std::getline(is, line)) {
3062 lprintf("O:%s\n", line.c_str());
3063 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3073 - (Package *) packageWithName:(NSString *)name {
3074 @synchronized ([Database class]) {
3075 if (static_cast<pkgDepCache *>(cache_) == NULL)
3077 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3078 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3081 - (Database *) init {
3082 if ((self = [super init]) != nil) {
3089 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3090 apr_pool_create(&pool_, NULL);
3092 packages_ = [[NSMutableArray alloc] init];
3096 _assert(pipe(fds) != -1);
3099 _config->Set("APT::Keep-Fds::", cydiafd_);
3100 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3103 detachNewThreadSelector:@selector(_readCydia:)
3105 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3108 _assert(pipe(fds) != -1);
3112 detachNewThreadSelector:@selector(_readStatus:)
3114 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3117 _assert(pipe(fds) != -1);
3118 _assert(dup2(fds[0], 0) != -1);
3119 _assert(close(fds[0]) != -1);
3121 input_ = fdopen(fds[1], "a");
3123 _assert(pipe(fds) != -1);
3124 _assert(dup2(fds[1], 1) != -1);
3125 _assert(close(fds[1]) != -1);
3128 detachNewThreadSelector:@selector(_readOutput:)
3130 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3135 - (pkgCacheFile &) cache {
3139 - (pkgDepCache::Policy *) policy {
3143 - (pkgRecords *) records {
3147 - (pkgProblemResolver *) resolver {
3151 - (pkgAcquire &) fetcher {
3155 - (pkgSourceList &) list {
3159 - (NSArray *) packages {
3163 - (NSArray *) sources {
3164 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3165 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3166 [sources addObject:i->second];
3170 - (NSArray *) issues {
3171 if (cache_->BrokenCount() == 0)
3174 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3176 for (Package *package in packages_) {
3177 if (![package broken])
3179 pkgCache::PkgIterator pkg([package iterator]);
3181 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3182 [entry addObject:[package name]];
3183 [issues addObject:entry];
3185 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3189 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3190 pkgCache::DepIterator start;
3191 pkgCache::DepIterator end;
3192 dep.GlobOr(start, end); // ++dep
3194 if (!cache_->IsImportantDep(end))
3196 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3199 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3200 [entry addObject:failure];
3201 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3203 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3204 if (Package *package = [self packageWithName:name])
3205 name = [package name];
3206 [failure addObject:name];
3208 pkgCache::PkgIterator target(start.TargetPkg());
3209 if (target->ProvidesList != 0)
3210 [failure addObject:@"?"];
3212 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3214 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3215 else if (!cache_[target].CandidateVerIter(cache_).end())
3216 [failure addObject:@"-"];
3217 else if (target->ProvidesList == 0)
3218 [failure addObject:@"!"];
3220 [failure addObject:@"%"];
3224 if (start.TargetVer() != 0)
3225 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3236 - (bool) popErrorWithTitle:(NSString *)title {
3238 std::string message;
3240 while (!_error->empty()) {
3242 bool warning(!_error->PopMessage(error));
3246 size_t size(error.size());
3247 if (size == 0 || error[size - 1] != '\n')
3249 error.resize(size - 1);
3251 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3253 if (!message.empty())
3258 if (fatal && !message.empty())
3259 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3264 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3265 return [self popErrorWithTitle:title] || !success;
3268 - (void) reloadData { _pooled
3269 @synchronized ([Database class]) {
3270 @synchronized (self) {
3274 [packages_ removeAllObjects];
3300 apr_pool_clear(pool_);
3301 NSRecycleZone(zone_);
3303 int chk(creat("/tmp/cydia.chk", 0644));
3307 NSString *title(UCLocalize("DATABASE"));
3310 if (!cache_.Open(progress_, true)) { pop:
3312 bool warning(!_error->PopMessage(error));
3313 lprintf("cache_.Open():[%s]\n", error.c_str());
3315 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3316 [delegate_ repairWithSelector:@selector(configure)];
3317 else if (error == "The package lists or status file could not be parsed or opened.")
3318 [delegate_ repairWithSelector:@selector(update)];
3319 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3320 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3321 // else if (error == "The list of sources could not be read.")
3323 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3332 unlink("/tmp/cydia.chk");
3334 now_ = [[NSDate date] retain];
3336 policy_ = new pkgDepCache::Policy();
3337 records_ = new pkgRecords(cache_);
3338 resolver_ = new pkgProblemResolver(cache_);
3339 fetcher_ = new pkgAcquire(&status_);
3342 list_ = new pkgSourceList();
3343 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3346 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3347 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3351 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3354 if (cache_->BrokenCount() != 0) {
3355 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3358 if (cache_->BrokenCount() != 0) {
3359 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3363 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3369 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3370 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3371 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3372 // XXX: this could be more intelligent
3373 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3374 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3376 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3383 /*std::vector<Package *> packages;
3384 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3385 [packages_ release];
3390 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3391 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3392 //packages.push_back(package);
3393 [packages_ addObject:package];
3397 /*if (packages.empty())
3398 packages_ = [[NSArray alloc] init];
3400 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3403 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3404 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3405 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3413 /*if (!packages.empty())
3414 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3415 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3417 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3419 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3421 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3427 - (void) configure {
3428 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3429 system([dpkg UTF8String]);
3433 // XXX: I don't remember this condition
3438 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3440 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3442 if ([self popErrorWithTitle:title])
3446 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3449 public pkgArchiveCleaner
3452 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3457 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3464 fetcher_->Shutdown();
3466 pkgRecords records(cache_);
3468 lock_ = new FileFd();
3469 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3471 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3473 if ([self popErrorWithTitle:title])
3477 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3480 manager_ = (_system->CreatePM(cache_));
3481 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3488 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3490 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3492 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3494 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3495 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3498 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3503 bool failed = false;
3504 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3505 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3507 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3510 std::string uri = (*item)->DescURI();
3511 std::string error = (*item)->ErrorText;
3513 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3516 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3517 withObject:[NSArray arrayWithObjects:
3518 [NSString stringWithUTF8String:error.c_str()],
3530 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3532 if (_error->PendingError()) {
3537 if (result == pkgPackageManager::Failed) {
3542 if (result != pkgPackageManager::Completed) {
3547 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3549 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3551 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3552 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3555 if (![before isEqualToArray:after])
3560 NSString *title(UCLocalize("UPGRADE"));
3561 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3567 [self updateWithStatus:status_];
3570 - (void) setVisible {
3571 for (Package *package in packages_)
3572 [package setVisible];
3575 - (void) updateWithStatus:(Status &)status {
3576 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3577 NSString *title(UCLocalize("REFRESHING_DATA"));
3580 if (!list.ReadMainList())
3581 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3584 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3585 if ([self popErrorWithTitle:title])
3588 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3589 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
3591 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3595 - (void) setDelegate:(id)delegate {
3596 delegate_ = delegate;
3597 status_.setDelegate(delegate);
3598 progress_.setDelegate(delegate);
3601 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3602 SourceMap::const_iterator i(sources_.find(file->ID));
3603 return i == sources_.end() ? nil : i->second;
3609 /* Confirmation View {{{ */
3610 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3611 if (!iterator.end())
3612 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3613 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3615 pkgCache::PkgIterator package(dep.TargetPkg());
3618 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3625 /* Web Scripting {{{ */
3626 @interface CydiaObject : NSObject {
3631 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3634 @implementation CydiaObject
3637 [indirect_ release];
3641 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3642 if ((self = [super init]) != nil) {
3643 indirect_ = [indirect retain];
3647 - (void) setDelegate:(id)delegate {
3648 delegate_ = delegate;
3651 + (NSArray *) _attributeKeys {
3652 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3655 - (NSArray *) attributeKeys {
3656 return [[self class] _attributeKeys];
3659 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3660 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3663 - (NSString *) device {
3664 return [[UIDevice currentDevice] uniqueIdentifier];
3667 #if 0 // XXX: implement!
3668 - (NSString *) mac {
3669 if (![indirect_ promptForSensitive:@"Mac Address"])
3673 - (NSString *) serial {
3674 if (![indirect_ promptForSensitive:@"Serial #"])
3678 - (NSString *) firewire {
3679 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3683 - (NSString *) imei {
3684 if (![indirect_ promptForSensitive:@"IMEI"])
3689 + (NSString *) webScriptNameForSelector:(SEL)selector {
3690 if (selector == @selector(close))
3692 else if (selector == @selector(getInstalledPackages))
3693 return @"getInstalledPackages";
3694 else if (selector == @selector(getPackageById:))
3695 return @"getPackageById";
3696 else if (selector == @selector(installPackages:))
3697 return @"installPackages";
3698 else if (selector == @selector(setAutoPopup:))
3699 return @"setAutoPopup";
3700 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3701 return @"setButtonImage";
3702 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3703 return @"setButtonTitle";
3704 else if (selector == @selector(setFinishHook:))
3705 return @"setFinishHook";
3706 else if (selector == @selector(setPopupHook:))
3707 return @"setPopupHook";
3708 else if (selector == @selector(setSpecial:))
3709 return @"setSpecial";
3710 else if (selector == @selector(setToken:))
3712 else if (selector == @selector(setViewportWidth:))
3713 return @"setViewportWidth";
3714 else if (selector == @selector(supports:))
3716 else if (selector == @selector(stringWithFormat:arguments:))
3718 else if (selector == @selector(localizedStringForKey:value:table:))
3720 else if (selector == @selector(du:))
3722 else if (selector == @selector(statfs:))
3728 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3729 return [self webScriptNameForSelector:selector] == nil;
3732 - (BOOL) supports:(NSString *)feature {
3733 return [feature isEqualToString:@"window.open"];
3736 - (NSArray *) getInstalledPackages {
3737 NSArray *packages([[Database sharedInstance] packages]);
3738 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3739 for (Package *package in packages)
3740 if ([package installed] != nil)
3741 [installed addObject:package];
3745 - (Package *) getPackageById:(NSString *)id {
3746 Package *package([[Database sharedInstance] packageWithName:id]);
3751 - (NSArray *) statfs:(NSString *)path {
3754 if (path == nil || statfs([path UTF8String], &stat) == -1)
3757 return [NSArray arrayWithObjects:
3758 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3759 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3760 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3764 - (NSNumber *) du:(NSString *)path {
3765 NSNumber *value(nil);
3768 _assert(pipe(fds) != -1);
3770 pid_t pid(ExecFork());
3772 _assert(dup2(fds[1], 1) != -1);
3773 _assert(close(fds[0]) != -1);
3774 _assert(close(fds[1]) != -1);
3775 /* XXX: this should probably not use du */
3776 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3781 _assert(close(fds[1]) != -1);
3783 if (FILE *du = fdopen(fds[0], "r")) {
3785 while (fgets(line, sizeof(line), du) != NULL) {
3786 size_t length(strlen(line));
3787 while (length != 0 && line[length - 1] == '\n')
3788 line[--length] = '\0';
3789 if (char *tab = strchr(line, '\t')) {
3791 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3796 } else _assert(close(fds[0]));
3800 if (waitpid(pid, &status, 0) == -1)
3803 else _assert(false);
3812 - (void) installPackages:(NSArray *)packages {
3813 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3816 - (void) setAutoPopup:(BOOL)popup {
3817 [indirect_ setAutoPopup:popup];
3820 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3821 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3824 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3825 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3828 - (void) setSpecial:(id)function {
3829 [indirect_ setSpecial:function];
3832 - (void) setToken:(NSString *)token {
3835 Token_ = [token retain];
3837 [Metadata_ setObject:Token_ forKey:@"Token"];
3841 - (void) setFinishHook:(id)function {
3842 [indirect_ setFinishHook:function];
3845 - (void) setPopupHook:(id)function {
3846 [indirect_ setPopupHook:function];
3849 - (void) setViewportWidth:(float)width {
3850 [indirect_ setViewportWidth:width];
3853 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3854 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3855 unsigned count([arguments count]);
3857 for (unsigned i(0); i != count; ++i)
3858 values[i] = [arguments objectAtIndex:i];
3859 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3862 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3863 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3865 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3867 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3873 @interface CydiaBrowserView : BrowserView {
3874 CydiaObject *cydia_;
3879 @implementation CydiaBrowserView
3886 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3889 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3890 [super webView:sender didClearWindowObject:window forFrame:frame];
3892 WebDataSource *source([frame dataSource]);
3893 NSURLResponse *response([source response]);
3894 NSURL *url([response URL]);
3895 NSString *scheme([url scheme]);
3897 NSHTTPURLResponse *http;
3898 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3899 http = (NSHTTPURLResponse *) response;
3903 NSDictionary *headers([http allHeaderFields]);
3904 NSString *host([url host]);
3905 [self setHeaders:headers forHost:host];
3908 [host isEqualToString:@"cydia.saurik.com"] ||
3909 [host hasSuffix:@".cydia.saurik.com"] ||
3910 [scheme isEqualToString:@"file"]
3912 [window setValue:cydia_ forKey:@"cydia"];
3915 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3916 if (System_ != NULL)
3917 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3918 if (Machine_ != NULL)
3919 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3921 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3923 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3926 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3927 NSMutableURLRequest *copy = [request mutableCopy];
3928 [self _setMoreHeaders:copy];
3932 - (void) setDelegate:(id)delegate {
3933 [super setDelegate:delegate];
3934 [cydia_ setDelegate:delegate];
3937 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3938 if ((self = [super initWithBook:book forWidth:width ofClass:[CydiaBrowserView class]]) != nil) {
3939 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3941 WebView *webview([document_ webView]);
3943 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3945 NSString *application = package == nil ? @"Cydia" : [NSString
3946 stringWithFormat:@"Cydia/%@",
3951 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3953 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3954 if (Product_ != nil)
3955 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3957 [webview setApplicationNameForUserAgent:application];
3963 @protocol ConfirmationViewDelegate
3969 @interface ConfirmationView : CydiaBrowserView {
3970 _transient Database *database_;
3971 UIAlertView *essential_;
3978 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3982 @implementation ConfirmationView
3989 if (essential_ != nil)
3990 [essential_ release];
3996 [book_ popFromSuperviewAnimated:YES];
3999 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4000 NSString *context([alert context]);
4002 if ([context isEqualToString:@"remove"]) {
4003 if (button == [alert cancelButtonIndex]) {
4005 } else if (button == [alert firstOtherButtonIndex]) {
4008 [delegate_ confirm];
4011 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4012 } else if ([context isEqualToString:@"unable"]) {
4014 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4016 [super alertView:alert clickedButtonAtIndex:button];
4020 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4021 [super webView:sender didClearWindowObject:window forFrame:frame];
4022 [window setValue:changes_ forKey:@"changes"];
4023 [window setValue:issues_ forKey:@"issues"];
4024 [window setValue:sizes_ forKey:@"sizes"];
4027 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4028 if ((self = [super initWithBook:book]) != nil) {
4029 database_ = database;
4031 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4032 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4033 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4034 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4035 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4039 pkgDepCache::Policy *policy([database_ policy]);
4041 pkgCacheFile &cache([database_ cache]);
4042 NSArray *packages = [database_ packages];
4043 for (Package *package in packages) {
4044 pkgCache::PkgIterator iterator = [package iterator];
4045 pkgDepCache::StateCache &state(cache[iterator]);
4047 NSString *name([package name]);
4049 if (state.NewInstall())
4050 [installing addObject:name];
4051 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4052 [reinstalling addObject:name];
4053 else if (state.Upgrade())
4054 [upgrading addObject:name];
4055 else if (state.Downgrade())
4056 [downgrading addObject:name];
4057 else if (state.Delete()) {
4058 if ([package essential])
4060 [removing addObject:name];
4063 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4064 substrate_ |= DepSubstrate(iterator.CurrentVer());
4069 else if (Advanced_) {
4070 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4072 essential_ = [[UIAlertView alloc]
4073 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4074 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4076 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4077 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4080 [essential_ setContext:@"remove"];
4082 essential_ = [[UIAlertView alloc]
4083 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4084 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4086 cancelButtonTitle:UCLocalize("OKAY")
4087 otherButtonTitles:nil
4090 [essential_ setContext:@"unable"];
4093 changes_ = [[NSArray alloc] initWithObjects:
4101 issues_ = [database_ issues];
4103 issues_ = [issues_ retain];
4105 sizes_ = [[NSArray alloc] initWithObjects:
4106 SizeString([database_ fetcher].FetchNeeded()),
4107 SizeString([database_ fetcher].PartialPresent()),
4108 SizeString([database_ cache]->UsrSize()),
4111 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4113 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4117 - (NSString *) backButtonTitle {
4118 return UCLocalize("CONFIRM");
4121 - (NSString *) leftButtonTitle {
4122 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
4125 - (id) rightButtonTitle {
4126 return issues_ != nil ? nil : [super rightButtonTitle];
4129 - (id) _rightButtonTitle {
4130 #if AlwaysReload || IgnoreInstall
4131 return [super _rightButtonTitle];
4133 return UCLocalize("CONFIRM");
4137 - (void) _leftButtonClicked {
4142 - (void) _rightButtonClicked {
4144 return [super _rightButtonClicked];
4146 if (essential_ != nil)
4147 [essential_ popupAlertAnimated:YES];
4151 [delegate_ confirm];
4159 /* Progress Data {{{ */
4160 @interface ProgressData : NSObject {
4166 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4173 @implementation ProgressData
4175 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4176 if ((self = [super init]) != nil) {
4177 selector_ = selector;
4197 /* Progress View {{{ */
4198 @interface ProgressView : UIView <
4199 ConfigurationDelegate,
4202 _transient Database *database_;
4204 UIView *background_;
4205 UITransitionView *transition_;
4207 UINavigationBar *navbar_;
4208 UIProgressBar *progress_;
4209 UITextView *output_;
4210 UITextLabel *status_;
4211 UIPushButton *close_;
4214 SHA1SumValue springlist_;
4215 SHA1SumValue notifyconf_;
4219 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4220 - (void) setContentView:(UIView *)view;
4223 - (void) _retachThread;
4224 - (void) _detachNewThreadData:(ProgressData *)data;
4225 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4231 @protocol ProgressViewDelegate
4232 - (void) progressViewIsComplete:(ProgressView *)sender;
4235 @implementation ProgressView
4238 [transition_ setDelegate:nil];
4239 [navbar_ setDelegate:nil];
4242 if (background_ != nil)
4243 [background_ release];
4244 [transition_ release];
4247 [progress_ release];
4256 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4257 if ((self = [super initWithFrame:frame]) != nil) {
4258 database_ = database;
4259 delegate_ = delegate;
4261 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4262 [transition_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4263 [transition_ setDelegate:self];
4265 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4266 [overlay_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4268 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4269 [background_ setBackgroundColor:[UIColor blackColor]];
4270 [self addSubview:background_];
4272 [self addSubview:transition_];
4274 CGSize navsize = [UINavigationBar defaultSize];
4275 CGRect navrect = {{0, 0}, navsize};
4277 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4278 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
4279 [overlay_ addSubview:navbar_];
4281 [navbar_ setBarStyle:1];
4282 [navbar_ setDelegate:self];
4284 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4285 [navbar_ pushNavigationItem:navitem];
4287 CGRect bounds = [overlay_ bounds];
4288 CGSize prgsize = [UIProgressBar defaultSize];
4291 (bounds.size.width - prgsize.width) / 2,
4292 bounds.size.height - prgsize.height - 20
4295 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4296 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4297 [progress_ setStyle:0];
4299 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4301 bounds.size.height - prgsize.height - 50,
4302 bounds.size.width - 20,
4306 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4308 [status_ setColor:[UIColor whiteColor]];
4309 [status_ setBackgroundColor:[UIColor clearColor]];
4311 [status_ setCentersHorizontally:YES];
4312 //[status_ setFont:font];
4314 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4316 navrect.size.height + 20,
4317 bounds.size.width - 20,
4318 bounds.size.height - navsize.height - 62 - navrect.size.height
4321 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4322 [overlay_ addSubview:output_];
4324 //[output_ setTextFont:@"Courier New"];
4325 [output_ setFont:[[output_ font] fontWithSize:12]];
4327 [output_ setTextColor:[UIColor whiteColor]];
4328 [output_ setBackgroundColor:[UIColor clearColor]];
4330 [output_ setMarginTop:0];
4331 [output_ setAllowsRubberBanding:YES];
4332 [output_ setEditable:NO];
4334 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4336 bounds.size.height - prgsize.height - 50,
4337 bounds.size.width - 20,
4341 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4343 [close_ setAutosizesToFit:NO];
4344 [close_ setDrawsShadow:YES];
4345 [close_ setStretchBackground:YES];
4346 [close_ setEnabled:YES];
4348 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4349 [close_ setTitleFont:bold];
4351 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4352 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4353 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4357 - (void) setContentView:(UIView *)view {
4358 view_ = [view retain];
4361 - (void) resetView {
4362 [transition_ transition:6 toView:view_];
4365 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4366 NSString *context([alert context]);
4368 if ([context isEqualToString:@"conffile"]) {
4369 FILE *input = [database_ input];
4370 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4371 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4374 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4378 - (void) closeButtonPushed {
4387 [delegate_ terminateWithSuccess];
4388 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4389 [delegate_ suspendWithAnimation:YES];
4391 [delegate_ suspend];*/
4395 system("launchctl stop com.apple.SpringBoard");
4399 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4408 - (void) _retachThread {
4409 UINavigationItem *item([navbar_ topItem]);
4410 [item setTitle:UCLocalize("COMPLETE")];
4412 [overlay_ addSubview:close_];
4413 [progress_ removeFromSuperview];
4414 [status_ removeFromSuperview];
4416 [database_ popErrorWithTitle:title_];
4417 [delegate_ progressViewIsComplete:self];
4421 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4424 MMap mmap(file, MMap::ReadOnly);
4426 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4427 if (!(notifyconf_ == sha1.Result()))
4434 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4437 MMap mmap(file, MMap::ReadOnly);
4439 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4440 if (!(springlist_ == sha1.Result()))
4446 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4447 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4448 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4449 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4450 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4453 system("su -c /usr/bin/uicache mobile");
4455 [delegate_ setStatusBarShowsProgress:NO];
4458 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4459 [[data target] performSelector:[data selector] withObject:[data object]];
4462 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4465 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4471 title_ = [title retain];
4473 UINavigationItem *item([navbar_ topItem]);
4474 [item setTitle:title_];
4476 [status_ setText:nil];
4477 [output_ setText:@""];
4478 [progress_ setProgress:0];
4480 [close_ removeFromSuperview];
4481 [overlay_ addSubview:progress_];
4482 [overlay_ addSubview:status_];
4484 [delegate_ setStatusBarShowsProgress:YES];
4489 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4492 MMap mmap(file, MMap::ReadOnly);
4494 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4495 notifyconf_ = sha1.Result();
4501 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4504 MMap mmap(file, MMap::ReadOnly);
4506 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4507 springlist_ = sha1.Result();
4511 [transition_ transition:6 toView:overlay_];
4514 detachNewThreadSelector:@selector(_detachNewThreadData:)
4516 withObject:[[ProgressData alloc]
4517 initWithSelector:selector
4524 - (void) repairWithSelector:(SEL)selector {
4526 detachNewThreadSelector:selector
4529 title:UCLocalize("REPAIRING")
4533 - (void) setConfigurationData:(NSString *)data {
4535 performSelectorOnMainThread:@selector(_setConfigurationData:)
4541 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4542 CYActionSheet *sheet([[[CYActionSheet alloc]
4544 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4545 defaultButtonIndex:0
4548 [sheet setBodyText:error];
4549 [sheet yieldToPopupAlertAnimated:YES];
4553 - (void) setProgressTitle:(NSString *)title {
4555 performSelectorOnMainThread:@selector(_setProgressTitle:)
4561 - (void) setProgressPercent:(float)percent {
4563 performSelectorOnMainThread:@selector(_setProgressPercent:)
4564 withObject:[NSNumber numberWithFloat:percent]
4569 - (void) startProgress {
4572 - (void) addProgressOutput:(NSString *)output {
4574 performSelectorOnMainThread:@selector(_addProgressOutput:)
4580 - (bool) isCancelling:(size_t)received {
4584 - (void) _setConfigurationData:(NSString *)data {
4585 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4587 if (!conffile_r(data)) {
4588 lprintf("E:invalid conffile\n");
4592 NSString *ofile = conffile_r[1];
4593 //NSString *nfile = conffile_r[2];
4595 UIAlertView *alert = [[[UIAlertView alloc]
4596 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4597 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4599 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4600 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4601 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4605 [alert setContext:@"conffile"];
4609 - (void) _setProgressTitle:(NSString *)title {
4610 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4611 for (size_t i(0), e([words count]); i != e; ++i) {
4612 NSString *word([words objectAtIndex:i]);
4613 if (Package *package = [database_ packageWithName:word])
4614 [words replaceObjectAtIndex:i withObject:[package name]];
4617 [status_ setText:[words componentsJoinedByString:@" "]];
4620 - (void) _setProgressPercent:(NSNumber *)percent {
4621 [progress_ setProgress:[percent floatValue]];
4624 - (void) _addProgressOutput:(NSString *)output {
4625 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4626 CGSize size = [output_ contentSize];
4627 CGRect rect = {{0, size.height}, {size.width, 0}};
4628 [output_ scrollRectToVisible:rect animated:YES];
4631 - (BOOL) isRunning {
4638 /* Package Cell {{{ */
4639 @interface ContentView : UIView {
4640 _transient id delegate_;
4645 @interface PackageCell : UITableViewCell {
4648 NSString *description_;
4654 ContentView *content_;
4660 - (PackageCell *) init;
4661 - (void) setPackage:(Package *)package;
4663 + (int) heightForPackage:(Package *)package;
4664 - (void) drawContentRect:(CGRect)rect;
4668 @implementation ContentView
4670 - (id) initWithFrame:(CGRect)frame {
4671 if ((self = [super initWithFrame:frame]) != nil) {
4675 - (void) setDelegate:(id)delegate {
4676 delegate_ = delegate;
4679 /* Fix landscape: redraw when frame changes. */
4680 - (void) setFrame:(CGRect)frame {
4681 [super setFrame:frame];
4682 [self setNeedsDisplay];
4685 - (void) drawRect:(CGRect)rect {
4686 [super drawRect:rect];
4687 [delegate_ drawContentRect:rect];
4692 @implementation PackageCell
4694 - (void) clearPackage {
4705 if (description_ != nil) {
4706 [description_ release];
4710 if (source_ != nil) {
4715 if (badge_ != nil) {
4720 if (placard_ != nil) {
4730 [self clearPackage];
4737 return faded_ ? [self selectionPercent] : fade_;
4740 - (PackageCell *) init {
4741 CGRect frame(CGRectMake(0, 0, 320, 74));
4742 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4743 UIView *content([self contentView]);
4744 CGRect bounds([content bounds]);
4746 content_ = [[ContentView alloc] initWithFrame:bounds];
4747 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4748 [content addSubview:content_];
4750 [content_ setDelegate:self];
4751 [content_ setOpaque:YES];
4752 if ([self respondsToSelector:@selector(selectionPercent)])
4755 [self setNeedsDisplayOnBoundsChange:YES];
4759 - (void) _setBackgroundColor {
4761 if (NSString *mode = [package_ mode]) {
4762 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4763 color = remove ? RemovingColor_ : InstallingColor_;
4765 color = [UIColor whiteColor];
4767 [content_ setBackgroundColor:color];
4768 [self setNeedsDisplay];
4771 - (void) setPackage:(Package *)package {
4772 [self clearPackage];
4775 Source *source = [package source];
4777 icon_ = [[package icon] retain];
4778 name_ = [[package name] retain];
4781 description_ = [package longDescription];
4782 if (description_ == nil)
4783 description_ = [package shortDescription];
4784 if (description_ != nil)
4785 description_ = [description_ retain];
4787 commercial_ = [package isCommercial];
4789 package_ = [package retain];
4791 NSString *label = nil;
4792 bool trusted = false;
4794 if (source != nil) {
4795 label = [source label];
4796 trusted = [source trusted];
4797 } else if ([[package id] isEqualToString:@"firmware"])
4798 label = UCLocalize("APPLE");
4800 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4802 NSString *from(label);
4804 NSString *section = [package simpleSection];
4805 if (section != nil && ![section isEqualToString:label]) {
4806 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4807 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4810 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4811 source_ = [from retain];
4813 if (NSString *purpose = [package primaryPurpose])
4814 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4815 badge_ = [badge_ retain];
4817 if ([package installed] != nil)
4818 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4819 placard_ = [placard_ retain];
4821 [self _setBackgroundColor];
4822 [content_ setNeedsDisplay];
4825 - (void) drawContentRect:(CGRect)rect {
4826 bool selected([self isSelected]);
4827 float width([self bounds].size.width);
4830 CGContextRef context(UIGraphicsGetCurrentContext());
4831 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4832 CGContextFillRect(context, rect);
4837 rect.size = [icon_ size];
4839 rect.size.width /= 2;
4840 rect.size.height /= 2;
4842 rect.origin.x = 25 - rect.size.width / 2;
4843 rect.origin.y = 25 - rect.size.height / 2;
4845 [icon_ drawInRect:rect];
4848 if (badge_ != nil) {
4849 CGSize size = [badge_ size];
4851 [badge_ drawAtPoint:CGPointMake(
4852 36 - size.width / 2,
4853 36 - size.height / 2
4861 UISetColor(commercial_ ? Purple_ : Black_);
4862 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ ellipsis:2];
4863 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
4866 UISetColor(commercial_ ? Purplish_ : Gray_);
4867 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ ellipsis:2];
4869 if (placard_ != nil)
4870 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4873 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4874 //[self _setBackgroundColor];
4875 [super setSelected:selected animated:fade];
4876 [content_ setNeedsDisplay];
4879 + (int) heightForPackage:(Package *)package {
4885 /* Section Cell {{{ */
4886 @interface SectionCell : UISimpleTableCell {
4892 _UISwitchSlider *switch_;
4897 - (void) setSection:(Section *)section editing:(BOOL)editing;
4901 @implementation SectionCell
4903 - (void) clearSection {
4904 if (basic_ != nil) {
4909 if (section_ != nil) {
4919 if (count_ != nil) {
4926 [self clearSection];
4933 if ((self = [super init]) != nil) {
4934 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4935 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4936 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventTouchUpInside];
4940 - (void) onSwitch:(id)sender {
4941 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4942 if (metadata == nil) {
4943 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4944 [Sections_ setObject:metadata forKey:basic_];
4948 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4951 - (void) setSection:(Section *)section editing:(BOOL)editing {
4952 if (editing != editing_) {
4954 [switch_ removeFromSuperview];
4956 [self addSubview:switch_];
4960 [self clearSection];
4962 if (section == nil) {
4963 name_ = [UCLocalize("ALL_PACKAGES") retain];
4966 basic_ = [section name];
4968 basic_ = [basic_ retain];
4970 section_ = [section localized];
4971 if (section_ != nil)
4972 section_ = [section_ retain];
4974 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4975 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4978 [switch_ setValue:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4982 - (void) setFrame:(CGRect)frame {
4983 [super setFrame:frame];
4984 CGRect rect([switch_ frame]);
4985 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4988 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4989 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4997 float width(rect.size.width + 23);
5001 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ ellipsis:2];
5003 CGSize size = [count_ sizeWithFont:Font14_];
5007 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5009 [super drawContentInRect:rect selected:selected];
5015 /* File Table {{{ */
5016 @interface FileTable : RVPage {
5017 _transient Database *database_;
5020 NSMutableArray *files_;
5024 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5025 - (void) setPackage:(Package *)package;
5029 @implementation FileTable
5032 if (package_ != nil)
5041 - (int) numberOfRowsInTable:(UITable *)table {
5042 return files_ == nil ? 0 : [files_ count];
5045 - (float) table:(UITable *)table heightForRow:(int)row {
5049 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
5050 if (reusing == nil) {
5051 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
5052 UIFont *font = [UIFont systemFontOfSize:16];
5053 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
5055 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
5059 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5063 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5064 if ((self = [super initWithBook:book]) != nil) {
5065 database_ = database;
5067 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5069 list_ = [[UITable alloc] initWithFrame:[self bounds]];
5070 [self addSubview:list_];
5072 UITableColumn *column = [[[UITableColumn alloc]
5073 initWithTitle:UCLocalize("NAME")
5075 width:[self frame].size.width
5078 [list_ setDataSource:self];
5079 [list_ setSeparatorStyle:1];
5080 [list_ addTableColumn:column];
5081 [list_ setDelegate:self];
5082 [list_ setReusesTableCells:YES];
5084 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5085 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5089 - (void) setPackage:(Package *)package {
5090 if (package_ != nil) {
5091 [package_ autorelease];
5100 [files_ removeAllObjects];
5102 if (package != nil) {
5103 package_ = [package retain];
5104 name_ = [[package id] retain];
5106 if (NSArray *files = [package files])
5107 [files_ addObjectsFromArray:files];
5109 if ([files_ count] != 0) {
5110 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5111 [files_ removeObjectAtIndex:0];
5112 [files_ sortUsingSelector:@selector(compareByPath:)];
5114 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5115 [stack addObject:@"/"];
5117 for (int i(0), e([files_ count]); i != e; ++i) {
5118 NSString *file = [files_ objectAtIndex:i];
5119 while (![file hasPrefix:[stack lastObject]])
5120 [stack removeLastObject];
5121 NSString *directory = [stack lastObject];
5122 [stack addObject:[file stringByAppendingString:@"/"]];
5123 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5124 ([stack count] - 2) * 3, "",
5125 [file substringFromIndex:[directory length]]
5134 - (void) resetViewAnimated:(BOOL)animated {
5135 [list_ resetViewAnimated:animated];
5138 - (void) reloadData {
5139 [self setPackage:[database_ packageWithName:name_]];
5140 [self reloadButtons];
5143 - (NSString *) title {
5144 return UCLocalize("INSTALLED_FILES");
5147 - (NSString *) backButtonTitle {
5148 return UCLocalize("FILES");
5153 /* Package View {{{ */
5154 @interface PackageView : CydiaBrowserView {
5155 _transient Database *database_;
5159 NSMutableArray *buttons_;
5162 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5163 - (void) setPackage:(Package *)package;
5167 @implementation PackageView
5170 if (package_ != nil)
5179 if ([self retainCount] == 1)
5180 [delegate_ setPackageView:self];
5184 /* XXX: this is not safe at all... localization of /fail/ */
5185 - (void) _clickButtonWithName:(NSString *)name {
5186 if ([name isEqualToString:UCLocalize("CLEAR")])
5187 [delegate_ clearPackage:package_];
5188 else if ([name isEqualToString:UCLocalize("INSTALL")])
5189 [delegate_ installPackage:package_];
5190 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5191 [delegate_ installPackage:package_];
5192 else if ([name isEqualToString:UCLocalize("REMOVE")])
5193 [delegate_ removePackage:package_];
5194 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5195 [delegate_ installPackage:package_];
5196 else _assert(false);
5199 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5200 NSString *context([sheet context]);
5202 if ([context isEqualToString:@"modify"]) {
5203 int count = [buttons_ count];
5204 _assert(count != 0);
5205 _assert(button <= count + 1);
5207 if (count != button - 1)
5208 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
5212 [super alertSheet:sheet buttonClicked:button];
5215 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5216 return [super webView:sender didFinishLoadForFrame:frame];
5219 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5220 [super webView:sender didClearWindowObject:window forFrame:frame];
5221 [window setValue:package_ forKey:@"package"];
5224 - (bool) _allowJavaScriptPanel {
5229 - (void) __rightButtonClicked {
5230 int count([buttons_ count]);
5235 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5237 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
5238 [buttons addObjectsFromArray:buttons_];
5239 [buttons addObject:UCLocalize("CANCEL")];
5241 [delegate_ slideUp:[[[UIActionSheet alloc]
5244 defaultButtonIndex:([buttons count] - 1)
5251 - (void) _rightButtonClicked {
5253 [super _rightButtonClicked];
5255 [self __rightButtonClicked];
5259 - (id) _rightButtonTitle {
5260 int count = [buttons_ count];
5261 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5264 - (NSString *) backButtonTitle {
5268 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5269 if ((self = [super initWithBook:book]) != nil) {
5270 database_ = database;
5271 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5272 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5276 - (void) setPackage:(Package *)package {
5277 if (package_ != nil) {
5278 [package_ autorelease];
5287 [buttons_ removeAllObjects];
5289 if (package != nil) {
5292 package_ = [package retain];
5293 name_ = [[package id] retain];
5294 commercial_ = [package isCommercial];
5296 if ([package_ mode] != nil)
5297 [buttons_ addObject:UCLocalize("CLEAR")];
5298 if ([package_ source] == nil);
5299 else if ([package_ upgradableAndEssential:NO])
5300 [buttons_ addObject:UCLocalize("UPGRADE")];
5301 else if ([package_ uninstalled])
5302 [buttons_ addObject:UCLocalize("INSTALL")];
5304 [buttons_ addObject:UCLocalize("REINSTALL")];
5305 if (![package_ uninstalled])
5306 [buttons_ addObject:UCLocalize("REMOVE")];
5308 if (special_ != NULL) {
5309 CGRect frame([document_ frame]);
5310 frame.size.width = 320;
5311 frame.size.height = 0;
5312 [document_ setFrame:frame];
5314 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5315 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5317 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
5320 [[[document_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5322 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5324 [self setFinishHook:nil];
5325 [self setPopupHook:nil];
5328 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5329 [super callFunction:special_];
5333 [self reloadButtons];
5336 - (bool) isLoading {
5337 return commercial_ ? [super isLoading] : false;
5340 - (void) reloadData {
5341 [self setPackage:[database_ packageWithName:name_]];
5346 /* Package Table {{{ */
5347 @interface PackageTable : RVPage {
5348 _transient Database *database_;
5350 NSMutableArray *packages_;
5351 NSMutableArray *sections_;
5353 NSMutableArray *index_;
5354 NSMutableDictionary *indices_;
5357 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5359 - (void) setDelegate:(id)delegate;
5361 - (void) reloadData;
5362 - (void) resetCursor;
5364 - (UITableView *) list;
5366 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5370 @implementation PackageTable
5373 [list_ setDataSource:nil];
5376 [packages_ release];
5377 [sections_ release];
5384 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5385 NSInteger count([sections_ count]);
5386 return count == 0 ? 1 : count;
5389 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5390 if ([sections_ count] == 0)
5392 return [[sections_ objectAtIndex:section] name];
5395 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5396 if ([sections_ count] == 0)
5398 return [[sections_ objectAtIndex:section] count];
5401 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5402 Section *section([sections_ objectAtIndex:[path section]]);
5403 NSInteger row([path row]);
5404 Package *package([packages_ objectAtIndex:([section row] + row)]);
5408 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5409 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5411 cell = [[[PackageCell alloc] init] autorelease];
5412 [cell setPackage:[self packageAtIndexPath:path]];
5416 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5418 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5421 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5422 Package *package([self packageAtIndexPath:path]);
5423 package = [database_ packageWithName:[package id]];
5424 PackageView *view([delegate_ packageView]);
5425 [view setPackage:package];
5426 [view setDelegate:delegate_];
5427 [book_ pushPage:view];
5431 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5432 return [packages_ count] > 20 ? index_ : nil;
5435 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5439 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5440 if ((self = [super initWithBook:book]) != nil) {
5441 database_ = database;
5442 title_ = [title retain];
5444 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5445 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5447 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5448 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5450 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5451 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5452 [self addSubview:list_];
5454 [list_ setDataSource:self];
5455 [list_ setDelegate:self];
5457 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5461 - (void) setDelegate:(id)delegate {
5462 delegate_ = delegate;
5465 - (bool) hasPackage:(Package *)package {
5469 - (void) reloadData {
5470 NSArray *packages = [database_ packages];
5472 [packages_ removeAllObjects];
5473 [sections_ removeAllObjects];
5475 _profile(PackageTable$reloadData$Filter)
5476 for (Package *package in packages)
5477 if ([self hasPackage:package])
5478 [packages_ addObject:package];
5481 [index_ removeAllObjects];
5482 [indices_ removeAllObjects];
5484 Section *section = nil;
5486 _profile(PackageTable$reloadData$Section)
5487 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5491 _profile(PackageTable$reloadData$Section$Package)
5492 package = [packages_ objectAtIndex:offset];
5493 index = [package index];
5496 if (section == nil || [section index] != index) {
5497 _profile(PackageTable$reloadData$Section$Allocate)
5498 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5501 [index_ addObject:[section name]];
5502 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5504 _profile(PackageTable$reloadData$Section$Add)
5505 [sections_ addObject:section];
5509 [section addToCount];
5513 _profile(PackageTable$reloadData$List)
5518 - (NSString *) title {
5522 - (void) resetViewAnimated:(BOOL)animated {
5523 [list_ resetViewAnimated:animated];
5526 - (void) resetCursor {
5527 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5530 - (UITableView *) list {
5534 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5535 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5540 /* Filtered Package Table {{{ */
5541 @interface FilteredPackageTable : PackageTable {
5547 - (void) setObject:(id)object;
5548 - (void) setObject:(id)object forFilter:(SEL)filter;
5550 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5554 @implementation FilteredPackageTable
5562 - (void) setFilter:(SEL)filter {
5565 /* XXX: this is an unsafe optimization of doomy hell */
5566 Method method(class_getInstanceMethod([Package class], filter));
5567 _assert(method != NULL);
5568 imp_ = method_getImplementation(method);
5569 _assert(imp_ != NULL);
5572 - (void) setObject:(id)object {
5578 object_ = [object retain];
5581 - (void) setObject:(id)object forFilter:(SEL)filter {
5582 [self setFilter:filter];
5583 [self setObject:object];
5587 - (bool) hasPackage:(Package *)package {
5588 _profile(FilteredPackageTable$hasPackage)
5589 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5593 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5594 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5595 [self setFilter:filter];
5596 object_ = object == nil ? nil : [object retain];
5604 /* Add Source View {{{ */
5605 @interface AddSourceView : RVPage {
5606 _transient Database *database_;
5609 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5613 @implementation AddSourceView
5615 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5616 if ((self = [super initWithBook:book]) != nil) {
5617 database_ = database;
5623 /* Source Cell {{{ */
5624 @interface SourceCell : UITableCell {
5627 NSString *description_;
5633 - (SourceCell *) initWithSource:(Source *)source;
5637 @implementation SourceCell
5642 [description_ release];
5647 - (SourceCell *) initWithSource:(Source *)source {
5648 if ((self = [super init]) != nil) {
5650 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5652 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5653 icon_ = [icon_ retain];
5655 origin_ = [[source name] retain];
5656 label_ = [[source uri] retain];
5657 description_ = [[source description] retain];
5661 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5662 float width(rect.size.width);
5665 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5672 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ ellipsis:2];
5676 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
5680 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ ellipsis:2];
5682 [super drawContentInRect:rect selected:selected];
5687 /* Source Table {{{ */
5688 @interface SourceTable : RVPage {
5689 _transient Database *database_;
5690 UISectionList *list_;
5691 NSMutableArray *sources_;
5692 UIActionSheet *alert_;
5696 UIProgressHUD *hud_;
5699 //NSURLConnection *installer_;
5700 NSURLConnection *trivial_;
5701 NSURLConnection *trivial_bz2_;
5702 NSURLConnection *trivial_gz_;
5703 //NSURLConnection *automatic_;
5708 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5712 @implementation SourceTable
5714 - (void) _deallocConnection:(NSURLConnection *)connection {
5715 if (connection != nil) {
5716 [connection cancel];
5717 //[connection setDelegate:nil];
5718 [connection release];
5723 [[list_ table] setDelegate:nil];
5724 [list_ setDataSource:nil];
5733 //[self _deallocConnection:installer_];
5734 [self _deallocConnection:trivial_];
5735 [self _deallocConnection:trivial_gz_];
5736 [self _deallocConnection:trivial_bz2_];
5737 //[self _deallocConnection:automatic_];
5744 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5745 return offset_ == 0 ? 1 : 2;
5748 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5749 switch (section + (offset_ == 0 ? 1 : 0)) {
5750 case 0: return UCLocalize("ENTERED_BY_USER");
5751 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5757 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5758 switch (section + (offset_ == 0 ? 1 : 0)) {
5760 case 1: return offset_;
5766 - (int) numberOfRowsInTable:(UITable *)table {
5767 return [sources_ count];
5770 - (float) table:(UITable *)table heightForRow:(int)row {
5771 Source *source = [sources_ objectAtIndex:row];
5772 return [source description] == nil ? 56 : 73;
5775 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5776 Source *source = [sources_ objectAtIndex:row];
5777 // XXX: weird warning, stupid selectors ;P
5778 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5781 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5785 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5789 - (void) tableRowSelected:(NSNotification*)notification {
5790 UITable *table([list_ table]);
5791 int row([table selectedRow]);
5795 Source *source = [sources_ objectAtIndex:row];
5797 PackageTable *packages = [[[FilteredPackageTable alloc]
5800 title:[source label]
5801 filter:@selector(isVisibleInSource:)
5805 [packages setDelegate:delegate_];
5807 [book_ pushPage:packages];
5810 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5811 Source *source = [sources_ objectAtIndex:row];
5812 return [source record] != nil;
5815 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5816 [[list_ table] setDeleteConfirmationRow:row];
5819 - (void) table:(UITable *)table deleteRow:(int)row {
5820 Source *source = [sources_ objectAtIndex:row];
5821 [Sources_ removeObjectForKey:[source key]];
5822 [delegate_ syncData];
5826 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5829 @"./", @"Distribution",
5830 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5832 [delegate_ syncData];
5835 - (NSString *) getWarning {
5836 NSString *href(href_);
5837 NSRange colon([href rangeOfString:@"://"]);
5838 if (colon.location != NSNotFound)
5839 href = [href substringFromIndex:(colon.location + 3)];
5840 href = [href stringByAddingPercentEscapes];
5841 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5842 href = [href stringByCachingURLWithCurrentCDN];
5844 NSURL *url([NSURL URLWithString:href]);
5846 NSStringEncoding encoding;
5847 NSError *error(nil);
5849 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5850 return [warning length] == 0 ? nil : warning;
5854 - (void) _endConnection:(NSURLConnection *)connection {
5855 NSURLConnection **field = NULL;
5856 if (connection == trivial_)
5858 else if (connection == trivial_bz2_)
5859 field = &trivial_bz2_;
5860 else if (connection == trivial_gz_)
5861 field = &trivial_gz_;
5862 _assert(field != NULL);
5863 [connection release];
5868 trivial_bz2_ == nil &&
5874 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5877 UIActionSheet *sheet = [[[UIActionSheet alloc]
5878 initWithTitle:UCLocalize("SOURCE_WARNING")
5879 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5880 defaultButtonIndex:0
5885 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
5887 [sheet setNumberOfRows:1];
5888 [sheet setBodyText:warning];
5889 [sheet popupAlertAnimated:YES];
5892 } else if (error_ != nil) {
5893 UIActionSheet *sheet = [[[UIActionSheet alloc]
5894 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5895 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5896 defaultButtonIndex:0
5901 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
5903 [sheet setBodyText:[error_ localizedDescription]];
5904 [sheet popupAlertAnimated:YES];
5906 UIActionSheet *sheet = [[[UIActionSheet alloc]
5907 initWithTitle:UCLocalize("NOT_REPOSITORY")
5908 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5909 defaultButtonIndex:0
5914 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
5916 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5917 [sheet popupAlertAnimated:YES];
5920 [delegate_ setStatusBarShowsProgress:NO];
5921 [delegate_ removeProgressHUD:hud_];
5931 if (error_ != nil) {
5938 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5939 switch ([response statusCode]) {
5945 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5946 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5948 error_ = [error retain];
5949 [self _endConnection:connection];
5952 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5953 [self _endConnection:connection];
5956 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5957 NSMutableURLRequest *request = [NSMutableURLRequest
5958 requestWithURL:[NSURL URLWithString:href]
5959 cachePolicy:NSURLRequestUseProtocolCachePolicy
5960 timeoutInterval:120.0
5963 [request setHTTPMethod:method];
5965 if (Machine_ != NULL)
5966 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5967 if (UniqueID_ != nil)
5968 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5970 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5972 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5975 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5976 NSString *context([sheet context]);
5978 if ([context isEqualToString:@"source"]) {
5981 NSString *href = [[sheet textField] text];
5983 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5985 if (![href hasSuffix:@"/"])
5986 href_ = [href stringByAppendingString:@"/"];
5989 href_ = [href_ retain];
5991 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
5992 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5993 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5994 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5998 hud_ = [[delegate_ addProgressHUD] retain];
5999 [hud_ setText:UCLocalize("VERIFYING_URL")];
6009 } else if ([context isEqualToString:@"trivial"])
6011 else if ([context isEqualToString:@"urlerror"])
6013 else if ([context isEqualToString:@"warning"]) {
6032 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6033 if ((self = [super initWithBook:book]) != nil) {
6034 database_ = database;
6035 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6037 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
6038 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6039 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6040 [self addSubview:list_];
6042 [list_ setShouldHideHeaderInShortLists:NO];
6043 [list_ setDataSource:self];
6045 UITableColumn *column = [[UITableColumn alloc]
6046 initWithTitle:UCLocalize("NAME")
6048 width:[self frame].size.width
6051 UITable *table = [list_ table];
6052 [table setSeparatorStyle:1];
6053 [table addTableColumn:column];
6054 [table setDelegate:self];
6058 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6062 - (void) reloadData {
6064 if (!list.ReadMainList())
6067 [sources_ removeAllObjects];
6068 [sources_ addObjectsFromArray:[database_ sources]];
6070 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6073 int count([sources_ count]);
6074 for (offset_ = 0; offset_ != count; ++offset_) {
6075 Source *source = [sources_ objectAtIndex:offset_];
6076 if ([source record] == nil)
6083 - (void) resetViewAnimated:(BOOL)animated {
6084 [list_ resetViewAnimated:animated];
6087 - (void) _leftButtonClicked {
6088 /*[book_ pushPage:[[[AddSourceView alloc]
6093 UIActionSheet *sheet = [[[UIActionSheet alloc]
6094 initWithTitle:UCLocalize("ENTER_APT_URL")
6095 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
6096 defaultButtonIndex:0
6101 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6103 [sheet setNumberOfRows:1];
6104 [sheet addTextFieldWithValue:@"http://" label:@""];
6106 UITextInputTraits *traits = [[sheet textField] textInputTraits];
6107 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6108 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6109 [traits setKeyboardType:UIKeyboardTypeURL];
6110 // XXX: UIReturnKeyDone
6111 [traits setReturnKeyType:UIReturnKeyNext];
6113 [sheet popupAlertAnimated:YES];
6116 - (void) _rightButtonClicked {
6117 UITable *table = [list_ table];
6118 BOOL editing = [table isRowDeletionEnabled];
6119 [table enableRowDeletion:!editing animated:YES];
6120 [book_ reloadButtonsForPage:self];
6123 - (NSString *) title {
6124 return UCLocalize("SOURCES");
6127 - (NSString *) leftButtonTitle {
6128 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
6131 - (id) rightButtonTitle {
6132 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
6135 - (UINavigationButtonStyle) rightButtonStyle {
6136 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6142 /* Installed View {{{ */
6143 @interface InstalledView : RVPage {
6144 _transient Database *database_;
6145 FilteredPackageTable *packages_;
6149 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6153 @implementation InstalledView
6156 [packages_ release];
6160 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6161 if ((self = [super initWithBook:book]) != nil) {
6162 database_ = database;
6164 packages_ = [[FilteredPackageTable alloc]
6168 filter:@selector(isInstalledAndVisible:)
6169 with:[NSNumber numberWithBool:YES]
6172 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6173 [self addSubview:packages_];
6175 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6179 - (void) resetViewAnimated:(BOOL)animated {
6180 [packages_ resetViewAnimated:animated];
6183 - (void) reloadData {
6184 [packages_ reloadData];
6187 - (void) _rightButtonClicked {
6188 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6189 [packages_ reloadData];
6191 [book_ reloadButtonsForPage:self];
6194 - (NSString *) title {
6195 return UCLocalize("INSTALLED");
6198 - (NSString *) backButtonTitle {
6199 return UCLocalize("PACKAGES");
6202 - (id) rightButtonTitle {
6203 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6206 - (UINavigationButtonStyle) rightButtonStyle {
6207 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6210 - (void) setDelegate:(id)delegate {
6211 [super setDelegate:delegate];
6212 [packages_ setDelegate:delegate];
6219 @interface HomeView : CydiaBrowserView {
6224 @implementation HomeView
6226 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6227 [super _setMoreHeaders:request];
6229 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6230 if (UniqueID_ != nil)
6231 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6234 - (void) _leftButtonClicked {
6235 UIAlertView *alert = [[[UIAlertView alloc] init] autorelease];
6236 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6237 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6238 [alert setCancelButtonIndex:0];
6241 @"Copyright (C) 2008-2010\n"
6242 "Jay Freeman (saurik)\n"
6243 "saurik@saurik.com\n"
6244 "http://www.saurik.com/"
6250 - (NSString *) leftButtonTitle {
6251 return UCLocalize("ABOUT");
6256 /* Manage View {{{ */
6257 @interface ManageView : CydiaBrowserView {
6262 @implementation ManageView
6264 - (NSString *) title {
6265 return UCLocalize("MANAGE");
6268 - (void) _leftButtonClicked {
6269 [delegate_ askForSettings];
6270 [delegate_ updateData];
6273 - (NSString *) leftButtonTitle {
6274 return UCLocalize("SETTINGS");
6278 - (id) _rightButtonTitle {
6279 return Queuing_ ? UCLocalize("QUEUE") : nil;
6282 - (UINavigationButtonStyle) rightButtonStyle {
6283 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6286 - (void) _rightButtonClicked {
6291 - (bool) isLoading {
6298 /* Cydia Book {{{ */
6299 @interface CYBook : RVBook <
6302 _transient Database *database_;
6303 UINavigationBar *overlay_;
6304 UINavigationBar *underlay_;
6305 UIProgressIndicator *indicator_;
6306 UITextLabel *prompt_;
6307 UIProgressBar *progress_;
6308 UINavigationButton *cancel_;
6313 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6316 - (void) setUpdate:(NSDate *)date;
6320 @implementation CYBook
6324 [indicator_ release];
6326 [progress_ release];
6331 - (NSString *) getTitleForPage:(RVPage *)page {
6332 return [super getTitleForPage:page];
6344 [UIView beginAnimations:nil context:NULL];
6346 CGRect ovrframe = [overlay_ frame];
6347 ovrframe.origin.y = 0;
6348 [overlay_ setFrame:ovrframe];
6350 CGRect barframe = [navbar_ frame];
6351 barframe.origin.y += ovrframe.size.height;
6352 [navbar_ setFrame:barframe];
6354 CGRect trnframe = [transition_ frame];
6355 trnframe.origin.y += ovrframe.size.height;
6356 trnframe.size.height -= ovrframe.size.height;
6357 [transition_ setFrame:trnframe];
6359 [UIView endAnimations];
6367 [UIView beginAnimations:nil context:NULL];
6369 CGRect ovrframe = [overlay_ frame];
6370 ovrframe.origin.y = -ovrframe.size.height;
6371 [overlay_ setFrame:ovrframe];
6373 CGRect barframe = [navbar_ frame];
6374 barframe.origin.y -= ovrframe.size.height;
6375 [navbar_ setFrame:barframe];
6377 CGRect trnframe = [transition_ frame];
6378 trnframe.origin.y -= ovrframe.size.height;
6379 trnframe.size.height += ovrframe.size.height;
6380 [transition_ setFrame:trnframe];
6382 [UIView commitAnimations];
6385 - (void) setUpdate:(NSDate *)date {
6392 [indicator_ startAnimation];
6393 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6394 [progress_ setProgress:0];
6397 [overlay_ addSubview:cancel_];
6400 detachNewThreadSelector:@selector(_update)
6406 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6407 NSString *context([sheet context]);
6409 if ([context isEqualToString:@"refresh"])
6416 [indicator_ stopAnimation];
6420 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6423 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6424 if ((self = [super initWithFrame:frame]) != nil) {
6425 database_ = database;
6427 CGRect ovrrect([navbar_ bounds]);
6428 ovrrect.size.height = [UINavigationBar defaultSize].height;
6429 ovrrect.origin.y = -ovrrect.size.height;
6431 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6432 [overlay_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6433 [self addSubview:overlay_];
6435 ovrrect.origin.y = frame.size.height;
6436 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6437 [underlay_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6438 [self addSubview:underlay_];
6440 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6442 [overlay_ setBarStyle:1];
6443 [underlay_ setBarStyle:1];
6445 int barstyle([overlay_ _barStyle:NO]);
6446 bool ugly(barstyle == 0);
6448 UIProgressIndicatorStyle style = ugly ?
6449 UIProgressIndicatorStyleMediumBrown :
6450 UIProgressIndicatorStyleMediumWhite;
6452 CGSize indsize([UIProgressIndicator defaultSizeForStyle:style]);
6453 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6454 CGRect indrect = {{indoffset, indoffset}, indsize};
6456 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6457 [indicator_ setStyle:style];
6458 [overlay_ addSubview:indicator_];
6460 CGSize prmsize = {215, indsize.height + 4};
6463 indoffset * 2 + indsize.width,
6464 unsigned(ovrrect.size.height - prmsize.height) / 2 - 1
6467 UIFont *font([UIFont systemFontOfSize:15]);
6469 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6471 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6472 [prompt_ setBackgroundColor:[UIColor clearColor]];
6473 [prompt_ setFont:font];
6475 [overlay_ addSubview:prompt_];
6477 CGSize prgsize = {75, 100};
6480 ovrrect.size.width - prgsize.width - 10,
6481 (ovrrect.size.height - prgsize.height) / 2
6484 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6485 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6486 [overlay_ addSubview:progress_];
6488 [progress_ setStyle:0];
6490 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6491 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6492 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6494 CGRect frame = [cancel_ frame];
6495 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6496 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6497 [cancel_ setFrame:frame];
6499 [cancel_ setBarStyle:barstyle];
6503 - (void) _onCancel {
6505 [cancel_ removeFromSuperview];
6508 - (void) _update { _pooled
6510 status.setDelegate(self);
6511 [database_ updateWithStatus:status];
6514 performSelectorOnMainThread:@selector(_update_)
6520 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6521 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6525 UIActionSheet *sheet = [[[UIActionSheet alloc]
6526 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6527 buttons:[NSArray arrayWithObjects:
6530 defaultButtonIndex:0
6535 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6537 [sheet setBodyText:error];
6538 [sheet popupAlertAnimated:YES];
6540 [self reloadButtons];
6543 - (void) setProgressTitle:(NSString *)title {
6545 performSelectorOnMainThread:@selector(_setProgressTitle:)
6551 - (void) setProgressPercent:(float)percent {
6553 performSelectorOnMainThread:@selector(_setProgressPercent:)
6554 withObject:[NSNumber numberWithFloat:percent]
6559 - (void) startProgress {
6562 - (void) addProgressOutput:(NSString *)output {
6564 performSelectorOnMainThread:@selector(_addProgressOutput:)
6570 - (bool) isCancelling:(size_t)received {
6574 - (void) _setProgressTitle:(NSString *)title {
6575 [prompt_ setText:title];
6578 - (void) _setProgressPercent:(NSNumber *)percent {
6579 [progress_ setProgress:[percent floatValue]];
6582 - (void) _addProgressOutput:(NSString *)output {
6587 /* Cydia:// Protocol {{{ */
6588 @interface CydiaURLProtocol : NSURLProtocol {
6593 @implementation CydiaURLProtocol
6595 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6596 NSURL *url([request URL]);
6599 NSString *scheme([[url scheme] lowercaseString]);
6600 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6605 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6609 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6610 id<NSURLProtocolClient> client([self client]);
6612 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6614 NSData *data(UIImagePNGRepresentation(icon));
6616 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6617 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6618 [client URLProtocol:self didLoadData:data];
6619 [client URLProtocolDidFinishLoading:self];
6623 - (void) startLoading {
6624 id<NSURLProtocolClient> client([self client]);
6625 NSURLRequest *request([self request]);
6627 NSURL *url([request URL]);
6628 NSString *href([url absoluteString]);
6630 NSString *path([href substringFromIndex:8]);
6631 NSRange slash([path rangeOfString:@"/"]);
6634 if (slash.location == NSNotFound) {
6638 command = [path substringToIndex:slash.location];
6639 path = [path substringFromIndex:(slash.location + 1)];
6642 Database *database([Database sharedInstance]);
6644 if ([command isEqualToString:@"package-icon"]) {
6647 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6648 Package *package([database packageWithName:path]);
6651 UIImage *icon([package icon]);
6652 [self _returnPNGWithImage:icon forRequest:request];
6653 } else if ([command isEqualToString:@"source-icon"]) {
6656 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6657 NSString *source(Simplify(path));
6658 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6660 icon = [UIImage applicationImageNamed:@"unknown.png"];
6661 [self _returnPNGWithImage:icon forRequest:request];
6662 } else if ([command isEqualToString:@"uikit-image"]) {
6665 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6666 UIImage *icon(_UIImageWithName(path));
6667 [self _returnPNGWithImage:icon forRequest:request];
6668 } else if ([command isEqualToString:@"section-icon"]) {
6671 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6672 NSString *section(Simplify(path));
6673 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6675 icon = [UIImage applicationImageNamed:@"unknown.png"];
6676 [self _returnPNGWithImage:icon forRequest:request];
6678 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6682 - (void) stopLoading {
6688 /* Sections View {{{ */
6689 @interface SectionsView : RVPage {
6690 _transient Database *database_;
6691 NSMutableArray *sections_;
6692 NSMutableArray *filtered_;
6698 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6699 - (void) reloadData;
6704 @implementation SectionsView
6707 [list_ setDataSource:nil];
6708 [list_ setDelegate:nil];
6710 [sections_ release];
6711 [filtered_ release];
6713 [accessory_ release];
6717 - (int) numberOfRowsInTable:(UITable *)table {
6718 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6721 - (float) table:(UITable *)table heightForRow:(int)row {
6725 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6727 reusing = [[[SectionCell alloc] init] autorelease];
6728 [(SectionCell *)reusing setSection:(editing_ ?
6729 [sections_ objectAtIndex:row] :
6730 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6731 ) editing:editing_];
6735 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6739 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6743 - (void) tableRowSelected:(NSNotification *)notification {
6744 int row = [[notification object] selectedRow];
6755 title = UCLocalize("ALL_PACKAGES");
6757 section = [filtered_ objectAtIndex:(row - 1)];
6758 name = [section name];
6761 name = [NSString stringWithString:name];
6762 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6765 title = UCLocalize("NO_SECTION");
6769 PackageTable *table = [[[FilteredPackageTable alloc]
6773 filter:@selector(isVisibleInSection:)
6777 [table setDelegate:delegate_];
6779 [book_ pushPage:table];
6782 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6783 if ((self = [super initWithBook:book]) != nil) {
6784 database_ = database;
6786 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6787 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6789 list_ = [[UITable alloc] initWithFrame:[self bounds]];
6790 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6791 [self addSubview:list_];
6793 UITableColumn *column = [[[UITableColumn alloc]
6794 initWithTitle:UCLocalize("NAME")
6796 width:[self frame].size.width
6799 [list_ setDataSource:self];
6800 [list_ setSeparatorStyle:1];
6801 [list_ addTableColumn:column];
6802 [list_ setDelegate:self];
6803 [list_ setReusesTableCells:YES];
6807 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6811 - (void) reloadData {
6812 NSArray *packages = [database_ packages];
6814 [sections_ removeAllObjects];
6815 [filtered_ removeAllObjects];
6818 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6819 SectionMap sections;
6820 sections.resize(64);
6822 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6826 for (Package *package in packages) {
6827 NSString *name([package section]);
6828 NSString *key(name == nil ? @"" : name);
6833 _profile(SectionsView$reloadData$Section)
6834 section = §ions[key];
6835 if (*section == nil) {
6836 _profile(SectionsView$reloadData$Section$Allocate)
6837 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6842 [*section addToCount];
6844 _profile(SectionsView$reloadData$Filter)
6845 if (![package valid] || ![package visible])
6849 [*section addToRow];
6853 _profile(SectionsView$reloadData$Section)
6854 section = [sections objectForKey:key];
6855 if (section == nil) {
6856 _profile(SectionsView$reloadData$Section$Allocate)
6857 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6858 [sections setObject:section forKey:key];
6863 [section addToCount];
6865 _profile(SectionsView$reloadData$Filter)
6866 if (![package valid] || ![package visible])
6876 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6877 [sections_ addObject:i->second];
6879 [sections_ addObjectsFromArray:[sections allValues]];
6882 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6884 for (Section *section in sections_) {
6885 size_t count([section row]);
6889 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6890 [section setCount:count];
6891 [filtered_ addObject:section];
6898 - (void) resetView {
6900 [self _rightButtonClicked];
6903 - (void) resetViewAnimated:(BOOL)animated {
6904 [list_ resetViewAnimated:animated];
6907 - (void) _rightButtonClicked {
6908 if ((editing_ = !editing_))
6911 [delegate_ updateData];
6912 [book_ reloadTitleForPage:self];
6913 [book_ reloadButtonsForPage:self];
6916 - (NSString *) title {
6917 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS");
6920 - (NSString *) backButtonTitle {
6921 return UCLocalize("SECTIONS");
6924 - (id) rightButtonTitle {
6925 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6928 - (UINavigationButtonStyle) rightButtonStyle {
6929 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6932 - (UIView *) accessoryView {
6938 /* Changes View {{{ */
6939 @interface ChangesView : RVPage {
6940 _transient Database *database_;
6941 NSMutableArray *packages_;
6942 NSMutableArray *sections_;
6947 - (id) initWithBook:(RVBook *)book database:(Database *)database delegate:(id)delegate;
6948 - (void) reloadData;
6952 @implementation ChangesView
6955 [list_ setDelegate:nil];
6956 [list_ setDataSource:nil];
6958 [packages_ release];
6959 [sections_ release];
6964 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6965 NSInteger count([sections_ count]);
6966 return count == 0 ? 1 : count;
6969 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6970 if ([sections_ count] == 0)
6972 return [[sections_ objectAtIndex:section] name];
6975 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6976 if ([sections_ count] == 0)
6978 return [[sections_ objectAtIndex:section] count];
6981 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6982 Section *section([sections_ objectAtIndex:[path section]]);
6983 NSInteger row([path row]);
6984 return [packages_ objectAtIndex:([section row] + row)];
6987 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6988 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6990 cell = [[[PackageCell alloc] init] autorelease];
6991 [cell setPackage:[self packageAtIndexPath:path]];
6995 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6997 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7000 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7001 Package *package([self packageAtIndexPath:path]);
7002 PackageView *view([delegate_ packageView]);
7003 [view setDelegate:delegate_];
7004 [view setPackage:package];
7005 [book_ pushPage:view];
7009 - (void) _leftButtonClicked {
7010 [(CYBook *)book_ update];
7011 [self reloadButtons];
7014 - (void) _rightButtonClicked {
7015 [delegate_ distUpgrade];
7018 - (id) initWithBook:(RVBook *)book database:(Database *)database delegate:(id)delegate {
7019 if ((self = [super initWithBook:book]) != nil) {
7020 database_ = database;
7022 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7023 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7025 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
7026 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7027 [self addSubview:list_];
7029 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
7030 [list_ setDataSource:self];
7031 [list_ setDelegate:self];
7032 //[list_ setSectionListStyle:1];
7034 delegate_ = delegate;
7037 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7041 - (void) _reloadPackages:(NSArray *)packages {
7043 for (Package *package in packages)
7045 [package uninstalled] && [package valid] && [package visible] ||
7046 [package upgradableAndEssential:YES]
7048 [packages_ addObject:package];
7051 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7055 - (void) reloadData {
7056 NSArray *packages = [database_ packages];
7058 [packages_ removeAllObjects];
7059 [sections_ removeAllObjects];
7061 UIProgressHUD *hud([delegate_ addProgressHUD]);
7063 [hud setText:@"Loading Changes"];
7064 NSLog(@"HUD:%@::%@", delegate_, hud);
7065 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7066 [delegate_ removeProgressHUD:hud];
7068 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7069 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7070 Section *section = nil;
7074 bool unseens = false;
7076 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7078 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7079 Package *package = [packages_ objectAtIndex:offset];
7081 BOOL uae = [package upgradableAndEssential:YES];
7087 _profile(ChangesView$reloadData$Remember)
7088 seen = [package seen];
7091 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7096 name = UCLocalize("UNKNOWN");
7098 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7102 _profile(ChangesView$reloadData$Allocate)
7103 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7104 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7105 [sections_ addObject:section];
7109 [section addToCount];
7110 } else if ([package ignored])
7111 [ignored addToCount];
7114 [upgradable addToCount];
7119 CFRelease(formatter);
7122 Section *last = [sections_ lastObject];
7123 size_t count = [last count];
7124 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7125 [sections_ removeLastObject];
7128 if ([ignored count] != 0)
7129 [sections_ insertObject:ignored atIndex:0];
7131 [sections_ insertObject:upgradable atIndex:0];
7134 [self reloadButtons];
7137 - (void) resetViewAnimated:(BOOL)animated {
7138 [list_ resetViewAnimated:animated];
7141 - (NSString *) leftButtonTitle {
7142 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
7145 - (id) rightButtonTitle {
7146 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
7149 - (NSString *) title {
7150 return UCLocalize("CHANGES");
7155 /* Search View {{{ */
7156 @protocol SearchViewDelegate
7157 - (void) showKeyboard:(BOOL)show;
7160 @interface SearchView : RVPage {
7162 UISearchField *field_;
7163 FilteredPackageTable *table_;
7167 - (id) initWithBook:(RVBook *)book database:(Database *)database;
7168 - (void) reloadData;
7172 @implementation SearchView
7175 [field_ setDelegate:nil];
7177 [accessory_ release];
7183 - (void) _showKeyboard:(BOOL)show {
7184 CGSize keysize = [UIKeyboard defaultSize];
7185 CGRect keydown = [book_ pageBounds];
7186 CGRect keyup = keydown;
7187 keyup.size.height -= keysize.height - ButtonBarHeight_;
7189 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7191 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7192 [animation setSignificantRectFields:8];
7195 [animation setStartFrame:keydown];
7196 [animation setEndFrame:keyup];
7198 [animation setStartFrame:keyup];
7199 [animation setEndFrame:keydown];
7202 UIAnimator *animator = [UIAnimator sharedAnimator];
7205 addAnimations:[NSArray arrayWithObjects:animation, nil]
7206 withDuration:(KeyboardTime_ - delay)
7211 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7213 //[delegate_ showKeyboard:show];
7216 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7217 [self _showKeyboard:YES];
7218 [table_ setObject:[field_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7222 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7223 [self _showKeyboard:NO];
7224 [table_ setObject:[field_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7228 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7230 NSString *text([field_ text]);
7231 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7232 [table_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7238 - (void) textFieldClearButtonPressed:(UITextField *)field {
7242 - (void) keyboardInputShouldDelete:(id)input {
7246 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7247 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7251 [field_ resignFirstResponder];
7256 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7257 if ((self = [super initWithBook:book]) != nil) {
7258 CGRect pageBounds = [book_ pageBounds];
7260 table_ = [[FilteredPackageTable alloc]
7264 filter:@selector(isUnfilteredAndSearchedForBy:)
7268 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7269 [self addSubview:table_];
7271 [table_ setShouldHideHeaderInShortLists:NO];
7273 CGRect cnfrect = {{7, 38}, {17, 18}};
7280 area.size.width = [self bounds].size.width - area.origin.x * 2;
7281 area.size.height = [UISearchField defaultHeight];
7283 field_ = [[UISearchField alloc] initWithFrame:area];
7284 [field_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7286 UIFont *font = [UIFont systemFontOfSize:16];
7287 [field_ setFont:font];
7289 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7290 [field_ setDelegate:self];
7292 [field_ setPaddingTop:5];
7294 UITextInputTraits *traits([field_ textInputTraits]);
7295 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7296 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7297 [traits setReturnKeyType:UIReturnKeySearch];
7299 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7301 accessory_ = [[UIView alloc] initWithFrame:accrect];
7302 [accessory_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7303 [accessory_ addSubview:field_];
7305 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7309 - (void) resetViewAnimated:(BOOL)animated {
7310 [table_ resetViewAnimated:animated];
7313 - (void) _reloadData {
7316 - (void) reloadData {
7317 _profile(SearchView$reloadData)
7318 [table_ reloadData];
7321 [table_ resetCursor];
7324 - (UIView *) accessoryView {
7328 - (NSString *) title {
7332 - (NSString *) backButtonTitle {
7333 return UCLocalize("SEARCH");
7336 - (void) setDelegate:(id)delegate {
7337 [table_ setDelegate:delegate];
7338 [super setDelegate:delegate];
7343 /* Settings View {{{ */
7344 @interface SettingsView : RVPage {
7345 _transient Database *database_;
7348 UIPreferencesTable *table_;
7349 _UISwitchSlider *subscribedSwitch_;
7350 _UISwitchSlider *ignoredSwitch_;
7351 UIPreferencesControlTableCell *subscribedCell_;
7352 UIPreferencesControlTableCell *ignoredCell_;
7355 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7359 @implementation SettingsView
7362 [table_ setDataSource:nil];
7365 if (package_ != nil)
7368 [subscribedSwitch_ release];
7369 [ignoredSwitch_ release];
7370 [subscribedCell_ release];
7371 [ignoredCell_ release];
7375 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7376 if (package_ == nil)
7382 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7383 if (package_ == nil)
7396 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7397 if (package_ == nil)
7410 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7411 if (package_ == nil)
7424 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7425 if (package_ == nil)
7428 _UISwitchSlider *slider([cell control]);
7429 BOOL value([slider value] != 0);
7430 NSMutableDictionary *metadata([package_ metadata]);
7433 if (NSNumber *number = [metadata objectForKey:key])
7434 before = [number boolValue];
7438 if (value != before) {
7439 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7441 [delegate_ updateData];
7445 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7446 [self onSomething:cell withKey:@"IsSubscribed"];
7449 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7450 [self onSomething:cell withKey:@"IsIgnored"];
7453 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7454 if (package_ == nil)
7458 case 0: switch (row) {
7460 return subscribedCell_;
7462 return ignoredCell_;
7466 case 1: switch (row) {
7468 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7469 [cell setShowSelection:NO];
7470 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7483 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7484 if ((self = [super initWithBook:book])) {
7485 database_ = database;
7486 name_ = [package retain];
7488 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7489 [self addSubview:table_];
7491 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7492 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7494 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7495 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7497 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7498 [subscribedCell_ setShowSelection:NO];
7499 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7500 [subscribedCell_ setControl:subscribedSwitch_];
7502 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7503 [ignoredCell_ setShowSelection:NO];
7504 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7505 [ignoredCell_ setControl:ignoredSwitch_];
7507 [table_ setDataSource:self];
7512 - (void) resetViewAnimated:(BOOL)animated {
7513 [table_ resetViewAnimated:animated];
7516 - (void) reloadData {
7517 if (package_ != nil)
7518 [package_ autorelease];
7519 package_ = [database_ packageWithName:name_];
7520 if (package_ != nil) {
7522 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7523 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7526 [table_ reloadData];
7529 - (NSString *) title {
7530 return UCLocalize("SETTINGS");
7536 /* Signature View {{{ */
7537 @interface SignatureView : CydiaBrowserView {
7538 _transient Database *database_;
7542 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7546 @implementation SignatureView
7553 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7555 [super webView:sender didClearWindowObject:window forFrame:frame];
7558 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7559 if ((self = [super initWithBook:book]) != nil) {
7560 database_ = database;
7561 package_ = [package retain];
7566 - (void) resetViewAnimated:(BOOL)animated {
7569 - (void) reloadData {
7570 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7576 @interface CydiaViewController : UIViewController {
7581 @implementation CydiaViewController
7583 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7584 return NO; // XXX: return YES;
7589 @interface Cydia : UIApplication <
7590 ConfirmationViewDelegate,
7591 ProgressViewDelegate,
7596 CydiaViewController *root_;
7607 NSMutableArray *essential_;
7608 NSMutableArray *broken_;
7610 Database *database_;
7611 ProgressView *progress_;
7615 UIKeyboard *keyboard_;
7616 UIProgressHUD *hud_;
7618 SectionsView *sections_;
7619 ChangesView *changes_;
7620 ManageView *manage_;
7621 SearchView *search_;
7623 #if RecyclePackageViews
7624 NSMutableArray *details_;
7628 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7629 - (void) setPage:(RVPage *)page;
7633 static _finline void _setHomePage(Cydia *self) {
7634 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeView class]]];
7637 @implementation Cydia
7639 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7644 if ([broken_ count] != 0) {
7645 int count = [broken_ count];
7647 UIActionSheet *sheet = [[[UIActionSheet alloc]
7648 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7649 buttons:[NSArray arrayWithObjects:
7650 UCLocalize("FORCIBLY_CLEAR"),
7651 UCLocalize("TEMPORARY_IGNORE"),
7653 defaultButtonIndex:0
7658 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7660 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7661 [sheet popupAlertAnimated:YES];
7662 } else if (!Ignored_ && [essential_ count] != 0) {
7663 int count = [essential_ count];
7665 UIActionSheet *sheet = [[[UIActionSheet alloc]
7666 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7667 buttons:[NSArray arrayWithObjects:
7668 UCLocalize("UPGRADE_ESSENTIAL"),
7669 UCLocalize("COMPLETE_UPGRADE"),
7670 UCLocalize("TEMPORARY_IGNORE"),
7672 defaultButtonIndex:0
7677 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7679 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7680 [sheet popupAlertAnimated:YES];
7684 - (void) _saveConfig {
7687 NSString *error(nil);
7688 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7690 NSError *error(nil);
7691 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7692 NSLog(@"failure to save metadata data: %@", error);
7695 NSLog(@"failure to serialize metadata: %@", error);
7703 - (void) _updateData {
7706 /* XXX: this is just stupid */
7707 if (tag_ != 1 && sections_ != nil)
7708 [sections_ reloadData];
7709 if (tag_ != 2 && changes_ != nil)
7710 [changes_ reloadData];
7711 if (tag_ != 4 && search_ != nil)
7712 [search_ reloadData];
7717 - (void) _reloadData {
7720 static bool loaded(false);
7721 UIProgressHUD *hud([self addProgressHUD]);
7722 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7724 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7727 [self removeProgressHUD:hud];
7731 [essential_ removeAllObjects];
7732 [broken_ removeAllObjects];
7734 NSArray *packages([database_ packages]);
7735 for (Package *package in packages) {
7737 [broken_ addObject:package];
7738 if ([package upgradableAndEssential:NO]) {
7739 if ([package essential])
7740 [essential_ addObject:package];
7746 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7747 [[[toolbar_ items] objectAtIndex:2] setBadgeValue:badge];
7748 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7749 [[[toolbar_ items] objectAtIndex:2] setAnimatedBadge:YES];
7750 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7751 [self setApplicationBadge:badge];
7753 [self setApplicationBadgeString:badge];
7755 [[[toolbar_ items] objectAtIndex:2] setBadgeValue:nil];
7756 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7757 [[[toolbar_ items] objectAtIndex:2] setAnimatedBadge:NO];
7758 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7759 [self removeApplicationBadge];
7760 else // XXX: maybe use setApplicationBadgeString also?
7761 [self setApplicationIconBadgeNumber:0];
7765 [[[toolbar_ items] objectAtIndex:3] setBadgeValue:nil];
7769 if (loaded || ManualRefresh) loaded:
7774 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
7776 if (update != nil) {
7777 NSTimeInterval interval([update timeIntervalSinceNow]);
7778 if (interval <= 0 && interval > -(15*60))
7782 [book_ setUpdate:update];
7786 - (void) updateData {
7787 [database_ setVisible];
7796 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7797 _assert(file != NULL);
7799 for (NSString *key in [Sources_ allKeys]) {
7800 NSDictionary *source([Sources_ objectForKey:key]);
7802 fprintf(file, "%s %s %s\n",
7803 [[source objectForKey:@"Type"] UTF8String],
7804 [[source objectForKey:@"URI"] UTF8String],
7805 [[source objectForKey:@"Distribution"] UTF8String]
7814 detachNewThreadSelector:@selector(update_)
7817 title:UCLocalize("UPDATING_SOURCES")
7821 - (void) reloadData {
7822 @synchronized (self) {
7823 if (confirm_ == nil)
7829 pkgProblemResolver *resolver = [database_ resolver];
7831 resolver->InstallProtect();
7832 if (!resolver->Resolve(true))
7836 - (void) popUpBook:(RVBook *)book {
7837 [underlay_ popSubview:book];
7840 - (CGRect) popUpBounds {
7841 return [underlay_ bounds];
7845 if (![database_ prepare])
7848 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7849 [confirm_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7850 [confirm_ setDelegate:self];
7852 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7853 [page setDelegate:self];
7855 [confirm_ setPage:page];
7856 [self popUpBook:confirm_];
7862 @synchronized (self) {
7867 - (void) clearPackage:(Package *)package {
7868 @synchronized (self) {
7875 - (void) installPackages:(NSArray *)packages {
7876 @synchronized (self) {
7877 for (Package *package in packages)
7884 - (void) installPackage:(Package *)package {
7885 @synchronized (self) {
7892 - (void) removePackage:(Package *)package {
7893 @synchronized (self) {
7900 - (void) distUpgrade {
7901 @synchronized (self) {
7902 if (![database_ upgrade])
7909 [self slideUp:[[[UIActionSheet alloc]
7911 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7912 defaultButtonIndex:1
7919 @synchronized (self) {
7922 if (confirm_ != nil) {
7930 [overlay_ removeFromSuperview];
7934 detachNewThreadSelector:@selector(perform)
7937 title:UCLocalize("RUNNING")
7941 - (void) progressViewIsComplete:(ProgressView *)progress {
7942 if (confirm_ != nil) {
7943 [underlay_ addSubview:overlay_];
7944 [confirm_ popFromSuperviewAnimated:NO];
7950 - (void) setPage:(RVPage *)page {
7951 [page resetViewAnimated:NO];
7952 [page setDelegate:self];
7953 [book_ setPage:page];
7956 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7957 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7958 [browser loadURL:url];
7962 - (SectionsView *) sectionsView {
7963 if (sections_ == nil)
7964 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7968 - (ChangesView *) changesView {
7969 if (changes_ == nil)
7970 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_ delegate:self];
7974 - (ManageView *) manageView {
7976 manage_ = (ManageView *) [[self
7977 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7978 withClass:[ManageView class]
7983 - (SearchView *) searchView {
7985 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7989 - (void) tabBar:(UITabBar *)sender didSelectItem:(UITabBarItem *)item {
7990 int tag = [item tag];
7992 [book_ resetViewAnimated:YES];
7994 } else if (tag_ == 1)
7995 [[self sectionsView] resetView];
7998 case 0: _setHomePage(self); break;
8000 case 1: [self setPage:[self sectionsView]]; break;
8001 case 2: [self setPage:[self changesView]]; break;
8002 case 3: [self setPage:[self manageView]]; break;
8003 case 4: [self setPage:[self searchView]]; break;
8011 - (void) askForSettings {
8012 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
8014 CYActionSheet *role([[[CYActionSheet alloc]
8015 initWithTitle:UCLocalize("WHO_ARE_YOU")
8016 buttons:[NSArray arrayWithObjects:
8017 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
8018 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
8019 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
8021 defaultButtonIndex:-1
8024 [role setBodyText:UCLocalize("ROLE_EX")];
8026 int button([role yieldToPopupAlertAnimated:YES]);
8029 case 1: Role_ = @"User"; break;
8030 case 2: Role_ = @"Hacker"; break;
8031 case 3: Role_ = @"Developer"; break;
8036 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8040 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8047 - (void) setPackageView:(PackageView *)view {
8049 [view setPackage:nil];
8050 #if RecyclePackageViews
8051 if ([details_ count] < 3)
8052 [details_ addObject:view];
8057 - (PackageView *) _packageView {
8058 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
8061 - (PackageView *) packageView {
8062 #if RecyclePackageViews
8064 size_t count([details_ count]);
8067 view = [self _packageView];
8069 [details_ addObject:[self _packageView]];
8071 view = [[[details_ lastObject] retain] autorelease];
8072 [details_ removeLastObject];
8079 return [self _packageView];
8083 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
8084 NSString *context([sheet context]);
8086 if ([context isEqualToString:@"missing"])
8088 else if ([context isEqualToString:@"cancel"]) {
8105 @synchronized (self) {
8110 [[[toolbar_ items] objectAtIndex:3] setBadgeValue:UCLocalize("Q_D")];
8114 if (confirm_ != nil) {
8119 } else if ([context isEqualToString:@"fixhalf"]) {
8122 @synchronized (self) {
8123 for (Package *broken in broken_) {
8126 NSString *id = [broken id];
8127 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8128 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8129 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8130 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8139 [broken_ removeAllObjects];
8147 } else if ([context isEqualToString:@"upgrade"]) {
8150 @synchronized (self) {
8151 for (Package *essential in essential_)
8152 [essential install];
8174 - (void) system:(NSString *)command { _pooled
8175 system([command UTF8String]);
8178 - (void) applicationWillSuspend {
8180 [super applicationWillSuspend];
8183 - (void) applicationSuspend:(__GSEvent *)event {
8184 if (hud_ == nil && ![progress_ isRunning])
8185 [super applicationSuspend:event];
8188 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8190 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8193 - (void) _setSuspended:(BOOL)value {
8195 [super _setSuspended:value];
8198 - (UIProgressHUD *) addProgressHUD {
8199 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8200 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8202 [window_ setUserInteractionEnabled:NO];
8204 [progress_ addSubview:hud];
8208 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8210 [hud removeFromSuperview];
8211 [window_ setUserInteractionEnabled:YES];
8214 - (RVPage *) pageForPackage:(NSString *)name {
8215 if (Package *package = [database_ packageWithName:name]) {
8216 PackageView *view([self packageView]);
8217 [view setPackage:package];
8220 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8221 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8222 return [self _pageForURL:url withClass:[CydiaBrowserView class]];
8226 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8230 NSString *href([url absoluteString]);
8231 if ([href hasPrefix:@"apptapp://package/"])
8232 return [self pageForPackage:[href substringFromIndex:18]];
8234 NSString *scheme([[url scheme] lowercaseString]);
8235 if (![scheme isEqualToString:@"cydia"])
8237 NSString *path([url absoluteString]);
8238 if ([path length] < 8)
8240 path = [path substringFromIndex:8];
8241 if (![path hasPrefix:@"/"])
8242 path = [@"/" stringByAppendingString:path];
8244 if ([path isEqualToString:@"/add-source"])
8245 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8246 else if ([path isEqualToString:@"/storage"])
8247 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8248 else if ([path isEqualToString:@"/sources"])
8249 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8250 else if ([path isEqualToString:@"/packages"])
8251 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8252 else if ([path hasPrefix:@"/url/"])
8253 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8254 else if ([path hasPrefix:@"/launch/"])
8255 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8256 else if ([path hasPrefix:@"/package-settings/"])
8257 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8258 else if ([path hasPrefix:@"/package-signature/"])
8259 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8260 else if ([path hasPrefix:@"/package/"])
8261 return [self pageForPackage:[path substringFromIndex:9]];
8262 else if ([path hasPrefix:@"/files/"]) {
8263 NSString *name = [path substringFromIndex:7];
8265 if (Package *package = [database_ packageWithName:name]) {
8266 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8267 [files setPackage:package];
8275 - (void) applicationOpenURL:(NSURL *)url {
8276 [super applicationOpenURL:url];
8278 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8279 [self setPage:page];
8281 [toolbar_ setSelectedItem:(tag_ == -1 ? nil : [items_ objectAtIndex:tag_])];
8285 - (void) applicationDidFinishLaunching:(id)unused {
8286 [BrowserView _initialize];
8288 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8290 Font12_ = [[UIFont systemFontOfSize:12] retain];
8291 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8292 Font14_ = [[UIFont systemFontOfSize:14] retain];
8293 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8294 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8298 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8299 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8301 UIScreen *screen([UIScreen mainScreen]);
8303 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8304 [window_ orderFront:self];
8305 [window_ makeKey:self];
8306 [window_ setHidden:NO];
8308 root_ = [[CydiaViewController alloc] init];
8309 [window_ addSubview:[root_ view]];
8311 database_ = [Database sharedInstance];
8313 progress_ = [[ProgressView alloc] initWithFrame:[[root_ view] bounds] database:database_ delegate:self];
8314 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8315 [[root_ view] addSubview:progress_];
8317 [database_ setDelegate:progress_];
8319 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8320 [underlay_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8321 [progress_ setContentView:underlay_];
8323 [progress_ resetView];
8326 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8327 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8328 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8329 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8330 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8331 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8332 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8333 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8334 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8337 [self setIdleTimerDisabled:YES];
8339 hud_ = [self addProgressHUD];
8340 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8341 [self setStatusBarShowsProgress:YES];
8343 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8345 [self setStatusBarShowsProgress:NO];
8346 [self removeProgressHUD:hud_];
8349 if (ExecFork() == 0) {
8350 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8351 perror("launchctl stop");
8358 [self askForSettings];
8361 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
8362 [overlay_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8364 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8366 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
8367 0, 0, screenrect.size.width, screenrect.size.height - 48
8368 ) database:database_];
8370 [book_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8371 [overlay_ addSubview:book_];
8373 [book_ setDelegate:self];
8375 items_ = [[NSArray arrayWithObjects:
8376 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
8377 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:1] autorelease],
8378 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:2] autorelease],
8379 [[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:3] autorelease],
8380 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:4] autorelease],
8383 toolbar_ = [[UITabBar alloc]
8384 initWithFrame:CGRectMake(
8385 0, screenrect.size.height - ButtonBarHeight_,
8386 screenrect.size.width, ButtonBarHeight_
8390 [toolbar_ setItems:items_];
8392 [toolbar_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
8393 [overlay_ addSubview:toolbar_];
8395 [toolbar_ setDelegate:self];
8397 /*int buttons[5] = {1, 2, 3, 4, 5};
8398 [toolbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
8399 [toolbar_ showButtonGroup:0 withDuration:0];
8401 for (int i = 0; i != 5; ++i) {
8402 UIView *button([toolbar_ viewWithTag:(i + 1)]);
8404 [button setFrame:CGRectMake(
8405 i * (screenrect.size.width / 5) + (screenrect.size.width / 5 - ButtonBarWidth_) / 2, 1,
8406 ButtonBarWidth_, ButtonBarHeight_
8409 [button setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8412 [toolbar_ setSelectedItem:[items_ objectAtIndex:0]];
8414 [UIKeyboard initImplementationNow];
8415 /*CGSize keysize = [UIKeyboard defaultSize];
8416 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8417 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8418 [overlay_ addSubview:keyboard_];*/
8420 [underlay_ addSubview:overlay_];
8424 #if RecyclePackageViews
8425 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8426 [details_ addObject:[self _packageView]];
8427 [details_ addObject:[self _packageView]];
8435 - (void) showKeyboard:(BOOL)show {
8436 CGSize keysize([UIKeyboard defaultSize]);
8437 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8438 CGRect keyup(keydown);
8439 keyup.origin.y -= keysize.height;
8441 UIFrameAnimation *animation([[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease]);
8442 [animation setSignificantRectFields:2];
8445 [animation setStartFrame:keydown];
8446 [animation setEndFrame:keyup];
8447 [keyboard_ activate];
8449 [animation setStartFrame:keyup];
8450 [animation setEndFrame:keydown];
8451 [keyboard_ deactivate];
8454 [[UIAnimator sharedAnimator]
8455 addAnimations:[NSArray arrayWithObjects:animation, nil]
8456 withDuration:KeyboardTime_
8461 - (void) slideUp:(UIActionSheet *)alert {
8462 [alert setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8463 [alert presentSheetInView:overlay_];
8469 id Alloc_(id self, SEL selector) {
8470 id object = alloc_(self, selector);
8471 lprintf("[%s]A-%p\n", self->isa->name, object);
8476 id Dealloc_(id self, SEL selector) {
8477 id object = dealloc_(self, selector);
8478 lprintf("[%s]D-%p\n", self->isa->name, object);
8482 Class $WebDefaultUIKitDelegate;
8484 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8485 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8486 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8487 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8490 int main(int argc, char *argv[]) { _pooled
8493 if (Class $UIDevice = objc_getClass("UIDevice")) {
8494 UIDevice *device([$UIDevice currentDevice]);
8495 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8499 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8501 /* Library Hacks {{{ */
8502 class_addMethod(objc_getClass("WebScriptObject"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &WebScriptObject$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8503 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8505 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8506 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8507 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8508 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8509 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8512 /* Set Locale {{{ */
8513 Locale_ = CFLocaleCopyCurrent();
8514 Languages_ = [NSLocale preferredLanguages];
8515 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8516 //NSLog(@"%@", [Languages_ description]);
8519 if (Languages_ == nil || [Languages_ count] == 0)
8520 // XXX: consider just setting to C and then falling through?
8523 lang = [[Languages_ objectAtIndex:0] UTF8String];
8524 setenv("LANG", lang, true);
8527 //std::setlocale(LC_ALL, lang);
8528 NSLog(@"Setting Language: %s", lang);
8531 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8533 /* Parse Arguments {{{ */
8534 bool substrate(false);
8540 for (int argi(1); argi != argc; ++argi)
8541 if (strcmp(argv[argi], "--") == 0) {
8543 argv[argi] = argv[0];
8549 for (int argi(1); argi != arge; ++argi)
8550 if (strcmp(args[argi], "--substrate") == 0)
8553 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8557 App_ = [[NSBundle mainBundle] bundlePath];
8558 Home_ = NSHomeDirectory();
8564 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8565 alloc_ = alloc->method_imp;
8566 alloc->method_imp = (IMP) &Alloc_;*/
8568 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8569 dealloc_ = dealloc->method_imp;
8570 dealloc->method_imp = (IMP) &Dealloc_;*/
8572 /* System Information {{{ */
8576 size = sizeof(maxproc);
8577 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8578 perror("sysctlbyname(\"kern.maxproc\", ?)");
8579 else if (maxproc < 64) {
8581 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8582 perror("sysctlbyname(\"kern.maxproc\", #)");
8585 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8586 char *osversion = new char[size];
8587 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8588 perror("sysctlbyname(\"kern.osversion\", ?)");
8590 System_ = [NSString stringWithUTF8String:osversion];
8592 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8593 char *machine = new char[size];
8594 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8595 perror("sysctlbyname(\"hw.machine\", ?)");
8599 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8600 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8601 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8602 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8606 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8607 NSData *data((NSData *) ecid);
8608 size_t length([data length]);
8609 uint8_t bytes[length];
8610 [data getBytes:bytes];
8611 char string[length * 2 + 1];
8612 for (size_t i(0); i != length; ++i)
8613 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8614 ChipID_ = [NSString stringWithUTF8String:string];
8618 IOObjectRelease(service);
8622 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8624 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8625 Build_ = [system objectForKey:@"ProductBuildVersion"];
8626 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8627 Product_ = [info objectForKey:@"SafariProductVersion"];
8628 Safari_ = [info objectForKey:@"CFBundleVersion"];
8631 /* Load Database {{{ */
8633 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8635 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8638 if (Metadata_ == NULL)
8639 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8641 Settings_ = [Metadata_ objectForKey:@"Settings"];
8643 Packages_ = [Metadata_ objectForKey:@"Packages"];
8644 Sections_ = [Metadata_ objectForKey:@"Sections"];
8645 Sources_ = [Metadata_ objectForKey:@"Sources"];
8647 Token_ = [Metadata_ objectForKey:@"Token"];
8650 if (Settings_ != nil)
8651 Role_ = [Settings_ objectForKey:@"Role"];
8653 if (Packages_ == nil) {
8654 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8655 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8658 if (Sections_ == nil) {
8659 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8660 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8663 if (Sources_ == nil) {
8664 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8665 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8670 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8673 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8675 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8676 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
8677 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8678 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8679 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8680 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8682 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8684 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8685 unlink("/tmp/.cydia.fw");
8687 } else if (access("/User", F_OK) != 0 || version < 2) {
8690 system("/usr/libexec/cydia/firmware.sh");
8694 _assert([[NSFileManager defaultManager]
8695 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8696 withIntermediateDirectories:YES
8701 if (access("/tmp/cydia.chk", F_OK) == 0) {
8702 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8703 _assert(errno == ENOENT);
8704 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8705 _assert(errno == ENOENT);
8708 /* APT Initialization {{{ */
8709 _assert(pkgInitConfig(*_config));
8710 _assert(pkgInitSystem(*_config, _system));
8713 _config->Set("APT::Acquire::Translation", lang);
8714 _config->Set("Acquire::http::Timeout", 15);
8715 _config->Set("Acquire::http::MaxParallel", 3);
8717 /* Color Choices {{{ */
8718 space_ = CGColorSpaceCreateDeviceRGB();
8720 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8721 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8722 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8723 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8724 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8725 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8726 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8727 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8728 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8730 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8731 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8733 /* UIKit Configuration {{{ */
8734 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8735 if ($GSFontSetUseLegacyFontMetrics != NULL)
8736 $GSFontSetUseLegacyFontMetrics(YES);
8738 // XXX: I have a feeling this was important
8739 //UIKeyboardDisableAutomaticAppearance();
8742 Colon_ = UCLocalize("COLON_DELIMITED");
8743 Error_ = UCLocalize("ERROR");
8744 Warning_ = UCLocalize("WARNING");
8747 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8749 CGColorSpaceRelease(space_);