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 setTitle:title];
296 [self setDelegate:self];
297 for (NSString *button in buttons) [self addButtonWithTitle:button];
298 [self setCancelButtonIndex:index];
302 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
303 button_ = buttonIndex + 1;
307 [self dismissWithClickedButtonIndex:-1 animated:YES];
310 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
313 NSRunLoop *loop([NSRunLoop currentRunLoop]);
314 NSDate *future([NSDate distantFuture]);
315 while (button_ == 0 && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
321 /* NSForcedOrderingSearch doesn't work on the iPhone */
322 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
323 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
324 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
326 /* Information Dictionaries {{{ */
327 @interface NSMutableArray (Cydia)
328 - (void) addInfoDictionary:(NSDictionary *)info;
331 @implementation NSMutableArray (Cydia)
333 - (void) addInfoDictionary:(NSDictionary *)info {
334 [self addObject:info];
339 @interface NSMutableDictionary (Cydia)
340 - (void) addInfoDictionary:(NSDictionary *)info;
343 @implementation NSMutableDictionary (Cydia)
345 - (void) addInfoDictionary:(NSDictionary *)info {
346 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
351 /* Pop Transitions {{{ */
352 @interface PopTransitionView : UITransitionView {
357 @implementation PopTransitionView
359 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
360 if (from != nil && to == nil)
361 [self removeFromSuperview];
366 @implementation UIView (PopUpView)
368 - (void) popFromSuperviewAnimated:(BOOL)animated {
369 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
372 - (void) popSubview:(UIView *)view {
373 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
374 [transition setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
375 [self addSubview:transition];
377 [transition setDelegate:transition];
379 UIView *blank([[[UIView alloc] initWithFrame:[transition bounds]] autorelease]);
380 [blank setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
382 [transition transition:UITransitionNone toView:blank];
383 [transition transition:UITransitionPushFromBottom toView:view];
389 #define lprintf(args...) fprintf(stderr, args)
392 #define TraceLogging (1 && !ForRelease)
393 #define HistogramInsertionSort (0 && !ForRelease)
394 #define ProfileTimes (0 && !ForRelease)
395 #define ForSaurik (0 && !ForRelease)
396 #define LogBrowser (0 && !ForRelease)
397 #define TrackResize (0 && !ForRelease)
398 #define ManualRefresh (0 && !ForRelease)
399 #define ShowInternals (0 && !ForRelease)
400 #define IgnoreInstall (0 && !ForRelease)
401 #define RecycleWebViews 0
402 #define RecyclePackageViews (1 && ForRelease)
403 #define AlwaysReload (1 && !ForRelease)
407 #define _trace(args...)
412 #define _profile(name) {
415 #define PrintTimes() do {} while (false)
419 typedef uint32_t (*SKRadixFunction)(id, void *);
421 @interface NSMutableArray (Radix)
422 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
423 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
431 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
432 struct RadixItem_ *lhs(swap), *rhs(swap + count);
434 static const size_t width = 32;
435 static const size_t bits = 11;
436 static const size_t slots = 1 << bits;
437 static const size_t passes = (width + (bits - 1)) / bits;
439 size_t *hist(new size_t[slots]);
441 for (size_t pass(0); pass != passes; ++pass) {
442 memset(hist, 0, sizeof(size_t) * slots);
444 for (size_t i(0); i != count; ++i) {
445 uint32_t key(lhs[i].key);
447 key &= _not(uint32_t) >> width - bits;
452 for (size_t i(0); i != slots; ++i) {
453 size_t local(offset);
458 for (size_t i(0); i != count; ++i) {
459 uint32_t key(lhs[i].key);
461 key &= _not(uint32_t) >> width - bits;
462 rhs[hist[key]++] = lhs[i];
465 RadixItem_ *tmp(lhs);
472 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
473 for (size_t i(0); i != count; ++i)
474 [values addObject:[self objectAtIndex:lhs[i].index]];
475 [self setArray:values];
480 @implementation NSMutableArray (Radix)
482 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
483 size_t count([self count]);
488 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
489 [invocation setSelector:selector];
490 [invocation setArgument:&object atIndex:2];
492 /* XXX: this is an unsafe optimization of doomy hell */
493 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
494 _assert(method != NULL);
495 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
496 _assert(imp != NULL);
499 struct RadixItem_ *swap(new RadixItem_[count * 2]);
501 for (size_t i(0); i != count; ++i) {
502 RadixItem_ &item(swap[i]);
505 id object([self objectAtIndex:i]);
508 [invocation setTarget:object];
510 [invocation getReturnValue:&item.key];
512 item.key = imp(object, selector, object);
516 RadixSort_(self, count, swap);
519 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
520 size_t count([self count]);
521 struct RadixItem_ *swap(new RadixItem_[count * 2]);
523 for (size_t i(0); i != count; ++i) {
524 RadixItem_ &item(swap[i]);
527 id object([self objectAtIndex:i]);
528 item.key = function(object, argument);
531 RadixSort_(self, count, swap);
536 /* Insertion Sort {{{ */
538 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
539 const char *ptr = (const char *)list;
541 CFIndex half = count / 2;
542 const char *probe = ptr + elementSize * half;
543 CFComparisonResult cr = comparator(element, probe, context);
544 if (0 == cr) return (probe - (const char *)list) / elementSize;
545 ptr = (cr < 0) ? ptr : probe + elementSize;
546 count = (cr < 0) ? half : (half + (count & 1) - 1);
548 return (ptr - (const char *)list) / elementSize;
551 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
552 const char *ptr = (const char *)list;
554 CFIndex half = count / 2;
555 const char *probe = ptr + elementSize * half;
556 CFComparisonResult cr = comparator(element, probe, context);
557 if (0 == cr) return (probe - (const char *)list) / elementSize;
558 ptr = (cr < 0) ? ptr : probe + elementSize;
559 count = (cr < 0) ? half : (half + (count & 1) - 1);
561 return (ptr - (const char *)list) / elementSize;
564 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
565 if (range.length == 0)
567 const void **values(new const void *[range.length]);
568 CFArrayGetValues(array, range, values);
570 #if HistogramInsertionSort
571 uint32_t total(0), *offsets(new uint32_t[range.length]);
574 for (CFIndex index(1); index != range.length; ++index) {
575 const void *value(values[index]);
576 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
577 CFIndex correct(index);
578 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
581 if (correct != index) {
582 size_t offset(index - correct);
583 #if HistogramInsertionSort
587 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
589 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
590 values[correct] = value;
594 CFArrayReplaceValues(array, range, values, range.length);
597 #if HistogramInsertionSort
598 for (CFIndex index(0); index != range.length; ++index)
599 if (offsets[index] != 0)
600 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
601 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
608 /* Apple Bug Fixes {{{ */
609 @implementation UIWebDocumentView (Cydia)
611 - (void) _setScrollerOffset:(CGPoint)offset {
612 UIScroller *scroller([self _scroller]);
614 CGSize size([scroller contentSize]);
615 CGSize bounds([scroller bounds].size);
618 max.x = size.width - bounds.width;
619 max.y = size.height - bounds.height;
627 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
628 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
630 [scroller setOffset:offset];
636 NSUInteger WebScriptObject$countByEnumeratingWithState$objects$count$(WebScriptObject *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
637 size_t length([self count] - state->state);
640 else if (length > count)
642 for (size_t i(0); i != length; ++i)
643 objects[i] = [self objectAtIndex:state->state++];
644 state->itemsPtr = objects;
645 state->mutationsPtr = (unsigned long *) self;
649 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
650 size_t length([self length] - state->state);
653 else if (length > count)
655 for (size_t i(0); i != length; ++i)
656 objects[i] = [self item:state->state++];
657 state->itemsPtr = objects;
658 state->mutationsPtr = (unsigned long *) self;
662 @interface NSString (UIKit)
663 - (NSString *) stringByAddingPercentEscapes;
666 /* Cydia NSString Additions {{{ */
667 @interface NSString (Cydia)
668 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
669 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
670 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
671 - (NSComparisonResult) compareByPath:(NSString *)other;
672 - (NSString *) stringByCachingURLWithCurrentCDN;
673 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
676 @implementation NSString (Cydia)
678 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
679 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
682 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
683 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
684 memcpy(data, bytes, length);
685 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
688 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
689 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
692 - (NSComparisonResult) compareByPath:(NSString *)other {
693 NSString *prefix = [self commonPrefixWithString:other options:0];
694 size_t length = [prefix length];
696 NSRange lrange = NSMakeRange(length, [self length] - length);
697 NSRange rrange = NSMakeRange(length, [other length] - length);
699 lrange = [self rangeOfString:@"/" options:0 range:lrange];
700 rrange = [other rangeOfString:@"/" options:0 range:rrange];
702 NSComparisonResult value;
704 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
705 value = NSOrderedSame;
706 else if (lrange.location == NSNotFound)
707 value = NSOrderedAscending;
708 else if (rrange.location == NSNotFound)
709 value = NSOrderedDescending;
711 value = NSOrderedSame;
713 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
714 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
715 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
716 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
718 NSComparisonResult result = [lpath compare:rpath];
719 return result == NSOrderedSame ? value : result;
722 - (NSString *) stringByCachingURLWithCurrentCDN {
724 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
725 withString:@"://cache.cydia.saurik.com/"
729 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
730 return [(id)CFURLCreateStringByAddingPercentEscapes(
735 kCFStringEncodingUTF8
742 /* C++ NSString Wrapper Cache {{{ */
749 _finline void clear_() {
750 if (cache_ != NULL) {
757 _finline bool empty() const {
761 _finline size_t size() const {
765 _finline char *data() const {
769 _finline void clear() {
774 _finline CYString() :
781 _finline ~CYString() {
785 void operator =(const CYString &rhs) {
789 if (rhs.cache_ == nil)
792 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
795 void set(apr_pool_t *pool, const char *data, size_t size) {
801 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
802 memcpy(temp, data, size);
809 _finline void set(apr_pool_t *pool, const char *data) {
810 set(pool, data, data == NULL ? 0 : strlen(data));
813 _finline void set(apr_pool_t *pool, const std::string &rhs) {
814 set(pool, rhs.data(), rhs.size());
817 bool operator ==(const CYString &rhs) const {
818 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
821 operator CFStringRef() {
822 if (cache_ == NULL) {
825 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
827 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
831 _finline operator id() {
832 return (NSString *) static_cast<CFStringRef>(*this);
836 /* C++ NSString Algorithm Adapters {{{ */
838 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
841 struct NSStringMapHash :
842 std::unary_function<NSString *, size_t>
844 _finline size_t operator ()(NSString *value) const {
845 return CFStringHashNSString((CFStringRef) value);
849 struct NSStringMapLess :
850 std::binary_function<NSString *, NSString *, bool>
852 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
853 return [lhs compare:rhs] == NSOrderedAscending;
857 struct NSStringMapEqual :
858 std::binary_function<NSString *, NSString *, bool>
860 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
861 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
862 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
863 //[lhs isEqualToString:rhs];
868 /* Perl-Compatible RegEx {{{ */
878 Pcre(const char *regex) :
883 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
886 lprintf("%d:%s\n", offset, error);
890 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
891 matches_ = new int[(capture_ + 1) * 3];
899 NSString *operator [](size_t match) {
900 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
903 bool operator ()(NSString *data) {
904 // XXX: length is for characters, not for bytes
905 return operator ()([data UTF8String], [data length]);
908 bool operator ()(const char *data, size_t size) {
910 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
914 /* Mime Addresses {{{ */
915 @interface Address : NSObject {
921 - (NSString *) address;
923 - (void) setAddress:(NSString *)address;
925 + (Address *) addressWithString:(NSString *)string;
926 - (Address *) initWithString:(NSString *)string;
929 @implementation Address
938 - (NSString *) name {
942 - (NSString *) address {
946 - (void) setAddress:(NSString *)address {
948 [address_ autorelease];
952 address_ = [address retain];
955 + (Address *) addressWithString:(NSString *)string {
956 return [[[Address alloc] initWithString:string] autorelease];
959 + (NSArray *) _attributeKeys {
960 return [NSArray arrayWithObjects:@"address", @"name", nil];
963 - (NSArray *) attributeKeys {
964 return [[self class] _attributeKeys];
967 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
968 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
971 - (Address *) initWithString:(NSString *)string {
972 if ((self = [super init]) != nil) {
973 const char *data = [string UTF8String];
974 size_t size = [string length];
976 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
978 if (address_r(data, size)) {
979 name_ = [address_r[1] retain];
980 address_ = [address_r[2] retain];
982 name_ = [string retain];
990 /* CoreGraphics Primitives {{{ */
1001 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1004 Set(space, red, green, blue, alpha);
1009 CGColorRelease(color_);
1016 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1018 float color[] = {red, green, blue, alpha};
1019 color_ = CGColorCreate(space, color);
1022 operator CGColorRef() {
1028 /* Random Global Variables {{{ */
1029 static const int PulseInterval_ = 50000;
1030 static const int ButtonBarWidth_ = 60;
1031 static const int ButtonBarHeight_ = 48;
1032 static const float KeyboardTime_ = 0.3f;
1035 static NSArray *Finishes_;
1037 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1038 #define NotifyConfig_ "/etc/notify.conf"
1040 static bool Queuing_;
1042 static CGColor Blue_;
1043 static CGColor Blueish_;
1044 static CGColor Black_;
1045 static CGColor Off_;
1046 static CGColor White_;
1047 static CGColor Gray_;
1048 static CGColor Green_;
1049 static CGColor Purple_;
1050 static CGColor Purplish_;
1052 static UIColor *InstallingColor_;
1053 static UIColor *RemovingColor_;
1055 static NSString *App_;
1056 static NSString *Home_;
1058 static BOOL Advanced_;
1059 static BOOL Ignored_;
1061 static UIFont *Font12_;
1062 static UIFont *Font12Bold_;
1063 static UIFont *Font14_;
1064 static UIFont *Font18Bold_;
1065 static UIFont *Font22Bold_;
1067 static const char *Machine_ = NULL;
1068 static const NSString *System_ = NULL;
1069 static const NSString *SerialNumber_ = nil;
1070 static const NSString *ChipID_ = nil;
1071 static const NSString *Token_ = nil;
1072 static const NSString *UniqueID_ = nil;
1073 static const NSString *Build_ = nil;
1074 static const NSString *Product_ = nil;
1075 static const NSString *Safari_ = nil;
1077 static CFLocaleRef Locale_;
1078 static NSArray *Languages_;
1079 static CGColorSpaceRef space_;
1081 static bool reload_;
1083 static NSDictionary *SectionMap_;
1084 static NSMutableDictionary *Metadata_;
1085 static _transient NSMutableDictionary *Settings_;
1086 static _transient NSString *Role_;
1087 static _transient NSMutableDictionary *Packages_;
1088 static _transient NSMutableDictionary *Sections_;
1089 static _transient NSMutableDictionary *Sources_;
1090 static bool Changed_;
1091 static NSDate *now_;
1093 static bool IsWildcat_;
1096 static NSMutableArray *Documents_;
1100 /* Display Helpers {{{ */
1101 inline float Interpolate(float begin, float end, float fraction) {
1102 return (end - begin) * fraction + begin;
1105 /* XXX: localize this! */
1106 NSString *SizeString(double size) {
1107 bool negative = size < 0;
1112 while (size > 1024) {
1117 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1119 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1122 static _finline CFStringRef CFCString(const char *value) {
1123 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1126 const char *StripVersion_(const char *version) {
1127 const char *colon(strchr(version, ':'));
1129 version = colon + 1;
1133 CFStringRef StripVersion(const char *version) {
1134 const char *colon(strchr(version, ':'));
1136 version = colon + 1;
1137 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1139 return CFCString(version);
1142 NSString *LocalizeSection(NSString *section) {
1143 static Pcre title_r("^(.*?) \\((.*)\\)$");
1144 if (title_r(section)) {
1145 NSString *parent(title_r[1]);
1146 NSString *child(title_r[2]);
1148 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1149 LocalizeSection(parent),
1150 LocalizeSection(child)
1154 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1157 NSString *Simplify(NSString *title) {
1158 const char *data = [title UTF8String];
1159 size_t size = [title length];
1161 static Pcre square_r("^\\[(.*)\\]$");
1162 if (square_r(data, size))
1163 return Simplify(square_r[1]);
1165 static Pcre paren_r("^\\((.*)\\)$");
1166 if (paren_r(data, size))
1167 return Simplify(paren_r[1]);
1169 static Pcre title_r("^(.*?) \\((.*)\\)$");
1170 if (title_r(data, size))
1171 return Simplify(title_r[1]);
1177 NSString *GetLastUpdate() {
1178 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1181 return UCLocalize("NEVER_OR_UNKNOWN");
1183 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1184 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1186 CFRelease(formatter);
1188 return [(NSString *) formatted autorelease];
1191 bool isSectionVisible(NSString *section) {
1192 NSDictionary *metadata([Sections_ objectForKey:section]);
1193 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1194 return hidden == nil || ![hidden boolValue];
1197 /* Delegate Prototypes {{{ */
1201 @interface NSObject (ProgressDelegate)
1204 @protocol ProgressDelegate
1205 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1206 - (void) setProgressTitle:(NSString *)title;
1207 - (void) setProgressPercent:(float)percent;
1208 - (void) startProgress;
1209 - (void) addProgressOutput:(NSString *)output;
1210 - (bool) isCancelling:(size_t)received;
1213 @protocol ConfigurationDelegate
1214 - (void) repairWithSelector:(SEL)selector;
1215 - (void) setConfigurationData:(NSString *)data;
1220 @protocol CydiaDelegate
1221 - (void) setPackageView:(PackageView *)view;
1222 - (void) clearPackage:(Package *)package;
1223 - (void) installPackage:(Package *)package;
1224 - (void) installPackages:(NSArray *)packages;
1225 - (void) removePackage:(Package *)package;
1226 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIButton *)item;
1227 - (void) distUpgrade;
1228 - (void) updateData;
1230 - (void) askForSettings;
1231 - (UIProgressHUD *) addProgressHUD;
1232 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1233 - (RVPage *) pageForPackage:(NSString *)name;
1234 - (PackageView *) packageView;
1238 /* Status Delegation {{{ */
1240 public pkgAcquireStatus
1243 _transient NSObject<ProgressDelegate> *delegate_;
1251 void setDelegate(id delegate) {
1252 delegate_ = delegate;
1255 NSObject<ProgressDelegate> *getDelegate() const {
1259 virtual bool MediaChange(std::string media, std::string drive) {
1263 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1266 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1267 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1268 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1271 virtual void Done(pkgAcquire::ItemDesc &item) {
1274 virtual void Fail(pkgAcquire::ItemDesc &item) {
1276 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1277 item.Owner->Status == pkgAcquire::Item::StatDone
1281 std::string &error(item.Owner->ErrorText);
1285 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1286 NSArray *fields([description componentsSeparatedByString:@" "]);
1287 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1289 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1290 withObject:[NSArray arrayWithObjects:
1291 [NSString stringWithUTF8String:error.c_str()],
1298 virtual bool Pulse(pkgAcquire *Owner) {
1299 bool value = pkgAcquireStatus::Pulse(Owner);
1302 double(CurrentBytes + CurrentItems) /
1303 double(TotalBytes + TotalItems)
1306 [delegate_ setProgressPercent:percent];
1307 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1310 virtual void Start() {
1311 [delegate_ startProgress];
1314 virtual void Stop() {
1318 /* Progress Delegation {{{ */
1323 _transient id<ProgressDelegate> delegate_;
1327 virtual void Update() {
1328 /*if (abs(Percent - percent_) > 2)
1329 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1333 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1334 [delegate_ setProgressPercent:(Percent / 100)];*/
1344 void setDelegate(id delegate) {
1345 delegate_ = delegate;
1348 id getDelegate() const {
1352 virtual void Done() {
1354 //[delegate_ setProgressPercent:1];
1359 /* Database Interface {{{ */
1360 typedef std::map< unsigned long, _H<Source> > SourceMap;
1362 @interface Database : NSObject {
1368 pkgCacheFile cache_;
1369 pkgDepCache::Policy *policy_;
1370 pkgRecords *records_;
1371 pkgProblemResolver *resolver_;
1372 pkgAcquire *fetcher_;
1374 SPtr<pkgPackageManager> manager_;
1375 pkgSourceList *list_;
1378 NSMutableArray *packages_;
1380 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1389 + (Database *) sharedInstance;
1392 - (void) _readCydia:(NSNumber *)fd;
1393 - (void) _readStatus:(NSNumber *)fd;
1394 - (void) _readOutput:(NSNumber *)fd;
1398 - (Package *) packageWithName:(NSString *)name;
1400 - (pkgCacheFile &) cache;
1401 - (pkgDepCache::Policy *) policy;
1402 - (pkgRecords *) records;
1403 - (pkgProblemResolver *) resolver;
1404 - (pkgAcquire &) fetcher;
1405 - (pkgSourceList &) list;
1406 - (NSArray *) packages;
1407 - (NSArray *) sources;
1408 - (void) reloadData;
1416 - (void) setVisible;
1418 - (void) updateWithStatus:(Status &)status;
1420 - (void) setDelegate:(id)delegate;
1421 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1424 /* Delegate Helpers {{{ */
1425 @implementation NSObject(ProgressDelegate)
1427 - (void) _setProgressErrorPackage:(NSArray *)args {
1428 [self performSelector:@selector(setProgressError:forPackage:)
1429 withObject:[args objectAtIndex:0]
1430 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1434 - (void) _setProgressErrorTitle:(NSArray *)args {
1435 [self performSelector:@selector(setProgressError:withTitle:)
1436 withObject:[args objectAtIndex:0]
1437 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1441 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1442 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1443 withObject:[NSArray arrayWithObjects:error, title, nil]
1448 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1449 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1450 // XXX: holy typecast batman!
1451 [(id<ProgressDelegate>)self setProgressError:error withTitle:(package == nil ? id : [package name])];
1457 /* Source Class {{{ */
1458 @interface Source : NSObject {
1459 CYString depiction_;
1460 CYString description_;
1466 CYString distribution_;
1471 NSString *authority_;
1473 CYString defaultIcon_;
1475 NSDictionary *record_;
1479 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1481 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1483 - (NSString *) depictionForPackage:(NSString *)package;
1484 - (NSString *) supportForPackage:(NSString *)package;
1486 - (NSDictionary *) record;
1490 - (NSString *) distribution;
1491 - (NSString *) type;
1493 - (NSString *) host;
1495 - (NSString *) name;
1496 - (NSString *) description;
1497 - (NSString *) label;
1498 - (NSString *) origin;
1499 - (NSString *) version;
1501 - (NSString *) defaultIcon;
1505 @implementation Source
1509 distribution_.clear();
1512 description_.clear();
1518 defaultIcon_.clear();
1520 if (record_ != nil) {
1530 if (authority_ != nil) {
1531 [authority_ release];
1541 + (NSArray *) _attributeKeys {
1542 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1545 - (NSArray *) attributeKeys {
1546 return [[self class] _attributeKeys];
1549 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1550 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1553 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1556 trusted_ = index->IsTrusted();
1558 uri_.set(pool, index->GetURI());
1559 distribution_.set(pool, index->GetDist());
1560 type_.set(pool, index->GetType());
1562 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1563 if (dindex != NULL) {
1565 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1568 pkgTagFile tags(&fd);
1570 pkgTagSection section;
1577 {"default-icon", &defaultIcon_},
1578 {"depiction", &depiction_},
1579 {"description", &description_},
1581 {"origin", &origin_},
1582 {"support", &support_},
1583 {"version", &version_},
1586 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1587 const char *start, *end;
1589 if (section.Find(names[i].name_, start, end)) {
1590 CYString &value(*names[i].value_);
1591 value.set(pool, start, end - start);
1597 record_ = [Sources_ objectForKey:[self key]];
1599 record_ = [record_ retain];
1601 NSURL *url([NSURL URLWithString:uri_]);
1605 host_ = [[host_ lowercaseString] retain];
1610 authority_ = [url path];
1612 if (authority_ != nil)
1613 authority_ = [authority_ retain];
1616 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1617 if ((self = [super init]) != nil) {
1618 [self setMetaIndex:index inPool:pool];
1622 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1623 NSDictionary *lhr = [self record];
1624 NSDictionary *rhr = [source record];
1627 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1629 NSString *lhs = [self name];
1630 NSString *rhs = [source name];
1632 if ([lhs length] != 0 && [rhs length] != 0) {
1633 unichar lhc = [lhs characterAtIndex:0];
1634 unichar rhc = [rhs characterAtIndex:0];
1636 if (isalpha(lhc) && !isalpha(rhc))
1637 return NSOrderedAscending;
1638 else if (!isalpha(lhc) && isalpha(rhc))
1639 return NSOrderedDescending;
1642 return [lhs compare:rhs options:LaxCompareOptions_];
1645 - (NSString *) depictionForPackage:(NSString *)package {
1646 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1649 - (NSString *) supportForPackage:(NSString *)package {
1650 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1653 - (NSDictionary *) record {
1661 - (NSString *) uri {
1665 - (NSString *) distribution {
1666 return distribution_;
1669 - (NSString *) type {
1673 - (NSString *) key {
1674 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1677 - (NSString *) host {
1681 - (NSString *) name {
1682 return origin_.empty() ? authority_ : origin_;
1685 - (NSString *) description {
1686 return description_;
1689 - (NSString *) label {
1690 return label_.empty() ? authority_ : label_;
1693 - (NSString *) origin {
1697 - (NSString *) version {
1701 - (NSString *) defaultIcon {
1702 return defaultIcon_;
1707 /* Relationship Class {{{ */
1708 @interface Relationship : NSObject {
1713 - (NSString *) type;
1715 - (NSString *) name;
1719 @implementation Relationship
1727 - (NSString *) type {
1735 - (NSString *) name {
1742 /* Package Class {{{ */
1743 @interface Package : NSObject {
1747 pkgCache::VerIterator version_;
1748 pkgCache::PkgIterator iterator_;
1749 _transient Database *database_;
1750 pkgCache::VerFileIterator file_;
1757 NSString *section$_;
1764 CYString installed_;
1770 CYString depiction_;
1781 NSMutableArray *tags_;
1784 NSArray *relationships_;
1786 NSMutableDictionary *metadata_;
1787 _transient NSDate *firstSeen_;
1788 _transient NSDate *lastSeen_;
1792 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1793 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1795 - (pkgCache::PkgIterator) iterator;
1798 - (NSString *) section;
1799 - (NSString *) simpleSection;
1801 - (NSString *) longSection;
1802 - (NSString *) shortSection;
1806 - (Address *) maintainer;
1808 - (NSString *) longDescription;
1809 - (NSString *) shortDescription;
1812 - (NSMutableDictionary *) metadata;
1814 - (BOOL) subscribed;
1817 - (NSString *) latest;
1818 - (NSString *) installed;
1819 - (BOOL) uninstalled;
1822 - (BOOL) upgradableAndEssential:(BOOL)essential;
1825 - (BOOL) unfiltered;
1829 - (BOOL) halfConfigured;
1830 - (BOOL) halfInstalled;
1832 - (NSString *) mode;
1834 - (void) setVisible;
1837 - (NSString *) name;
1839 - (NSString *) homepage;
1840 - (NSString *) depiction;
1841 - (Address *) author;
1843 - (NSString *) support;
1845 - (NSArray *) files;
1846 - (NSArray *) relationships;
1847 - (NSArray *) warnings;
1848 - (NSArray *) applications;
1850 - (Source *) source;
1851 - (NSString *) role;
1853 - (BOOL) matches:(NSString *)text;
1855 - (bool) hasSupportingRole;
1856 - (BOOL) hasTag:(NSString *)tag;
1857 - (NSString *) primaryPurpose;
1858 - (NSArray *) purposes;
1859 - (bool) isCommercial;
1861 - (CYString &) cyname;
1863 - (uint32_t) compareBySection:(NSArray *)sections;
1865 - (uint32_t) compareForChanges;
1870 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1871 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1872 - (bool) isInstalledAndVisible:(NSNumber *)number;
1873 - (bool) isVisibleInSection:(NSString *)section;
1874 - (bool) isVisibleInSource:(Source *)source;
1878 uint32_t PackageChangesRadix(Package *self, void *) {
1883 uint32_t timestamp : 30;
1884 uint32_t ignored : 1;
1885 uint32_t upgradable : 1;
1889 bool upgradable([self upgradableAndEssential:YES]);
1890 value.bits.upgradable = upgradable ? 1 : 0;
1893 value.bits.timestamp = 0;
1894 value.bits.ignored = [self ignored] ? 0 : 1;
1895 value.bits.upgradable = 1;
1897 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1898 value.bits.ignored = 0;
1899 value.bits.upgradable = 0;
1902 return _not(uint32_t) - value.key;
1905 _finline static void Stifle(uint8_t &value) {
1908 uint32_t PackagePrefixRadix(Package *self, void *context) {
1909 size_t offset(reinterpret_cast<size_t>(context));
1910 CYString &name([self cyname]);
1912 size_t size(name.size());
1915 char *text(name.data());
1918 if (!isdigit(text[0]))
1922 while (size != digits && isdigit(text[digits]))
1932 if (offset == 0 && zeros != 0) {
1933 memset(data, '0', zeros);
1934 memcpy(data + zeros, text, 4 - zeros);
1936 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1937 if (size <= offset - zeros)
1940 text += offset - zeros;
1941 size -= offset - zeros;
1944 memcpy(data, text, 4);
1946 memcpy(data, text, size);
1947 memset(data + size, 0, 4 - size);
1950 for (size_t i(0); i != 4; ++i)
1951 if (isalpha(data[i]))
1956 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1958 /* XXX: ntohl may be more honest */
1959 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1962 CYString &(*PackageName)(Package *self, SEL sel);
1964 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1965 _profile(PackageNameCompare)
1966 CYString &lhi(PackageName(lhs, @selector(cyname)));
1967 CYString &rhi(PackageName(rhs, @selector(cyname)));
1968 CFStringRef lhn(lhi), rhn(rhi);
1971 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1972 else if (rhn == NULL)
1973 return NSOrderedDescending;
1975 _profile(PackageNameCompare$NumbersLast)
1976 if (!lhi.empty() && !rhi.empty()) {
1977 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1978 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1979 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1980 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1981 return lha ? NSOrderedAscending : NSOrderedDescending;
1985 CFIndex length = CFStringGetLength(lhn);
1987 _profile(PackageNameCompare$Compare)
1988 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1993 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1994 return PackageNameCompare(*lhs, *rhs, context);
1997 struct PackageNameOrdering :
1998 std::binary_function<Package *, Package *, bool>
2000 _finline bool operator ()(Package *lhs, Package *rhs) const {
2001 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2005 @implementation Package
2007 - (NSString *) description {
2008 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2014 if (section$_ != nil)
2015 [section$_ release];
2020 if (sponsor$_ != nil)
2021 [sponsor$_ release];
2022 if (author$_ != nil)
2029 if (relationships_ != nil)
2030 [relationships_ release];
2031 if (metadata_ != nil)
2032 [metadata_ release];
2037 + (NSString *) webScriptNameForSelector:(SEL)selector {
2038 if (selector == @selector(hasTag:))
2044 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2045 return [self webScriptNameForSelector:selector] == nil;
2048 + (NSArray *) _attributeKeys {
2049 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];
2052 - (NSArray *) attributeKeys {
2053 return [[self class] _attributeKeys];
2056 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2057 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2067 _profile(Package$parse)
2068 pkgRecords::Parser *parser;
2070 _profile(Package$parse$Lookup)
2071 parser = &[database_ records]->Lookup(file_);
2076 _profile(Package$parse$Find)
2082 {"depiction", &depiction_},
2083 {"homepage", &homepage_},
2084 {"website", &website},
2086 {"support", &support_},
2087 {"sponsor", &sponsor_},
2088 {"author", &author_},
2091 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2092 const char *start, *end;
2094 if (parser->Find(names[i].name_, start, end)) {
2095 CYString &value(*names[i].value_);
2096 _profile(Package$parse$Value)
2097 value.set(pool_, start, end - start);
2103 _profile(Package$parse$Tagline)
2104 const char *start, *end;
2105 if (parser->ShortDesc(start, end)) {
2106 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2109 while (stop != start && stop[-1] == '\r')
2111 tagline_.set(pool_, start, stop - start);
2115 _profile(Package$parse$Retain)
2116 if (homepage_.empty())
2117 homepage_ = website;
2118 if (homepage_ == depiction_)
2124 - (void) setVisible {
2125 visible_ = required_ && [self unfiltered];
2128 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2129 if ((self = [super init]) != nil) {
2130 _profile(Package$initWithVersion)
2131 @synchronized (database) {
2132 era_ = [database era];
2136 iterator_ = version.ParentPkg();
2137 database_ = database;
2139 _profile(Package$initWithVersion$Latest)
2140 latest_ = (NSString *) StripVersion(version_.VerStr());
2143 pkgCache::VerIterator current;
2144 _profile(Package$initWithVersion$Versions)
2145 current = iterator_.CurrentVer();
2147 installed_.set(pool_, StripVersion_(current.VerStr()));
2149 if (!version_.end())
2150 file_ = version_.FileList();
2152 pkgCache &cache([database_ cache]);
2153 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2157 _profile(Package$initWithVersion$Name)
2158 id_.set(pool_, iterator_.Name());
2159 name_.set(pool, iterator_.Display());
2163 _profile(Package$initWithVersion$Source)
2164 source_ = [database_ getSource:file_.File()];
2173 _profile(Package$initWithVersion$Tags)
2174 pkgCache::TagIterator tag(iterator_.TagList());
2176 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2178 const char *name(tag.Name());
2179 [tags_ addObject:(NSString *)CFCString(name)];
2180 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2181 role_ = (NSString *) CFCString(name + 6);
2182 if (required_ && strncmp(name, "require::", 9) == 0 && (
2187 } while (!tag.end());
2191 bool changed(false);
2192 NSString *key([id_ lowercaseString]);
2194 _profile(Package$initWithVersion$Metadata)
2195 metadata_ = [Packages_ objectForKey:key];
2197 if (metadata_ == nil) {
2200 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2201 firstSeen_, @"FirstSeen",
2202 latest_, @"LastVersion",
2207 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2208 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2210 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2211 subscribed_ = [subscribed boolValue];
2213 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2215 if (firstSeen_ == nil) {
2216 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2217 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2221 if (version == nil) {
2222 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2224 } else if (![version isEqualToString:latest_]) {
2225 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2227 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2232 metadata_ = [metadata_ retain];
2235 [Packages_ setObject:metadata_ forKey:key];
2240 _profile(Package$initWithVersion$Section)
2241 section_.set(pool_, iterator_.Section());
2244 obsolete_ = [self hasTag:@"cydia::obsolete"];
2245 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2247 } _end } return self;
2250 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2251 @synchronized ([Database class]) {
2252 pkgCache::VerIterator version;
2254 _profile(Package$packageWithIterator$GetCandidateVer)
2255 version = [database policy]->GetCandidateVer(iterator);
2261 return [[[Package alloc]
2262 initWithVersion:version
2269 - (pkgCache::PkgIterator) iterator {
2273 - (NSString *) section {
2274 if (section$_ == nil) {
2275 if (section_.empty())
2278 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2279 NSString *name(section_);
2282 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2283 if (NSString *rename = [value objectForKey:@"Rename"]) {
2288 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2292 - (NSString *) simpleSection {
2293 if (NSString *section = [self section])
2294 return Simplify(section);
2299 - (NSString *) longSection {
2300 return LocalizeSection([self section]);
2303 - (NSString *) shortSection {
2304 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2307 - (NSString *) uri {
2310 pkgIndexFile *index;
2311 pkgCache::PkgFileIterator file(file_.File());
2312 if (![database_ list].FindIndex(file, index))
2314 return [NSString stringWithUTF8String:iterator_->Path];
2315 //return [NSString stringWithUTF8String:file.Site()];
2316 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2320 - (Address *) maintainer {
2323 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2324 const std::string &maintainer(parser->Maintainer());
2325 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2329 return version_.end() ? 0 : version_->InstalledSize;
2332 - (NSString *) longDescription {
2335 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2336 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2338 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2339 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2340 if ([lines count] < 2)
2343 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2344 for (size_t i(1), e([lines count]); i != e; ++i) {
2345 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2346 [trimmed addObject:trim];
2349 return [trimmed componentsJoinedByString:@"\n"];
2352 - (NSString *) shortDescription {
2357 _profile(Package$index)
2358 CFStringRef name((CFStringRef) [self name]);
2359 if (CFStringGetLength(name) == 0)
2361 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2362 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2364 return toupper(character);
2368 - (NSMutableDictionary *) metadata {
2373 if (subscribed_ && lastSeen_ != nil)
2378 - (BOOL) subscribed {
2383 NSDictionary *metadata([self metadata]);
2384 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2385 return [ignored boolValue];
2390 - (NSString *) latest {
2394 - (NSString *) installed {
2398 - (BOOL) uninstalled {
2399 return installed_.empty();
2403 return !version_.end();
2406 - (BOOL) upgradableAndEssential:(BOOL)essential {
2407 _profile(Package$upgradableAndEssential)
2408 pkgCache::VerIterator current(iterator_.CurrentVer());
2410 return essential && essential_ && visible_;
2412 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2416 - (BOOL) essential {
2421 return [database_ cache][iterator_].InstBroken();
2424 - (BOOL) unfiltered {
2425 NSString *section([self section]);
2426 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2434 unsigned char current(iterator_->CurrentState);
2435 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2438 - (BOOL) halfConfigured {
2439 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2442 - (BOOL) halfInstalled {
2443 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2447 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2448 return state.Mode != pkgDepCache::ModeKeep;
2451 - (NSString *) mode {
2452 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2454 switch (state.Mode) {
2455 case pkgDepCache::ModeDelete:
2456 if ((state.iFlags & pkgDepCache::Purge) != 0)
2460 case pkgDepCache::ModeKeep:
2461 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2462 return @"REINSTALL";
2463 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2467 case pkgDepCache::ModeInstall:
2468 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2469 return @"REINSTALL";
2470 else*/ switch (state.Status) {
2472 return @"DOWNGRADE";
2478 return @"NEW_INSTALL";
2489 - (NSString *) name {
2490 return name_.empty() ? id_ : name_;
2493 - (UIImage *) icon {
2494 NSString *section = [self simpleSection];
2498 if ([icon_ hasPrefix:@"file:///"])
2499 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2500 if (icon == nil) if (section != nil)
2501 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2502 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2503 if ([dicon hasPrefix:@"file:///"])
2504 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2506 icon = [UIImage applicationImageNamed:@"unknown.png"];
2510 - (NSString *) homepage {
2514 - (NSString *) depiction {
2515 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2518 - (Address *) sponsor {
2519 if (sponsor$_ == nil) {
2520 if (sponsor_.empty())
2522 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2526 - (Address *) author {
2527 if (author$_ == nil) {
2528 if (author_.empty())
2530 author$_ = [[Address addressWithString:author_] retain];
2534 - (NSString *) support {
2535 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2538 - (NSArray *) files {
2539 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2540 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2543 fin.open([path UTF8String]);
2548 while (std::getline(fin, line))
2549 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2554 - (NSArray *) relationships {
2555 return relationships_;
2558 - (NSArray *) warnings {
2559 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2560 const char *name(iterator_.Name());
2562 size_t length(strlen(name));
2563 if (length < 2) invalid:
2564 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2565 else for (size_t i(0); i != length; ++i)
2567 /* XXX: technically this is not allowed */
2568 (name[i] < 'A' || name[i] > 'Z') &&
2569 (name[i] < 'a' || name[i] > 'z') &&
2570 (name[i] < '0' || name[i] > '9') &&
2571 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2574 if (strcmp(name, "cydia") != 0) {
2577 bool _private = false;
2580 bool repository = [[self section] isEqualToString:@"Repositories"];
2582 if (NSArray *files = [self files])
2583 for (NSString *file in files)
2584 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2586 else if (!user && [file isEqualToString:@"/User"])
2588 else if (!_private && [file isEqualToString:@"/private"])
2590 else if (!stash && [file isEqualToString:@"/var/stash"])
2593 /* XXX: this is not sensitive enough. only some folders are valid. */
2594 if (cydia && !repository)
2595 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2597 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2599 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2601 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2604 return [warnings count] == 0 ? nil : warnings;
2607 - (NSArray *) applications {
2608 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2610 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2612 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2613 if (NSArray *files = [self files])
2614 for (NSString *file in files)
2615 if (application_r(file)) {
2616 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2617 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2618 if ([id isEqualToString:me])
2621 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2623 display = application_r[1];
2625 NSString *bundle([file stringByDeletingLastPathComponent]);
2626 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2627 if (icon == nil || [icon length] == 0)
2629 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2631 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2632 [applications addObject:application];
2634 [application addObject:id];
2635 [application addObject:display];
2636 [application addObject:url];
2639 return [applications count] == 0 ? nil : applications;
2642 - (Source *) source {
2644 @synchronized (database_) {
2645 if ([database_ era] != era_ || file_.end())
2648 source_ = [database_ getSource:file_.File()];
2660 - (NSString *) role {
2664 - (BOOL) matches:(NSString *)text {
2670 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2671 if (range.location != NSNotFound)
2674 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2675 if (range.location != NSNotFound)
2678 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2679 if (range.location != NSNotFound)
2685 - (bool) hasSupportingRole {
2688 if ([role_ isEqualToString:@"enduser"])
2690 if ([Role_ isEqualToString:@"User"])
2692 if ([role_ isEqualToString:@"hacker"])
2694 if ([Role_ isEqualToString:@"Hacker"])
2696 if ([role_ isEqualToString:@"developer"])
2698 if ([Role_ isEqualToString:@"Developer"])
2703 - (BOOL) hasTag:(NSString *)tag {
2704 return tags_ == nil ? NO : [tags_ containsObject:tag];
2707 - (NSString *) primaryPurpose {
2708 for (NSString *tag in tags_)
2709 if ([tag hasPrefix:@"purpose::"])
2710 return [tag substringFromIndex:9];
2714 - (NSArray *) purposes {
2715 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2716 for (NSString *tag in tags_)
2717 if ([tag hasPrefix:@"purpose::"])
2718 [purposes addObject:[tag substringFromIndex:9]];
2719 return [purposes count] == 0 ? nil : purposes;
2722 - (bool) isCommercial {
2723 return [self hasTag:@"cydia::commercial"];
2726 - (CYString &) cyname {
2727 return name_.empty() ? id_ : name_;
2730 - (uint32_t) compareBySection:(NSArray *)sections {
2731 NSString *section([self section]);
2732 for (size_t i(0), e([sections count]); i != e; ++i) {
2733 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2737 return _not(uint32_t);
2740 - (uint32_t) compareForChanges {
2745 uint32_t timestamp : 30;
2746 uint32_t ignored : 1;
2747 uint32_t upgradable : 1;
2751 bool upgradable([self upgradableAndEssential:YES]);
2752 value.bits.upgradable = upgradable ? 1 : 0;
2755 value.bits.timestamp = 0;
2756 value.bits.ignored = [self ignored] ? 0 : 1;
2757 value.bits.upgradable = 1;
2759 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2760 value.bits.ignored = 0;
2761 value.bits.upgradable = 0;
2764 return _not(uint32_t) - value.key;
2768 pkgProblemResolver *resolver = [database_ resolver];
2769 resolver->Clear(iterator_);
2770 resolver->Protect(iterator_);
2774 pkgProblemResolver *resolver = [database_ resolver];
2775 resolver->Clear(iterator_);
2776 resolver->Protect(iterator_);
2777 pkgCacheFile &cache([database_ cache]);
2778 cache->MarkInstall(iterator_, false);
2779 pkgDepCache::StateCache &state((*cache)[iterator_]);
2780 if (!state.Install())
2781 cache->SetReInstall(iterator_, true);
2785 pkgProblemResolver *resolver = [database_ resolver];
2786 resolver->Clear(iterator_);
2787 resolver->Protect(iterator_);
2788 resolver->Remove(iterator_);
2789 [database_ cache]->MarkDelete(iterator_, true);
2792 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2793 _profile(Package$isUnfilteredAndSearchedForBy)
2796 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2797 value &= [self unfiltered];
2800 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2801 value &= [self matches:search];
2808 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2809 if ([search length] == 0)
2812 _profile(Package$isUnfilteredAndSelectedForBy)
2815 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2816 value &= [self unfiltered];
2819 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2820 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2827 - (bool) isInstalledAndVisible:(NSNumber *)number {
2828 return (![number boolValue] || [self visible]) && ![self uninstalled];
2831 - (bool) isVisibleInSection:(NSString *)name {
2832 NSString *section = [self section];
2837 section == nil && [name length] == 0 ||
2838 [name isEqualToString:section]
2842 - (bool) isVisibleInSource:(Source *)source {
2843 return [self source] == source && [self visible];
2848 /* Section Class {{{ */
2849 @interface Section : NSObject {
2854 NSString *localized_;
2857 - (NSComparisonResult) compareByLocalized:(Section *)section;
2858 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2859 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2860 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2861 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2862 - (NSString *) name;
2869 - (void) addToCount;
2871 - (void) setCount:(size_t)count;
2872 - (NSString *) localized;
2876 @implementation Section
2880 if (localized_ != nil)
2881 [localized_ release];
2885 - (NSComparisonResult) compareByLocalized:(Section *)section {
2886 NSString *lhs(localized_);
2887 NSString *rhs([section localized]);
2889 /*if ([lhs length] != 0 && [rhs length] != 0) {
2890 unichar lhc = [lhs characterAtIndex:0];
2891 unichar rhc = [rhs characterAtIndex:0];
2893 if (isalpha(lhc) && !isalpha(rhc))
2894 return NSOrderedAscending;
2895 else if (!isalpha(lhc) && isalpha(rhc))
2896 return NSOrderedDescending;
2899 return [lhs compare:rhs options:LaxCompareOptions_];
2902 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2903 if ((self = [self initWithName:name localize:NO]) != nil) {
2904 if (localized != nil)
2905 localized_ = [localized retain];
2909 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2910 return [self initWithName:name row:0 localize:localize];
2913 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2914 if ((self = [super init]) != nil) {
2915 name_ = [name retain];
2919 localized_ = [LocalizeSection(name_) retain];
2923 /* XXX: localize the index thingees */
2924 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2925 if ((self = [super init]) != nil) {
2926 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2932 - (NSString *) name {
2952 - (void) addToCount {
2956 - (void) setCount:(size_t)count {
2960 - (NSString *) localized {
2967 static NSString *Colon_;
2968 static NSString *Error_;
2969 static NSString *Warning_;
2971 /* Database Implementation {{{ */
2972 @implementation Database
2974 + (Database *) sharedInstance {
2975 static Database *instance;
2976 if (instance == nil)
2977 instance = [[Database alloc] init];
2987 NSRecycleZone(zone_);
2988 // XXX: malloc_destroy_zone(zone_);
2989 apr_pool_destroy(pool_);
2993 - (void) _readCydia:(NSNumber *)fd { _pooled
2994 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2995 std::istream is(&ib);
2998 static Pcre finish_r("^finish:([^:]*)$");
3000 while (std::getline(is, line)) {
3001 const char *data(line.c_str());
3002 size_t size = line.size();
3003 lprintf("C:%s\n", data);
3005 if (finish_r(data, size)) {
3006 NSString *finish = finish_r[1];
3007 int index = [Finishes_ indexOfObject:finish];
3008 if (index != INT_MAX && index > Finish_)
3016 - (void) _readStatus:(NSNumber *)fd { _pooled
3017 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3018 std::istream is(&ib);
3021 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3022 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3024 while (std::getline(is, line)) {
3025 const char *data(line.c_str());
3026 size_t size(line.size());
3027 lprintf("S:%s\n", data);
3029 if (conffile_r(data, size)) {
3030 [delegate_ setConfigurationData:conffile_r[1]];
3031 } else if (strncmp(data, "status: ", 8) == 0) {
3032 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3033 [delegate_ setProgressTitle:string];
3034 } else if (pmstatus_r(data, size)) {
3035 std::string type([pmstatus_r[1] UTF8String]);
3036 NSString *id = pmstatus_r[2];
3038 float percent([pmstatus_r[3] floatValue]);
3039 [delegate_ setProgressPercent:(percent / 100)];
3041 NSString *string = pmstatus_r[4];
3043 if (type == "pmerror")
3044 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3045 withObject:[NSArray arrayWithObjects:string, id, nil]
3048 else if (type == "pmstatus") {
3049 [delegate_ setProgressTitle:string];
3050 } else if (type == "pmconffile")
3051 [delegate_ setConfigurationData:string];
3053 lprintf("E:unknown pmstatus\n");
3055 lprintf("E:unknown status\n");
3061 - (void) _readOutput:(NSNumber *)fd { _pooled
3062 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3063 std::istream is(&ib);
3066 while (std::getline(is, line)) {
3067 lprintf("O:%s\n", line.c_str());
3068 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3078 - (Package *) packageWithName:(NSString *)name {
3079 @synchronized ([Database class]) {
3080 if (static_cast<pkgDepCache *>(cache_) == NULL)
3082 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3083 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3086 - (Database *) init {
3087 if ((self = [super init]) != nil) {
3094 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3095 apr_pool_create(&pool_, NULL);
3097 packages_ = [[NSMutableArray alloc] init];
3101 _assert(pipe(fds) != -1);
3104 _config->Set("APT::Keep-Fds::", cydiafd_);
3105 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3108 detachNewThreadSelector:@selector(_readCydia:)
3110 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3113 _assert(pipe(fds) != -1);
3117 detachNewThreadSelector:@selector(_readStatus:)
3119 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3122 _assert(pipe(fds) != -1);
3123 _assert(dup2(fds[0], 0) != -1);
3124 _assert(close(fds[0]) != -1);
3126 input_ = fdopen(fds[1], "a");
3128 _assert(pipe(fds) != -1);
3129 _assert(dup2(fds[1], 1) != -1);
3130 _assert(close(fds[1]) != -1);
3133 detachNewThreadSelector:@selector(_readOutput:)
3135 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3140 - (pkgCacheFile &) cache {
3144 - (pkgDepCache::Policy *) policy {
3148 - (pkgRecords *) records {
3152 - (pkgProblemResolver *) resolver {
3156 - (pkgAcquire &) fetcher {
3160 - (pkgSourceList &) list {
3164 - (NSArray *) packages {
3168 - (NSArray *) sources {
3169 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3170 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3171 [sources addObject:i->second];
3175 - (NSArray *) issues {
3176 if (cache_->BrokenCount() == 0)
3179 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3181 for (Package *package in packages_) {
3182 if (![package broken])
3184 pkgCache::PkgIterator pkg([package iterator]);
3186 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3187 [entry addObject:[package name]];
3188 [issues addObject:entry];
3190 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3194 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3195 pkgCache::DepIterator start;
3196 pkgCache::DepIterator end;
3197 dep.GlobOr(start, end); // ++dep
3199 if (!cache_->IsImportantDep(end))
3201 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3204 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3205 [entry addObject:failure];
3206 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3208 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3209 if (Package *package = [self packageWithName:name])
3210 name = [package name];
3211 [failure addObject:name];
3213 pkgCache::PkgIterator target(start.TargetPkg());
3214 if (target->ProvidesList != 0)
3215 [failure addObject:@"?"];
3217 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3219 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3220 else if (!cache_[target].CandidateVerIter(cache_).end())
3221 [failure addObject:@"-"];
3222 else if (target->ProvidesList == 0)
3223 [failure addObject:@"!"];
3225 [failure addObject:@"%"];
3229 if (start.TargetVer() != 0)
3230 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3241 - (bool) popErrorWithTitle:(NSString *)title {
3243 std::string message;
3245 while (!_error->empty()) {
3247 bool warning(!_error->PopMessage(error));
3251 size_t size(error.size());
3252 if (size == 0 || error[size - 1] != '\n')
3254 error.resize(size - 1);
3256 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3258 if (!message.empty())
3263 if (fatal && !message.empty())
3264 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3269 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3270 return [self popErrorWithTitle:title] || !success;
3273 - (void) reloadData { _pooled
3274 @synchronized ([Database class]) {
3275 @synchronized (self) {
3279 [packages_ removeAllObjects];
3305 apr_pool_clear(pool_);
3306 NSRecycleZone(zone_);
3308 int chk(creat("/tmp/cydia.chk", 0644));
3312 NSString *title(UCLocalize("DATABASE"));
3315 if (!cache_.Open(progress_, true)) { pop:
3317 bool warning(!_error->PopMessage(error));
3318 lprintf("cache_.Open():[%s]\n", error.c_str());
3320 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3321 [delegate_ repairWithSelector:@selector(configure)];
3322 else if (error == "The package lists or status file could not be parsed or opened.")
3323 [delegate_ repairWithSelector:@selector(update)];
3324 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3325 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3326 // else if (error == "The list of sources could not be read.")
3328 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3337 unlink("/tmp/cydia.chk");
3339 now_ = [[NSDate date] retain];
3341 policy_ = new pkgDepCache::Policy();
3342 records_ = new pkgRecords(cache_);
3343 resolver_ = new pkgProblemResolver(cache_);
3344 fetcher_ = new pkgAcquire(&status_);
3347 list_ = new pkgSourceList();
3348 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3351 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3352 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3356 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3359 if (cache_->BrokenCount() != 0) {
3360 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3363 if (cache_->BrokenCount() != 0) {
3364 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3368 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3374 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3375 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3376 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3377 // XXX: this could be more intelligent
3378 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3379 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3381 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3388 /*std::vector<Package *> packages;
3389 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3390 [packages_ release];
3395 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3396 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3397 //packages.push_back(package);
3398 [packages_ addObject:package];
3402 /*if (packages.empty())
3403 packages_ = [[NSArray alloc] init];
3405 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3408 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3409 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3410 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3418 /*if (!packages.empty())
3419 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3420 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3422 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3424 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3426 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3432 - (void) configure {
3433 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3434 system([dpkg UTF8String]);
3438 // XXX: I don't remember this condition
3443 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3445 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3447 if ([self popErrorWithTitle:title])
3451 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3454 public pkgArchiveCleaner
3457 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3462 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3469 fetcher_->Shutdown();
3471 pkgRecords records(cache_);
3473 lock_ = new FileFd();
3474 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3476 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3478 if ([self popErrorWithTitle:title])
3482 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3485 manager_ = (_system->CreatePM(cache_));
3486 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3493 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3495 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3497 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3499 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3500 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3503 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3508 bool failed = false;
3509 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3510 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3512 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3515 std::string uri = (*item)->DescURI();
3516 std::string error = (*item)->ErrorText;
3518 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3521 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3522 withObject:[NSArray arrayWithObjects:
3523 [NSString stringWithUTF8String:error.c_str()],
3535 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3537 if (_error->PendingError()) {
3542 if (result == pkgPackageManager::Failed) {
3547 if (result != pkgPackageManager::Completed) {
3552 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3554 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3556 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3557 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3560 if (![before isEqualToArray:after])
3565 NSString *title(UCLocalize("UPGRADE"));
3566 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3572 [self updateWithStatus:status_];
3575 - (void) setVisible {
3576 for (Package *package in packages_)
3577 [package setVisible];
3580 - (void) updateWithStatus:(Status &)status {
3581 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3582 NSString *title(UCLocalize("REFRESHING_DATA"));
3585 if (!list.ReadMainList())
3586 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3589 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3590 if ([self popErrorWithTitle:title])
3593 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3594 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
3596 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3600 - (void) setDelegate:(id)delegate {
3601 delegate_ = delegate;
3602 status_.setDelegate(delegate);
3603 progress_.setDelegate(delegate);
3606 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3607 SourceMap::const_iterator i(sources_.find(file->ID));
3608 return i == sources_.end() ? nil : i->second;
3614 /* Confirmation View {{{ */
3615 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3616 if (!iterator.end())
3617 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3618 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3620 pkgCache::PkgIterator package(dep.TargetPkg());
3623 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3630 /* Web Scripting {{{ */
3631 @interface CydiaObject : NSObject {
3636 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3639 @implementation CydiaObject
3642 [indirect_ release];
3646 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3647 if ((self = [super init]) != nil) {
3648 indirect_ = [indirect retain];
3652 - (void) setDelegate:(id)delegate {
3653 delegate_ = delegate;
3656 + (NSArray *) _attributeKeys {
3657 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3660 - (NSArray *) attributeKeys {
3661 return [[self class] _attributeKeys];
3664 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3665 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3668 - (NSString *) device {
3669 return [[UIDevice currentDevice] uniqueIdentifier];
3672 #if 0 // XXX: implement!
3673 - (NSString *) mac {
3674 if (![indirect_ promptForSensitive:@"Mac Address"])
3678 - (NSString *) serial {
3679 if (![indirect_ promptForSensitive:@"Serial #"])
3683 - (NSString *) firewire {
3684 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3688 - (NSString *) imei {
3689 if (![indirect_ promptForSensitive:@"IMEI"])
3694 + (NSString *) webScriptNameForSelector:(SEL)selector {
3695 if (selector == @selector(close))
3697 else if (selector == @selector(getInstalledPackages))
3698 return @"getInstalledPackages";
3699 else if (selector == @selector(getPackageById:))
3700 return @"getPackageById";
3701 else if (selector == @selector(installPackages:))
3702 return @"installPackages";
3703 else if (selector == @selector(setAutoPopup:))
3704 return @"setAutoPopup";
3705 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3706 return @"setButtonImage";
3707 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3708 return @"setButtonTitle";
3709 else if (selector == @selector(setFinishHook:))
3710 return @"setFinishHook";
3711 else if (selector == @selector(setPopupHook:))
3712 return @"setPopupHook";
3713 else if (selector == @selector(setSpecial:))
3714 return @"setSpecial";
3715 else if (selector == @selector(setToken:))
3717 else if (selector == @selector(setViewportWidth:))
3718 return @"setViewportWidth";
3719 else if (selector == @selector(supports:))
3721 else if (selector == @selector(stringWithFormat:arguments:))
3723 else if (selector == @selector(localizedStringForKey:value:table:))
3725 else if (selector == @selector(du:))
3727 else if (selector == @selector(statfs:))
3733 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3734 return [self webScriptNameForSelector:selector] == nil;
3737 - (BOOL) supports:(NSString *)feature {
3738 return [feature isEqualToString:@"window.open"];
3741 - (NSArray *) getInstalledPackages {
3742 NSArray *packages([[Database sharedInstance] packages]);
3743 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3744 for (Package *package in packages)
3745 if ([package installed] != nil)
3746 [installed addObject:package];
3750 - (Package *) getPackageById:(NSString *)id {
3751 Package *package([[Database sharedInstance] packageWithName:id]);
3756 - (NSArray *) statfs:(NSString *)path {
3759 if (path == nil || statfs([path UTF8String], &stat) == -1)
3762 return [NSArray arrayWithObjects:
3763 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3764 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3765 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3769 - (NSNumber *) du:(NSString *)path {
3770 NSNumber *value(nil);
3773 _assert(pipe(fds) != -1);
3775 pid_t pid(ExecFork());
3777 _assert(dup2(fds[1], 1) != -1);
3778 _assert(close(fds[0]) != -1);
3779 _assert(close(fds[1]) != -1);
3780 /* XXX: this should probably not use du */
3781 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3786 _assert(close(fds[1]) != -1);
3788 if (FILE *du = fdopen(fds[0], "r")) {
3790 while (fgets(line, sizeof(line), du) != NULL) {
3791 size_t length(strlen(line));
3792 while (length != 0 && line[length - 1] == '\n')
3793 line[--length] = '\0';
3794 if (char *tab = strchr(line, '\t')) {
3796 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3801 } else _assert(close(fds[0]));
3805 if (waitpid(pid, &status, 0) == -1)
3808 else _assert(false);
3817 - (void) installPackages:(NSArray *)packages {
3818 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3821 - (void) setAutoPopup:(BOOL)popup {
3822 [indirect_ setAutoPopup:popup];
3825 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3826 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3829 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3830 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3833 - (void) setSpecial:(id)function {
3834 [indirect_ setSpecial:function];
3837 - (void) setToken:(NSString *)token {
3840 Token_ = [token retain];
3842 [Metadata_ setObject:Token_ forKey:@"Token"];
3846 - (void) setFinishHook:(id)function {
3847 [indirect_ setFinishHook:function];
3850 - (void) setPopupHook:(id)function {
3851 [indirect_ setPopupHook:function];
3854 - (void) setViewportWidth:(float)width {
3855 [indirect_ setViewportWidth:width];
3858 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3859 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3860 unsigned count([arguments count]);
3862 for (unsigned i(0); i != count; ++i)
3863 values[i] = [arguments objectAtIndex:i];
3864 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3867 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3868 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3870 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3872 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3878 @interface CydiaBrowserView : BrowserView {
3879 CydiaObject *cydia_;
3884 @implementation CydiaBrowserView
3891 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3894 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3895 [super webView:sender didClearWindowObject:window forFrame:frame];
3897 WebDataSource *source([frame dataSource]);
3898 NSURLResponse *response([source response]);
3899 NSURL *url([response URL]);
3900 NSString *scheme([url scheme]);
3902 NSHTTPURLResponse *http;
3903 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3904 http = (NSHTTPURLResponse *) response;
3908 NSDictionary *headers([http allHeaderFields]);
3909 NSString *host([url host]);
3910 [self setHeaders:headers forHost:host];
3913 [host isEqualToString:@"cydia.saurik.com"] ||
3914 [host hasSuffix:@".cydia.saurik.com"] ||
3915 [scheme isEqualToString:@"file"]
3917 [window setValue:cydia_ forKey:@"cydia"];
3920 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3921 if (System_ != NULL)
3922 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3923 if (Machine_ != NULL)
3924 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3926 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3928 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3931 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3932 NSMutableURLRequest *copy = [request mutableCopy];
3933 [self _setMoreHeaders:copy];
3937 - (void) setDelegate:(id)delegate {
3938 [super setDelegate:delegate];
3939 [cydia_ setDelegate:delegate];
3942 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3943 if ((self = [super initWithBook:book forWidth:width ofClass:[CydiaBrowserView class]]) != nil) {
3944 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3946 WebView *webview([document_ webView]);
3948 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3950 NSString *application = package == nil ? @"Cydia" : [NSString
3951 stringWithFormat:@"Cydia/%@",
3956 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3958 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3959 if (Product_ != nil)
3960 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3962 [webview setApplicationNameForUserAgent:application];
3968 @protocol ConfirmationViewDelegate
3969 - (void) cancelAndClear:(bool)clear;
3974 @interface ConfirmationView : CydiaBrowserView {
3975 _transient Database *database_;
3976 UIAlertView *essential_;
3983 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3987 @implementation ConfirmationView
3994 if (essential_ != nil)
3995 [essential_ release];
3999 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
4000 NSString *context([sheet context]);
4002 if ([context isEqualToString:@"cancel"]) {
4005 if (button == [sheet cancelButtonIndex]) return;
4006 else if (button == [sheet destructiveButtonIndex]) clear = true;
4009 [sheet dismissWithClickedButtonIndex:0xDEADBEEF animated:YES];
4010 [book_ popFromSuperviewAnimated:YES];
4011 [delegate_ cancelAndClear:clear];
4016 UIActionSheet *sheet = [[UIActionSheet alloc]
4019 cancelButtonTitle:nil
4020 destructiveButtonTitle:nil
4021 otherButtonTitles:nil
4024 [sheet addButtonWithTitle:UCLocalize("CANCEL_CLEAR")];
4025 [sheet setDestructiveButtonIndex:[sheet numberOfButtons] - 1];
4026 [sheet addButtonWithTitle:UCLocalize("CONTINUE_QUEUING")];
4027 [sheet setContext:@"cancel"];
4029 [delegate_ showActionSheet:[sheet autorelease] fromItem:[[book_ navigationBar] currentLeftView]];
4032 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4033 NSString *context([alert context]);
4035 if ([context isEqualToString:@"remove"]) {
4036 if (button == [alert cancelButtonIndex]) {
4038 } else if (button == [alert firstOtherButtonIndex]) {
4041 [delegate_ confirm];
4044 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4045 } else if ([context isEqualToString:@"unable"]) {
4047 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4049 [super alertView:alert clickedButtonAtIndex:button];
4053 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4054 [super webView:sender didClearWindowObject:window forFrame:frame];
4055 [window setValue:changes_ forKey:@"changes"];
4056 [window setValue:issues_ forKey:@"issues"];
4057 [window setValue:sizes_ forKey:@"sizes"];
4060 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4061 if ((self = [super initWithBook:book]) != nil) {
4062 database_ = database;
4064 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4065 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4066 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4067 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4068 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4072 pkgDepCache::Policy *policy([database_ policy]);
4074 pkgCacheFile &cache([database_ cache]);
4075 NSArray *packages = [database_ packages];
4076 for (Package *package in packages) {
4077 pkgCache::PkgIterator iterator = [package iterator];
4078 pkgDepCache::StateCache &state(cache[iterator]);
4080 NSString *name([package name]);
4082 if (state.NewInstall())
4083 [installing addObject:name];
4084 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4085 [reinstalling addObject:name];
4086 else if (state.Upgrade())
4087 [upgrading addObject:name];
4088 else if (state.Downgrade())
4089 [downgrading addObject:name];
4090 else if (state.Delete()) {
4091 if ([package essential])
4093 [removing addObject:name];
4096 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4097 substrate_ |= DepSubstrate(iterator.CurrentVer());
4102 else if (Advanced_) {
4103 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4105 essential_ = [[UIAlertView alloc]
4106 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4107 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4109 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4110 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4113 [essential_ setContext:@"remove"];
4115 essential_ = [[UIAlertView alloc]
4116 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4117 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4119 cancelButtonTitle:UCLocalize("OKAY")
4120 otherButtonTitles:nil
4123 [essential_ setContext:@"unable"];
4126 changes_ = [[NSArray alloc] initWithObjects:
4134 issues_ = [database_ issues];
4136 issues_ = [issues_ retain];
4138 sizes_ = [[NSArray alloc] initWithObjects:
4139 SizeString([database_ fetcher].FetchNeeded()),
4140 SizeString([database_ fetcher].PartialPresent()),
4141 SizeString([database_ cache]->UsrSize()),
4144 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4146 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4150 - (NSString *) backButtonTitle {
4151 return UCLocalize("CONFIRM");
4154 - (NSString *) leftButtonTitle {
4155 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
4158 - (id) rightButtonTitle {
4159 return issues_ != nil ? nil : [super rightButtonTitle];
4162 - (id) _rightButtonTitle {
4163 #if AlwaysReload || IgnoreInstall
4164 return [super _rightButtonTitle];
4166 return UCLocalize("CONFIRM");
4170 - (void) _leftButtonClicked {
4175 - (void) _rightButtonClicked {
4177 return [super _rightButtonClicked];
4179 if (essential_ != nil)
4180 [essential_ popupAlertAnimated:YES];
4184 [delegate_ confirm];
4192 /* Progress Data {{{ */
4193 @interface ProgressData : NSObject {
4199 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4206 @implementation ProgressData
4208 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4209 if ((self = [super init]) != nil) {
4210 selector_ = selector;
4230 /* Progress View {{{ */
4231 @interface ProgressView : UIView <
4232 ConfigurationDelegate,
4235 _transient Database *database_;
4237 UIView *background_;
4238 UITransitionView *transition_;
4240 UINavigationBar *navbar_;
4241 UIProgressBar *progress_;
4242 UITextView *output_;
4243 UITextLabel *status_;
4244 UIPushButton *close_;
4247 SHA1SumValue springlist_;
4248 SHA1SumValue notifyconf_;
4252 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4253 - (void) setContentView:(UIView *)view;
4256 - (void) _retachThread;
4257 - (void) _detachNewThreadData:(ProgressData *)data;
4258 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4264 @protocol ProgressViewDelegate
4265 - (void) progressViewIsComplete:(ProgressView *)sender;
4268 @implementation ProgressView
4271 [transition_ setDelegate:nil];
4272 [navbar_ setDelegate:nil];
4275 if (background_ != nil)
4276 [background_ release];
4277 [transition_ release];
4280 [progress_ release];
4289 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4290 if ((self = [super initWithFrame:frame]) != nil) {
4291 database_ = database;
4292 delegate_ = delegate;
4294 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4295 [transition_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4296 [transition_ setDelegate:self];
4298 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4299 [overlay_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4301 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4302 [background_ setBackgroundColor:[UIColor blackColor]];
4303 [self addSubview:background_];
4305 [self addSubview:transition_];
4307 CGSize navsize = [UINavigationBar defaultSize];
4308 CGRect navrect = {{0, 0}, navsize};
4310 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4311 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
4312 [overlay_ addSubview:navbar_];
4314 [navbar_ setBarStyle:1];
4315 [navbar_ setDelegate:self];
4317 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4318 [navbar_ pushNavigationItem:navitem];
4320 CGRect bounds = [overlay_ bounds];
4321 CGSize prgsize = [UIProgressBar defaultSize];
4324 (bounds.size.width - prgsize.width) / 2,
4325 bounds.size.height - prgsize.height - 20
4328 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4329 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4330 [progress_ setStyle:0];
4332 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4334 bounds.size.height - prgsize.height - 50,
4335 bounds.size.width - 20,
4339 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4341 [status_ setColor:[UIColor whiteColor]];
4342 [status_ setBackgroundColor:[UIColor clearColor]];
4344 [status_ setCentersHorizontally:YES];
4345 //[status_ setFont:font];
4347 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4349 navrect.size.height + 20,
4350 bounds.size.width - 20,
4351 bounds.size.height - navsize.height - 62 - navrect.size.height
4354 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4355 [overlay_ addSubview:output_];
4357 //[output_ setTextFont:@"Courier New"];
4358 [output_ setFont:[[output_ font] fontWithSize:12]];
4360 [output_ setTextColor:[UIColor whiteColor]];
4361 [output_ setBackgroundColor:[UIColor clearColor]];
4363 [output_ setMarginTop:0];
4364 [output_ setAllowsRubberBanding:YES];
4365 [output_ setEditable:NO];
4367 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4369 bounds.size.height - prgsize.height - 50,
4370 bounds.size.width - 20,
4374 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4376 [close_ setAutosizesToFit:NO];
4377 [close_ setDrawsShadow:YES];
4378 [close_ setStretchBackground:YES];
4379 [close_ setEnabled:YES];
4381 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4382 [close_ setTitleFont:bold];
4384 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4385 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4386 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4390 - (void) setContentView:(UIView *)view {
4391 view_ = [view retain];
4394 - (void) resetView {
4395 [transition_ transition:6 toView:view_];
4398 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4399 NSString *context([alert context]);
4401 if ([context isEqualToString:@"conffile"]) {
4402 FILE *input = [database_ input];
4403 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4404 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4407 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4411 - (void) closeButtonPushed {
4420 [delegate_ terminateWithSuccess];
4421 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4422 [delegate_ suspendWithAnimation:YES];
4424 [delegate_ suspend];*/
4428 system("launchctl stop com.apple.SpringBoard");
4432 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4441 - (void) _retachThread {
4442 UINavigationItem *item([navbar_ topItem]);
4443 [item setTitle:UCLocalize("COMPLETE")];
4445 [overlay_ addSubview:close_];
4446 [progress_ removeFromSuperview];
4447 [status_ removeFromSuperview];
4449 [database_ popErrorWithTitle:title_];
4450 [delegate_ progressViewIsComplete:self];
4454 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4457 MMap mmap(file, MMap::ReadOnly);
4459 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4460 if (!(notifyconf_ == sha1.Result()))
4467 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4470 MMap mmap(file, MMap::ReadOnly);
4472 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4473 if (!(springlist_ == sha1.Result()))
4479 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4480 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4481 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4482 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4483 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4486 system("su -c /usr/bin/uicache mobile");
4488 [delegate_ setStatusBarShowsProgress:NO];
4491 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4492 [[data target] performSelector:[data selector] withObject:[data object]];
4495 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4498 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4504 title_ = [title retain];
4506 UINavigationItem *item([navbar_ topItem]);
4507 [item setTitle:title_];
4509 [status_ setText:nil];
4510 [output_ setText:@""];
4511 [progress_ setProgress:0];
4513 [close_ removeFromSuperview];
4514 [overlay_ addSubview:progress_];
4515 [overlay_ addSubview:status_];
4517 [delegate_ setStatusBarShowsProgress:YES];
4522 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4525 MMap mmap(file, MMap::ReadOnly);
4527 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4528 notifyconf_ = sha1.Result();
4534 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4537 MMap mmap(file, MMap::ReadOnly);
4539 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4540 springlist_ = sha1.Result();
4544 [transition_ transition:6 toView:overlay_];
4547 detachNewThreadSelector:@selector(_detachNewThreadData:)
4549 withObject:[[ProgressData alloc]
4550 initWithSelector:selector
4557 - (void) repairWithSelector:(SEL)selector {
4559 detachNewThreadSelector:selector
4562 title:UCLocalize("REPAIRING")
4566 - (void) setConfigurationData:(NSString *)data {
4568 performSelectorOnMainThread:@selector(_setConfigurationData:)
4574 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4575 CYActionSheet *sheet([[[CYActionSheet alloc]
4577 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4578 defaultButtonIndex:0
4581 [sheet setMessage:error];
4582 [sheet yieldToPopupAlertAnimated:YES];
4586 - (void) setProgressTitle:(NSString *)title {
4588 performSelectorOnMainThread:@selector(_setProgressTitle:)
4594 - (void) setProgressPercent:(float)percent {
4596 performSelectorOnMainThread:@selector(_setProgressPercent:)
4597 withObject:[NSNumber numberWithFloat:percent]
4602 - (void) startProgress {
4605 - (void) addProgressOutput:(NSString *)output {
4607 performSelectorOnMainThread:@selector(_addProgressOutput:)
4613 - (bool) isCancelling:(size_t)received {
4617 - (void) _setConfigurationData:(NSString *)data {
4618 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4620 if (!conffile_r(data)) {
4621 lprintf("E:invalid conffile\n");
4625 NSString *ofile = conffile_r[1];
4626 //NSString *nfile = conffile_r[2];
4628 UIAlertView *alert = [[[UIAlertView alloc]
4629 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4630 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4632 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4633 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4634 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4638 [alert setContext:@"conffile"];
4642 - (void) _setProgressTitle:(NSString *)title {
4643 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4644 for (size_t i(0), e([words count]); i != e; ++i) {
4645 NSString *word([words objectAtIndex:i]);
4646 if (Package *package = [database_ packageWithName:word])
4647 [words replaceObjectAtIndex:i withObject:[package name]];
4650 [status_ setText:[words componentsJoinedByString:@" "]];
4653 - (void) _setProgressPercent:(NSNumber *)percent {
4654 [progress_ setProgress:[percent floatValue]];
4657 - (void) _addProgressOutput:(NSString *)output {
4658 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4659 CGSize size = [output_ contentSize];
4660 CGRect rect = {{0, size.height}, {size.width, 0}};
4661 [output_ scrollRectToVisible:rect animated:YES];
4664 - (BOOL) isRunning {
4671 /* Cell Content View {{{ */
4672 @interface ContentView : UIView {
4673 _transient id delegate_;
4678 @implementation ContentView
4679 - (id) initWithFrame:(CGRect)frame {
4680 if ((self = [super initWithFrame:frame]) != nil) {
4681 /* Fix landscape stretching. */
4682 [self setNeedsDisplayOnBoundsChange:YES];
4686 - (void) setDelegate:(id)delegate {
4687 delegate_ = delegate;
4690 - (void) drawRect:(CGRect)rect {
4691 [super drawRect:rect];
4692 [delegate_ drawContentRect:rect];
4696 /* Package Cell {{{ */
4697 @interface PackageCell : UITableViewCell {
4700 NSString *description_;
4706 ContentView *content_;
4712 - (PackageCell *) init;
4713 - (void) setPackage:(Package *)package;
4715 + (int) heightForPackage:(Package *)package;
4716 - (void) drawContentRect:(CGRect)rect;
4720 @implementation PackageCell
4722 - (void) clearPackage {
4733 if (description_ != nil) {
4734 [description_ release];
4738 if (source_ != nil) {
4743 if (badge_ != nil) {
4748 if (placard_ != nil) {
4758 [self clearPackage];
4765 return faded_ ? [self selectionPercent] : fade_;
4768 - (PackageCell *) init {
4769 CGRect frame(CGRectMake(0, 0, 320, 74));
4770 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4771 UIView *content([self contentView]);
4772 CGRect bounds([content bounds]);
4774 content_ = [[ContentView alloc] initWithFrame:bounds];
4775 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4776 [content addSubview:content_];
4778 [content_ setDelegate:self];
4779 [content_ setOpaque:YES];
4780 if ([self respondsToSelector:@selector(selectionPercent)])
4785 - (void) _setBackgroundColor {
4787 if (NSString *mode = [package_ mode]) {
4788 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4789 color = remove ? RemovingColor_ : InstallingColor_;
4791 color = [UIColor whiteColor];
4793 [content_ setBackgroundColor:color];
4794 [self setNeedsDisplay];
4797 - (void) setPackage:(Package *)package {
4798 [self clearPackage];
4801 Source *source = [package source];
4803 icon_ = [[package icon] retain];
4804 name_ = [[package name] retain];
4807 description_ = [package longDescription];
4808 if (description_ == nil)
4809 description_ = [package shortDescription];
4810 if (description_ != nil)
4811 description_ = [description_ retain];
4813 commercial_ = [package isCommercial];
4815 package_ = [package retain];
4817 NSString *label = nil;
4818 bool trusted = false;
4820 if (source != nil) {
4821 label = [source label];
4822 trusted = [source trusted];
4823 } else if ([[package id] isEqualToString:@"firmware"])
4824 label = UCLocalize("APPLE");
4826 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4828 NSString *from(label);
4830 NSString *section = [package simpleSection];
4831 if (section != nil && ![section isEqualToString:label]) {
4832 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4833 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4836 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4837 source_ = [from retain];
4839 if (NSString *purpose = [package primaryPurpose])
4840 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4841 badge_ = [badge_ retain];
4843 if ([package installed] != nil)
4844 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4845 placard_ = [placard_ retain];
4847 [self _setBackgroundColor];
4848 [content_ setNeedsDisplay];
4851 - (void) drawContentRect:(CGRect)rect {
4852 bool selected([self isSelected]);
4853 float width([self bounds].size.width);
4856 CGContextRef context(UIGraphicsGetCurrentContext());
4857 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4858 CGContextFillRect(context, rect);
4863 rect.size = [icon_ size];
4865 rect.size.width /= 2;
4866 rect.size.height /= 2;
4868 rect.origin.x = 25 - rect.size.width / 2;
4869 rect.origin.y = 25 - rect.size.height / 2;
4871 [icon_ drawInRect:rect];
4874 if (badge_ != nil) {
4875 CGSize size = [badge_ size];
4877 [badge_ drawAtPoint:CGPointMake(
4878 36 - size.width / 2,
4879 36 - size.height / 2
4887 UISetColor(commercial_ ? Purple_ : Black_);
4888 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ ellipsis:2];
4889 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
4892 UISetColor(commercial_ ? Purplish_ : Gray_);
4893 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ ellipsis:2];
4895 if (placard_ != nil)
4896 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4899 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4900 //[self _setBackgroundColor];
4901 [super setSelected:selected animated:fade];
4902 [content_ setNeedsDisplay];
4905 + (int) heightForPackage:(Package *)package {
4911 /* Section Cell {{{ */
4912 @interface SectionCell : UITableViewCell {
4918 ContentView *content_;
4924 - (void) setSection:(Section *)section editing:(BOOL)editing;
4928 @implementation SectionCell
4930 - (void) clearSection {
4931 if (basic_ != nil) {
4936 if (section_ != nil) {
4946 if (count_ != nil) {
4953 [self clearSection];
4961 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4962 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4963 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4964 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4965 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4967 UIView *content([self contentView]);
4968 CGRect bounds([content bounds]);
4970 content_ = [[ContentView alloc] initWithFrame:bounds];
4971 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4972 [content addSubview:content_];
4973 [content_ setBackgroundColor:[UIColor whiteColor]];
4975 [content_ setDelegate:self];
4979 - (void) onSwitch:(id)sender {
4980 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4981 if (metadata == nil) {
4982 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4983 [Sections_ setObject:metadata forKey:basic_];
4987 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4990 - (void) setSection:(Section *)section editing:(BOOL)editing {
4991 if (editing != editing_) {
4993 [switch_ removeFromSuperview];
4995 [self addSubview:switch_];
4999 [self clearSection];
5001 if (section == nil) {
5002 name_ = [UCLocalize("ALL_PACKAGES") retain];
5005 basic_ = [section name];
5007 basic_ = [basic_ retain];
5009 section_ = [section localized];
5010 if (section_ != nil)
5011 section_ = [section_ retain];
5013 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5014 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5017 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5020 [self setAccessoryType:editing ? 0 : 1 /*UITableViewCellAccessoryDisclosureIndicator*/];
5021 [content_ setNeedsDisplay];
5024 - (void) setFrame:(CGRect)frame {
5025 [super setFrame:frame];
5027 CGRect rect([switch_ frame]);
5028 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5031 - (void) drawContentRect:(CGRect)rect {
5032 BOOL selected = [self isSelected];
5034 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5042 float width(rect.size.width);
5046 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ ellipsis:2];
5048 CGSize size = [count_ sizeWithFont:Font14_];
5052 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5058 /* File Table {{{ */
5059 @interface FileTable : RVPage {
5060 _transient Database *database_;
5063 NSMutableArray *files_;
5067 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5068 - (void) setPackage:(Package *)package;
5072 @implementation FileTable
5075 if (package_ != nil)
5084 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
5085 return files_ == nil ? 0 : [files_ count];
5088 - (float) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5092 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5093 static NSString *reuseIdentifier = @"SourceCell";
5094 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5096 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5097 [cell setFont:[UIFont systemFontOfSize:16]];
5100 [cell setText:[files_ objectAtIndex:indexPath.row]];
5101 [cell setSelectionStyle:0 /*UITableViewCellSelectionStyleNone*/];
5105 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5106 if ((self = [super initWithBook:book]) != nil) {
5107 database_ = database;
5109 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5111 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5112 [self addSubview:list_];
5114 [list_ setDataSource:self];
5115 [list_ setDelegate:self];
5117 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5118 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5122 - (void) setPackage:(Package *)package {
5123 if (package_ != nil) {
5124 [package_ autorelease];
5133 [files_ removeAllObjects];
5135 if (package != nil) {
5136 package_ = [package retain];
5137 name_ = [[package id] retain];
5139 if (NSArray *files = [package files])
5140 [files_ addObjectsFromArray:files];
5142 if ([files_ count] != 0) {
5143 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5144 [files_ removeObjectAtIndex:0];
5145 [files_ sortUsingSelector:@selector(compareByPath:)];
5147 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5148 [stack addObject:@"/"];
5150 for (int i(0), e([files_ count]); i != e; ++i) {
5151 NSString *file = [files_ objectAtIndex:i];
5152 while (![file hasPrefix:[stack lastObject]])
5153 [stack removeLastObject];
5154 NSString *directory = [stack lastObject];
5155 [stack addObject:[file stringByAppendingString:@"/"]];
5156 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5157 ([stack count] - 2) * 3, "",
5158 [file substringFromIndex:[directory length]]
5167 - (void) resetViewAnimated:(BOOL)animated {
5168 [list_ resetViewAnimated:animated];
5171 - (void) reloadData {
5172 [self setPackage:[database_ packageWithName:name_]];
5173 [self reloadButtons];
5176 - (NSString *) title {
5177 return UCLocalize("INSTALLED_FILES");
5180 - (NSString *) backButtonTitle {
5181 return UCLocalize("FILES");
5186 /* Package View {{{ */
5187 @interface PackageView : CydiaBrowserView {
5188 _transient Database *database_;
5192 NSMutableArray *buttons_;
5195 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5196 - (void) setPackage:(Package *)package;
5200 @implementation PackageView
5203 if (package_ != nil)
5212 if ([self retainCount] == 1)
5213 [delegate_ setPackageView:self];
5217 /* XXX: this is not safe at all... localization of /fail/ */
5218 - (void) _clickButtonWithName:(NSString *)name {
5219 if ([name isEqualToString:UCLocalize("CLEAR")])
5220 [delegate_ clearPackage:package_];
5221 else if ([name isEqualToString:UCLocalize("INSTALL")])
5222 [delegate_ installPackage:package_];
5223 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5224 [delegate_ installPackage:package_];
5225 else if ([name isEqualToString:UCLocalize("REMOVE")])
5226 [delegate_ removePackage:package_];
5227 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5228 [delegate_ installPackage:package_];
5229 else _assert(false);
5232 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5233 NSString *context([sheet context]);
5235 if ([context isEqualToString:@"modify"]) {
5236 if (button != [sheet cancelButtonIndex]) {
5237 NSString *buttonName = [buttons_ objectAtIndex:button];
5238 [self _clickButtonWithName:buttonName];
5241 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5243 [super alertSheet:sheet clickedButtonAtIndex:button];
5247 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5248 return [super webView:sender didFinishLoadForFrame:frame];
5251 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5252 [super webView:sender didClearWindowObject:window forFrame:frame];
5253 [window setValue:package_ forKey:@"package"];
5256 - (bool) _allowJavaScriptPanel {
5261 - (void) __rightButtonClicked {
5262 int count([buttons_ count]);
5267 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5269 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5270 [buttons addObjectsFromArray:buttons_];
5272 UIActionSheet *sheet = [[[UIActionSheet alloc]
5275 cancelButtonTitle:nil
5276 destructiveButtonTitle:nil
5277 otherButtonTitles:nil
5280 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5282 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5283 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5285 [sheet setContext:@"modify"];
5287 [delegate_ showActionSheet:sheet fromItem:[[book_ navigationBar] currentRightView]];
5291 - (void) _rightButtonClicked {
5293 [super _rightButtonClicked];
5295 [self __rightButtonClicked];
5299 - (id) _rightButtonTitle {
5300 int count = [buttons_ count];
5301 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5304 - (NSString *) backButtonTitle {
5308 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5309 if ((self = [super initWithBook:book]) != nil) {
5310 database_ = database;
5311 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5312 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5316 - (void) setPackage:(Package *)package {
5317 if (package_ != nil) {
5318 [package_ autorelease];
5327 [buttons_ removeAllObjects];
5329 if (package != nil) {
5332 package_ = [package retain];
5333 name_ = [[package id] retain];
5334 commercial_ = [package isCommercial];
5336 if ([package_ mode] != nil)
5337 [buttons_ addObject:UCLocalize("CLEAR")];
5338 if ([package_ source] == nil);
5339 else if ([package_ upgradableAndEssential:NO])
5340 [buttons_ addObject:UCLocalize("UPGRADE")];
5341 else if ([package_ uninstalled])
5342 [buttons_ addObject:UCLocalize("INSTALL")];
5344 [buttons_ addObject:UCLocalize("REINSTALL")];
5345 if (![package_ uninstalled])
5346 [buttons_ addObject:UCLocalize("REMOVE")];
5348 if (special_ != NULL) {
5349 CGRect frame([document_ frame]);
5350 frame.size.width = 320;
5351 frame.size.height = 0;
5352 [document_ setFrame:frame];
5354 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5355 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5357 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
5360 [[[document_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5362 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5364 [self setFinishHook:nil];
5365 [self setPopupHook:nil];
5368 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5369 [super callFunction:special_];
5373 [self reloadButtons];
5376 - (bool) isLoading {
5377 return commercial_ ? [super isLoading] : false;
5380 - (void) reloadData {
5381 [self setPackage:[database_ packageWithName:name_]];
5386 /* Package Table {{{ */
5387 @interface PackageTable : RVPage {
5388 _transient Database *database_;
5390 NSMutableArray *packages_;
5391 NSMutableArray *sections_;
5393 NSMutableArray *index_;
5394 NSMutableDictionary *indices_;
5397 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5399 - (void) setDelegate:(id)delegate;
5401 - (void) reloadData;
5402 - (void) resetCursor;
5404 - (UITableView *) list;
5406 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5410 @implementation PackageTable
5413 [list_ setDataSource:nil];
5416 [packages_ release];
5417 [sections_ release];
5424 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5425 NSInteger count([sections_ count]);
5426 return count == 0 ? 1 : count;
5429 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5430 if ([sections_ count] == 0)
5432 return [[sections_ objectAtIndex:section] name];
5435 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5436 if ([sections_ count] == 0)
5438 return [[sections_ objectAtIndex:section] count];
5441 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5442 Section *section([sections_ objectAtIndex:[path section]]);
5443 NSInteger row([path row]);
5444 Package *package([packages_ objectAtIndex:([section row] + row)]);
5448 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5449 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5451 cell = [[[PackageCell alloc] init] autorelease];
5452 [cell setPackage:[self packageAtIndexPath:path]];
5456 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5458 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5461 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5462 Package *package([self packageAtIndexPath:path]);
5463 package = [database_ packageWithName:[package id]];
5464 PackageView *view([delegate_ packageView]);
5465 [view setPackage:package];
5466 [view setDelegate:delegate_];
5467 [book_ pushPage:view];
5471 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5472 return [packages_ count] > 20 ? index_ : nil;
5475 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5479 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5480 if ((self = [super initWithBook:book]) != nil) {
5481 database_ = database;
5482 title_ = [title retain];
5484 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5485 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5487 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5488 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5490 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5491 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5492 [self addSubview:list_];
5494 [list_ setDataSource:self];
5495 [list_ setDelegate:self];
5497 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5501 - (void) setDelegate:(id)delegate {
5502 delegate_ = delegate;
5505 - (bool) hasPackage:(Package *)package {
5509 - (void) reloadData {
5510 NSArray *packages = [database_ packages];
5512 [packages_ removeAllObjects];
5513 [sections_ removeAllObjects];
5515 _profile(PackageTable$reloadData$Filter)
5516 for (Package *package in packages)
5517 if ([self hasPackage:package])
5518 [packages_ addObject:package];
5521 [index_ removeAllObjects];
5522 [indices_ removeAllObjects];
5524 Section *section = nil;
5526 _profile(PackageTable$reloadData$Section)
5527 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5531 _profile(PackageTable$reloadData$Section$Package)
5532 package = [packages_ objectAtIndex:offset];
5533 index = [package index];
5536 if (section == nil || [section index] != index) {
5537 _profile(PackageTable$reloadData$Section$Allocate)
5538 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5541 [index_ addObject:[section name]];
5542 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5544 _profile(PackageTable$reloadData$Section$Add)
5545 [sections_ addObject:section];
5549 [section addToCount];
5553 _profile(PackageTable$reloadData$List)
5558 - (NSString *) title {
5562 - (void) resetViewAnimated:(BOOL)animated {
5563 [list_ resetViewAnimated:animated];
5566 - (void) resetCursor {
5567 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5570 - (UITableView *) list {
5574 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5575 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5580 /* Filtered Package Table {{{ */
5581 @interface FilteredPackageTable : PackageTable {
5587 - (void) setObject:(id)object;
5588 - (void) setObject:(id)object forFilter:(SEL)filter;
5590 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5594 @implementation FilteredPackageTable
5602 - (void) setFilter:(SEL)filter {
5605 /* XXX: this is an unsafe optimization of doomy hell */
5606 Method method(class_getInstanceMethod([Package class], filter));
5607 _assert(method != NULL);
5608 imp_ = method_getImplementation(method);
5609 _assert(imp_ != NULL);
5612 - (void) setObject:(id)object {
5618 object_ = [object retain];
5621 - (void) setObject:(id)object forFilter:(SEL)filter {
5622 [self setFilter:filter];
5623 [self setObject:object];
5627 - (bool) hasPackage:(Package *)package {
5628 _profile(FilteredPackageTable$hasPackage)
5629 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5633 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5634 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5635 [self setFilter:filter];
5636 object_ = object == nil ? nil : [object retain];
5644 /* Add Source View {{{ */
5645 @interface AddSourceView : RVPage {
5646 _transient Database *database_;
5649 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5653 @implementation AddSourceView
5655 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5656 if ((self = [super initWithBook:book]) != nil) {
5657 database_ = database;
5663 /* Source Cell {{{ */
5664 @interface SourceCell : UITableViewCell {
5667 NSString *description_;
5669 ContentView *content_;
5672 - (void) setSource:(Source *)source;
5676 @implementation SourceCell
5678 - (void) clearSource {
5681 [description_ release];
5690 - (void) setSource:(Source *)source {
5694 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5696 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5697 icon_ = [icon_ retain];
5699 origin_ = [[source name] retain];
5700 label_ = [[source uri] retain];
5701 description_ = [[source description] retain];
5703 [content_ setNeedsDisplay];
5712 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5713 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5714 UIView *content([self contentView]);
5715 CGRect bounds([content bounds]);
5717 content_ = [[ContentView alloc] initWithFrame:bounds];
5718 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5719 [content_ setBackgroundColor:[UIColor whiteColor]];
5720 [content addSubview:content_];
5722 [content_ setDelegate:self];
5723 [content_ setOpaque:YES];
5727 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5728 [super setSelected:selected animated:animated];
5729 [content_ setNeedsDisplay];
5732 - (void) drawContentRect:(CGRect)rect {
5733 bool selected([self isSelected]);
5734 float width(rect.size.width);
5737 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5744 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ ellipsis:2];
5748 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
5752 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ ellipsis:2];
5757 /* Source Table {{{ */
5758 @interface SourceTable : RVPage {
5759 _transient Database *database_;
5761 NSMutableArray *sources_;
5765 UIProgressHUD *hud_;
5768 //NSURLConnection *installer_;
5769 NSURLConnection *trivial_;
5770 NSURLConnection *trivial_bz2_;
5771 NSURLConnection *trivial_gz_;
5772 //NSURLConnection *automatic_;
5777 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5781 @implementation SourceTable
5783 - (void) _deallocConnection:(NSURLConnection *)connection {
5784 if (connection != nil) {
5785 [connection cancel];
5786 //[connection setDelegate:nil];
5787 [connection release];
5799 //[self _deallocConnection:installer_];
5800 [self _deallocConnection:trivial_];
5801 [self _deallocConnection:trivial_gz_];
5802 [self _deallocConnection:trivial_bz2_];
5803 //[self _deallocConnection:automatic_];
5811 - (int) numberOfSectionsInTableView:(UITableView *)tableView {
5812 return offset_ == 0 ? 1 : 2;
5815 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(int)section {
5816 switch (section + (offset_ == 0 ? 1 : 0)) {
5817 case 0: return UCLocalize("ENTERED_BY_USER");
5818 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5824 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
5825 int count = [sources_ count];
5827 case 0: return (offset_ == 0 ? count : offset_);
5828 case 1: return count - offset_;
5834 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5836 switch (indexPath.section) {
5837 case 0: idx = indexPath.row; break;
5838 case 1: idx = indexPath.row + offset_; break;
5842 return [sources_ objectAtIndex:idx];
5845 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5846 Source *source = [self sourceAtIndexPath:indexPath];
5847 return [source description] == nil ? 56 : 73;
5850 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5851 Source *source = [self sourceAtIndexPath:indexPath];
5853 static NSString *cellIdentifier = @"Source";
5854 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5856 cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5859 [cell setSource:source];
5863 - (int) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5864 return 1; //UITableViewCellAccessoryDisclosureIndicator?
5867 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5868 Source *source = [self sourceAtIndexPath:indexPath];
5870 PackageTable *packages = [[[FilteredPackageTable alloc]
5873 title:[source label]
5874 filter:@selector(isVisibleInSource:)
5878 [packages setDelegate:delegate_];
5880 [book_ pushPage:packages];
5883 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5884 Source *source = [self sourceAtIndexPath:indexPath];
5885 return [source record] != nil;
5888 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5889 Source *source = [self sourceAtIndexPath:indexPath];
5890 [Sources_ removeObjectForKey:[source key]];
5891 [delegate_ syncData];
5895 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5898 @"./", @"Distribution",
5899 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5901 [delegate_ syncData];
5904 - (NSString *) getWarning {
5905 NSString *href(href_);
5906 NSRange colon([href rangeOfString:@"://"]);
5907 if (colon.location != NSNotFound)
5908 href = [href substringFromIndex:(colon.location + 3)];
5909 href = [href stringByAddingPercentEscapes];
5910 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5911 href = [href stringByCachingURLWithCurrentCDN];
5913 NSURL *url([NSURL URLWithString:href]);
5915 NSStringEncoding encoding;
5916 NSError *error(nil);
5918 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5919 return [warning length] == 0 ? nil : warning;
5923 - (void) _endConnection:(NSURLConnection *)connection {
5924 NSURLConnection **field = NULL;
5925 if (connection == trivial_)
5927 else if (connection == trivial_bz2_)
5928 field = &trivial_bz2_;
5929 else if (connection == trivial_gz_)
5930 field = &trivial_gz_;
5931 _assert(field != NULL);
5932 [connection release];
5937 trivial_bz2_ == nil &&
5943 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5946 UIAlertView *alert = [[[UIAlertView alloc]
5947 initWithTitle:UCLocalize("SOURCE_WARNING")
5950 cancelButtonTitle:UCLocalize("CANCEL")
5951 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5954 [alert setContext:@"warning"];
5955 [alert setNumberOfRows:1];
5959 } else if (error_ != nil) {
5960 UIAlertView *alert = [[[UIAlertView alloc]
5961 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5962 message:[error_ localizedDescription]
5964 cancelButtonTitle:UCLocalize("OK")
5965 otherButtonTitles:nil
5968 [alert setContext:@"urlerror"];
5971 UIAlertView *alert = [[[UIAlertView alloc]
5972 initWithTitle:UCLocalize("NOT_REPOSITORY")
5973 message:UCLocalize("NOT_REPOSITORY_EX")
5975 cancelButtonTitle:UCLocalize("OK")
5976 otherButtonTitles:nil
5979 [alert setContext:@"trivial"];
5983 [delegate_ setStatusBarShowsProgress:NO];
5984 [delegate_ removeProgressHUD:hud_];
5994 if (error_ != nil) {
6001 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6002 switch ([response statusCode]) {
6008 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6009 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6011 error_ = [error retain];
6012 [self _endConnection:connection];
6015 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6016 [self _endConnection:connection];
6019 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6020 NSMutableURLRequest *request = [NSMutableURLRequest
6021 requestWithURL:[NSURL URLWithString:href]
6022 cachePolicy:NSURLRequestUseProtocolCachePolicy
6023 timeoutInterval:120.0
6026 [request setHTTPMethod:method];
6028 if (Machine_ != NULL)
6029 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6030 if (UniqueID_ != nil)
6031 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6033 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6035 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6038 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6039 NSString *context([alert context]);
6041 if ([context isEqualToString:@"source"]) {
6044 NSString *href = [[alert textField] text];
6046 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6048 if (![href hasSuffix:@"/"])
6049 href_ = [href stringByAppendingString:@"/"];
6052 href_ = [href_ retain];
6054 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6055 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6056 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6057 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6061 hud_ = [[delegate_ addProgressHUD] retain];
6062 [hud_ setText:UCLocalize("VERIFYING_URL")];
6071 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6072 } else if ([context isEqualToString:@"trivial"])
6073 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6074 else if ([context isEqualToString:@"urlerror"])
6075 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6076 else if ([context isEqualToString:@"warning"]) {
6091 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6095 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6096 if ((self = [super initWithBook:book]) != nil) {
6097 database_ = database;
6098 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6100 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
6101 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6102 [self addSubview:list_];
6104 [list_ setDataSource:self];
6105 [list_ setDelegate:self];
6109 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6113 - (void) reloadData {
6115 if (!list.ReadMainList())
6118 [sources_ removeAllObjects];
6119 [sources_ addObjectsFromArray:[database_ sources]];
6121 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6124 int count([sources_ count]);
6126 for (int i = 0; i != count; i++) {
6127 if ([[sources_ objectAtIndex:i] record] == nil) break;
6131 [list_ setEditing:NO];
6135 - (void) resetViewAnimated:(BOOL)animated {
6136 [list_ resetViewAnimated:animated];
6139 - (void) _leftButtonClicked {
6140 /*[book_ pushPage:[[[AddSourceView alloc]
6145 UIAlertView *alert = [[[UIAlertView alloc]
6146 initWithTitle:UCLocalize("ENTER_APT_URL")
6149 cancelButtonTitle:UCLocalize("CANCEL")
6150 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6153 [alert setContext:@"source"];
6154 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6156 [alert setNumberOfRows:1];
6157 [alert addTextFieldWithValue:@"http://" label:@""];
6159 UITextInputTraits *traits = [[alert textField] textInputTraits];
6160 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6161 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6162 [traits setKeyboardType:UIKeyboardTypeURL];
6163 // XXX: UIReturnKeyDone
6164 [traits setReturnKeyType:UIReturnKeyNext];
6169 - (void) _rightButtonClicked {
6170 [list_ setEditing:![list_ isEditing]];
6171 [book_ reloadButtonsForPage:self];
6174 - (NSString *) title {
6175 return UCLocalize("SOURCES");
6178 - (NSString *) leftButtonTitle {
6179 return [list_ isEditing] ? UCLocalize("ADD") : nil;
6182 - (id) rightButtonTitle {
6183 return [list_ isEditing] ? UCLocalize("DONE") : UCLocalize("EDIT");
6186 - (UINavigationButtonStyle) rightButtonStyle {
6187 return [list_ isEditing] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6193 /* Installed View {{{ */
6194 @interface InstalledView : RVPage {
6195 _transient Database *database_;
6196 FilteredPackageTable *packages_;
6200 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6204 @implementation InstalledView
6207 [packages_ release];
6211 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6212 if ((self = [super initWithBook:book]) != nil) {
6213 database_ = database;
6215 packages_ = [[FilteredPackageTable alloc]
6219 filter:@selector(isInstalledAndVisible:)
6220 with:[NSNumber numberWithBool:YES]
6223 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6224 [self addSubview:packages_];
6226 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6230 - (void) resetViewAnimated:(BOOL)animated {
6231 [packages_ resetViewAnimated:animated];
6234 - (void) reloadData {
6235 [packages_ reloadData];
6238 - (void) _rightButtonClicked {
6239 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6240 [packages_ reloadData];
6242 [book_ reloadButtonsForPage:self];
6245 - (NSString *) title {
6246 return UCLocalize("INSTALLED");
6249 - (NSString *) backButtonTitle {
6250 return UCLocalize("PACKAGES");
6253 - (id) rightButtonTitle {
6254 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6257 - (UINavigationButtonStyle) rightButtonStyle {
6258 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6261 - (void) setDelegate:(id)delegate {
6262 [super setDelegate:delegate];
6263 [packages_ setDelegate:delegate];
6270 @interface HomeView : CydiaBrowserView {
6275 @implementation HomeView
6277 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6278 [super _setMoreHeaders:request];
6280 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6281 if (UniqueID_ != nil)
6282 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6285 - (void) _leftButtonClicked {
6286 UIAlertView *alert = [[[UIAlertView alloc] init] autorelease];
6287 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6288 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6289 [alert setCancelButtonIndex:0];
6292 @"Copyright (C) 2008-2010\n"
6293 "Jay Freeman (saurik)\n"
6294 "saurik@saurik.com\n"
6295 "http://www.saurik.com/"
6301 - (NSString *) leftButtonTitle {
6302 return UCLocalize("ABOUT");
6307 /* Manage View {{{ */
6308 @interface ManageView : CydiaBrowserView {
6313 @implementation ManageView
6315 - (NSString *) title {
6316 return UCLocalize("MANAGE");
6319 - (void) _leftButtonClicked {
6320 [delegate_ askForSettings];
6321 [delegate_ updateData];
6324 - (NSString *) leftButtonTitle {
6325 return UCLocalize("SETTINGS");
6329 - (id) _rightButtonTitle {
6330 return Queuing_ ? UCLocalize("QUEUE") : nil;
6333 - (UINavigationButtonStyle) rightButtonStyle {
6334 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6337 - (void) _rightButtonClicked {
6342 - (bool) isLoading {
6349 /* Cydia Book {{{ */
6350 @interface CYBook : RVBook <
6353 _transient Database *database_;
6354 UINavigationBar *overlay_;
6355 UINavigationBar *underlay_;
6356 UIProgressIndicator *indicator_;
6357 UITextLabel *prompt_;
6358 UIProgressBar *progress_;
6359 UINavigationButton *cancel_;
6364 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6367 - (void) setUpdate:(NSDate *)date;
6371 @implementation CYBook
6375 [indicator_ release];
6377 [progress_ release];
6382 - (NSString *) getTitleForPage:(RVPage *)page {
6383 return [super getTitleForPage:page];
6395 [UIView beginAnimations:nil context:NULL];
6397 CGRect ovrframe = [overlay_ frame];
6398 ovrframe.origin.y = 0;
6399 [overlay_ setFrame:ovrframe];
6401 CGRect barframe = [navbar_ frame];
6402 barframe.origin.y += ovrframe.size.height;
6403 [navbar_ setFrame:barframe];
6405 CGRect trnframe = [transition_ frame];
6406 trnframe.origin.y += ovrframe.size.height;
6407 trnframe.size.height -= ovrframe.size.height;
6408 [transition_ setFrame:trnframe];
6410 [UIView endAnimations];
6418 [UIView beginAnimations:nil context:NULL];
6420 CGRect ovrframe = [overlay_ frame];
6421 ovrframe.origin.y = -ovrframe.size.height;
6422 [overlay_ setFrame:ovrframe];
6424 CGRect barframe = [navbar_ frame];
6425 barframe.origin.y -= ovrframe.size.height;
6426 [navbar_ setFrame:barframe];
6428 CGRect trnframe = [transition_ frame];
6429 trnframe.origin.y -= ovrframe.size.height;
6430 trnframe.size.height += ovrframe.size.height;
6431 [transition_ setFrame:trnframe];
6433 [UIView commitAnimations];
6436 - (void) setUpdate:(NSDate *)date {
6443 [indicator_ startAnimation];
6444 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6445 [progress_ setProgress:0];
6448 [overlay_ addSubview:cancel_];
6451 detachNewThreadSelector:@selector(_update)
6457 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6458 NSString *context([sheet context]);
6460 if ([context isEqualToString:@"refresh"])
6467 [indicator_ stopAnimation];
6471 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6474 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6475 if ((self = [super initWithFrame:frame]) != nil) {
6476 database_ = database;
6478 CGRect ovrrect([navbar_ bounds]);
6479 ovrrect.size.height = [UINavigationBar defaultSize].height;
6480 ovrrect.origin.y = -ovrrect.size.height;
6482 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6483 [overlay_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6484 [self addSubview:overlay_];
6486 ovrrect.origin.y = frame.size.height;
6487 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6488 [underlay_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6489 [self addSubview:underlay_];
6491 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6493 [overlay_ setBarStyle:1];
6494 [underlay_ setBarStyle:1];
6496 int barstyle([overlay_ _barStyle:NO]);
6497 bool ugly(barstyle == 0);
6499 UIProgressIndicatorStyle style = ugly ?
6500 UIProgressIndicatorStyleMediumBrown :
6501 UIProgressIndicatorStyleMediumWhite;
6503 CGSize indsize([UIProgressIndicator defaultSizeForStyle:style]);
6504 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6505 CGRect indrect = {{indoffset, indoffset}, indsize};
6507 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6508 [indicator_ setStyle:style];
6509 [overlay_ addSubview:indicator_];
6511 CGSize prmsize = {215, indsize.height + 4};
6514 indoffset * 2 + indsize.width,
6515 unsigned(ovrrect.size.height - prmsize.height) / 2 - 1
6518 UIFont *font([UIFont systemFontOfSize:15]);
6520 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6522 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6523 [prompt_ setBackgroundColor:[UIColor clearColor]];
6524 [prompt_ setFont:font];
6526 [overlay_ addSubview:prompt_];
6528 CGSize prgsize = {75, 100};
6531 ovrrect.size.width - prgsize.width - 10,
6532 (ovrrect.size.height - prgsize.height) / 2
6535 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6536 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6537 [overlay_ addSubview:progress_];
6539 [progress_ setStyle:0];
6541 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6542 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6543 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6545 CGRect frame = [cancel_ frame];
6546 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6547 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6548 [cancel_ setFrame:frame];
6550 [cancel_ setBarStyle:barstyle];
6554 - (void) _onCancel {
6556 [cancel_ removeFromSuperview];
6559 - (void) _update { _pooled
6561 status.setDelegate(self);
6562 [database_ updateWithStatus:status];
6565 performSelectorOnMainThread:@selector(_update_)
6571 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6572 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6576 UIActionSheet *sheet = [[[UIActionSheet alloc]
6577 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6578 buttons:[NSArray arrayWithObjects:
6581 defaultButtonIndex:0
6586 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6588 [sheet setBodyText:error];
6589 [sheet popupAlertAnimated:YES];
6591 [self reloadButtons];
6594 - (void) setProgressTitle:(NSString *)title {
6596 performSelectorOnMainThread:@selector(_setProgressTitle:)
6602 - (void) setProgressPercent:(float)percent {
6604 performSelectorOnMainThread:@selector(_setProgressPercent:)
6605 withObject:[NSNumber numberWithFloat:percent]
6610 - (void) startProgress {
6613 - (void) addProgressOutput:(NSString *)output {
6615 performSelectorOnMainThread:@selector(_addProgressOutput:)
6621 - (bool) isCancelling:(size_t)received {
6625 - (void) _setProgressTitle:(NSString *)title {
6626 [prompt_ setText:title];
6629 - (void) _setProgressPercent:(NSNumber *)percent {
6630 [progress_ setProgress:[percent floatValue]];
6633 - (void) _addProgressOutput:(NSString *)output {
6638 /* Cydia:// Protocol {{{ */
6639 @interface CydiaURLProtocol : NSURLProtocol {
6644 @implementation CydiaURLProtocol
6646 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6647 NSURL *url([request URL]);
6650 NSString *scheme([[url scheme] lowercaseString]);
6651 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6656 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6660 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6661 id<NSURLProtocolClient> client([self client]);
6663 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6665 NSData *data(UIImagePNGRepresentation(icon));
6667 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6668 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6669 [client URLProtocol:self didLoadData:data];
6670 [client URLProtocolDidFinishLoading:self];
6674 - (void) startLoading {
6675 id<NSURLProtocolClient> client([self client]);
6676 NSURLRequest *request([self request]);
6678 NSURL *url([request URL]);
6679 NSString *href([url absoluteString]);
6681 NSString *path([href substringFromIndex:8]);
6682 NSRange slash([path rangeOfString:@"/"]);
6685 if (slash.location == NSNotFound) {
6689 command = [path substringToIndex:slash.location];
6690 path = [path substringFromIndex:(slash.location + 1)];
6693 Database *database([Database sharedInstance]);
6695 if ([command isEqualToString:@"package-icon"]) {
6698 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6699 Package *package([database packageWithName:path]);
6702 UIImage *icon([package icon]);
6703 [self _returnPNGWithImage:icon forRequest:request];
6704 } else if ([command isEqualToString:@"source-icon"]) {
6707 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6708 NSString *source(Simplify(path));
6709 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6711 icon = [UIImage applicationImageNamed:@"unknown.png"];
6712 [self _returnPNGWithImage:icon forRequest:request];
6713 } else if ([command isEqualToString:@"uikit-image"]) {
6716 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6717 UIImage *icon(_UIImageWithName(path));
6718 [self _returnPNGWithImage:icon forRequest:request];
6719 } else if ([command isEqualToString:@"section-icon"]) {
6722 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6723 NSString *section(Simplify(path));
6724 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6726 icon = [UIImage applicationImageNamed:@"unknown.png"];
6727 [self _returnPNGWithImage:icon forRequest:request];
6729 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6733 - (void) stopLoading {
6739 /* Sections View {{{ */
6740 @interface SectionsView : RVPage {
6741 _transient Database *database_;
6742 NSMutableArray *sections_;
6743 NSMutableArray *filtered_;
6749 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6750 - (void) reloadData;
6755 @implementation SectionsView
6758 [list_ setDataSource:nil];
6759 [list_ setDelegate:nil];
6761 [sections_ release];
6762 [filtered_ release];
6764 [accessory_ release];
6768 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6769 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6773 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
6774 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6777 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6781 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6782 static NSString *cellIdentifier = @"SectionCell";
6783 SectionCell *cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
6784 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6790 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6791 Section *section = [self sectionAtIndexPath:indexPath];
6792 NSString *name = [section name];
6795 if ([indexPath row] == 0) {
6798 title = UCLocalize("ALL_PACKAGES");
6801 name = [NSString stringWithString:name];
6802 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6805 title = UCLocalize("NO_SECTION");
6809 PackageTable *table = [[[FilteredPackageTable alloc]
6813 filter:@selector(isVisibleInSection:)
6817 [table setDelegate:delegate_];
6819 [book_ pushPage:table];
6822 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6823 if ((self = [super initWithBook:book]) != nil) {
6824 database_ = database;
6826 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6827 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6829 list_ = [[UITableView alloc] initWithFrame:[self bounds]];
6830 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6831 [self addSubview:list_];
6833 [list_ setDelegate:self];
6834 [list_ setDataSource:self];
6838 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6842 - (void) reloadData {
6843 NSArray *packages = [database_ packages];
6845 [sections_ removeAllObjects];
6846 [filtered_ removeAllObjects];
6849 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6850 SectionMap sections;
6851 sections.resize(64);
6853 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6857 for (Package *package in packages) {
6858 NSString *name([package section]);
6859 NSString *key(name == nil ? @"" : name);
6864 _profile(SectionsView$reloadData$Section)
6865 section = §ions[key];
6866 if (*section == nil) {
6867 _profile(SectionsView$reloadData$Section$Allocate)
6868 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6873 [*section addToCount];
6875 _profile(SectionsView$reloadData$Filter)
6876 if (![package valid] || ![package visible])
6880 [*section addToRow];
6884 _profile(SectionsView$reloadData$Section)
6885 section = [sections objectForKey:key];
6886 if (section == nil) {
6887 _profile(SectionsView$reloadData$Section$Allocate)
6888 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6889 [sections setObject:section forKey:key];
6894 [section addToCount];
6896 _profile(SectionsView$reloadData$Filter)
6897 if (![package valid] || ![package visible])
6907 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6908 [sections_ addObject:i->second];
6910 [sections_ addObjectsFromArray:[sections allValues]];
6913 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6915 for (Section *section in sections_) {
6916 size_t count([section row]);
6920 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6921 [section setCount:count];
6922 [filtered_ addObject:section];
6929 - (void) resetView {
6931 [self _rightButtonClicked];
6934 - (void) resetViewAnimated:(BOOL)animated {
6935 [list_ resetViewAnimated:animated];
6938 - (void) _rightButtonClicked {
6939 if ((editing_ = !editing_))
6942 [delegate_ updateData];
6943 [book_ reloadTitleForPage:self];
6944 [book_ reloadButtonsForPage:self];
6947 - (NSString *) title {
6948 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS");
6951 - (NSString *) backButtonTitle {
6952 return UCLocalize("SECTIONS");
6955 - (id) rightButtonTitle {
6956 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6959 - (UINavigationButtonStyle) rightButtonStyle {
6960 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6963 - (UIView *) accessoryView {
6969 /* Changes View {{{ */
6970 @interface ChangesView : RVPage {
6971 _transient Database *database_;
6972 NSMutableArray *packages_;
6973 NSMutableArray *sections_;
6978 - (id) initWithBook:(RVBook *)book database:(Database *)database delegate:(id)delegate;
6979 - (void) reloadData;
6983 @implementation ChangesView
6986 [list_ setDelegate:nil];
6987 [list_ setDataSource:nil];
6989 [packages_ release];
6990 [sections_ release];
6995 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6996 NSInteger count([sections_ count]);
6997 return count == 0 ? 1 : count;
7000 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7001 if ([sections_ count] == 0)
7003 return [[sections_ objectAtIndex:section] name];
7006 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7007 if ([sections_ count] == 0)
7009 return [[sections_ objectAtIndex:section] count];
7012 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7013 Section *section([sections_ objectAtIndex:[path section]]);
7014 NSInteger row([path row]);
7015 return [packages_ objectAtIndex:([section row] + row)];
7018 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7019 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
7021 cell = [[[PackageCell alloc] init] autorelease];
7022 [cell setPackage:[self packageAtIndexPath:path]];
7026 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7028 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7031 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7032 Package *package([self packageAtIndexPath:path]);
7033 PackageView *view([delegate_ packageView]);
7034 [view setDelegate:delegate_];
7035 [view setPackage:package];
7036 [book_ pushPage:view];
7040 - (void) _leftButtonClicked {
7041 [(CYBook *)book_ update];
7042 [self reloadButtons];
7045 - (void) _rightButtonClicked {
7046 [delegate_ distUpgrade];
7049 - (id) initWithBook:(RVBook *)book database:(Database *)database delegate:(id)delegate {
7050 if ((self = [super initWithBook:book]) != nil) {
7051 database_ = database;
7053 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7054 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7056 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
7057 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7058 [self addSubview:list_];
7060 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
7061 [list_ setDataSource:self];
7062 [list_ setDelegate:self];
7063 //[list_ setSectionListStyle:1];
7065 delegate_ = delegate;
7068 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7072 - (void) _reloadPackages:(NSArray *)packages {
7074 for (Package *package in packages)
7076 [package uninstalled] && [package valid] && [package visible] ||
7077 [package upgradableAndEssential:YES]
7079 [packages_ addObject:package];
7082 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7086 - (void) reloadData {
7087 NSArray *packages = [database_ packages];
7089 [packages_ removeAllObjects];
7090 [sections_ removeAllObjects];
7092 UIProgressHUD *hud([delegate_ addProgressHUD]);
7094 [hud setText:@"Loading Changes"];
7095 NSLog(@"HUD:%@::%@", delegate_, hud);
7096 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7097 [delegate_ removeProgressHUD:hud];
7099 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7100 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7101 Section *section = nil;
7105 bool unseens = false;
7107 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7109 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7110 Package *package = [packages_ objectAtIndex:offset];
7112 BOOL uae = [package upgradableAndEssential:YES];
7118 _profile(ChangesView$reloadData$Remember)
7119 seen = [package seen];
7122 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7127 name = UCLocalize("UNKNOWN");
7129 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7133 _profile(ChangesView$reloadData$Allocate)
7134 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7135 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7136 [sections_ addObject:section];
7140 [section addToCount];
7141 } else if ([package ignored])
7142 [ignored addToCount];
7145 [upgradable addToCount];
7150 CFRelease(formatter);
7153 Section *last = [sections_ lastObject];
7154 size_t count = [last count];
7155 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7156 [sections_ removeLastObject];
7159 if ([ignored count] != 0)
7160 [sections_ insertObject:ignored atIndex:0];
7162 [sections_ insertObject:upgradable atIndex:0];
7165 [self reloadButtons];
7168 - (void) resetViewAnimated:(BOOL)animated {
7169 [list_ resetViewAnimated:animated];
7172 - (NSString *) leftButtonTitle {
7173 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
7176 - (id) rightButtonTitle {
7177 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
7180 - (NSString *) title {
7181 return UCLocalize("CHANGES");
7186 /* Search View {{{ */
7187 @protocol SearchViewDelegate
7188 - (void) showKeyboard:(BOOL)show;
7191 @interface SearchView : RVPage {
7193 UISearchField *field_;
7194 FilteredPackageTable *table_;
7198 - (id) initWithBook:(RVBook *)book database:(Database *)database;
7199 - (void) reloadData;
7203 @implementation SearchView
7206 [field_ setDelegate:nil];
7208 [accessory_ release];
7214 - (void) _showKeyboard:(BOOL)show {
7215 CGSize keysize = [UIKeyboard defaultSize];
7216 CGRect keydown = [book_ pageBounds];
7217 CGRect keyup = keydown;
7218 keyup.size.height -= keysize.height - ButtonBarHeight_;
7220 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7222 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7223 [animation setSignificantRectFields:8];
7226 [animation setStartFrame:keydown];
7227 [animation setEndFrame:keyup];
7229 [animation setStartFrame:keyup];
7230 [animation setEndFrame:keydown];
7233 UIAnimator *animator = [UIAnimator sharedAnimator];
7236 addAnimations:[NSArray arrayWithObjects:animation, nil]
7237 withDuration:(KeyboardTime_ - delay)
7242 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7244 //[delegate_ showKeyboard:show];
7247 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7248 [self _showKeyboard:YES];
7249 [table_ setObject:[field_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7253 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7254 [self _showKeyboard:NO];
7255 [table_ setObject:[field_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7259 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7261 NSString *text([field_ text]);
7262 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7263 [table_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7269 - (void) textFieldClearButtonPressed:(UITextField *)field {
7273 - (void) keyboardInputShouldDelete:(id)input {
7277 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7278 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7282 [field_ resignFirstResponder];
7287 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7288 if ((self = [super initWithBook:book]) != nil) {
7289 CGRect pageBounds = [book_ pageBounds];
7291 table_ = [[FilteredPackageTable alloc]
7295 filter:@selector(isUnfilteredAndSearchedForBy:)
7299 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7300 [self addSubview:table_];
7302 [table_ setShouldHideHeaderInShortLists:NO];
7304 CGRect cnfrect = {{7, 38}, {17, 18}};
7311 area.size.width = [self bounds].size.width - area.origin.x * 2;
7312 area.size.height = [UISearchField defaultHeight];
7314 field_ = [[UISearchField alloc] initWithFrame:area];
7315 [field_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7317 UIFont *font = [UIFont systemFontOfSize:16];
7318 [field_ setFont:font];
7320 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7321 [field_ setDelegate:self];
7323 [field_ setPaddingTop:5];
7325 UITextInputTraits *traits([field_ textInputTraits]);
7326 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7327 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7328 [traits setReturnKeyType:UIReturnKeySearch];
7330 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7332 accessory_ = [[UIView alloc] initWithFrame:accrect];
7333 [accessory_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7334 [accessory_ addSubview:field_];
7336 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7340 - (void) resetViewAnimated:(BOOL)animated {
7341 [table_ resetViewAnimated:animated];
7344 - (void) _reloadData {
7347 - (void) reloadData {
7348 _profile(SearchView$reloadData)
7349 [table_ reloadData];
7352 [table_ resetCursor];
7355 - (UIView *) accessoryView {
7359 - (NSString *) title {
7363 - (NSString *) backButtonTitle {
7364 return UCLocalize("SEARCH");
7367 - (void) setDelegate:(id)delegate {
7368 [table_ setDelegate:delegate];
7369 [super setDelegate:delegate];
7374 /* Settings View {{{ */
7375 @interface SettingsView : RVPage {
7376 _transient Database *database_;
7379 UIPreferencesTable *table_;
7380 _UISwitchSlider *subscribedSwitch_;
7381 _UISwitchSlider *ignoredSwitch_;
7382 UIPreferencesControlTableCell *subscribedCell_;
7383 UIPreferencesControlTableCell *ignoredCell_;
7386 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7390 @implementation SettingsView
7393 [table_ setDataSource:nil];
7396 if (package_ != nil)
7399 [subscribedSwitch_ release];
7400 [ignoredSwitch_ release];
7401 [subscribedCell_ release];
7402 [ignoredCell_ release];
7406 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7407 if (package_ == nil)
7413 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7414 if (package_ == nil)
7427 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7428 if (package_ == nil)
7441 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7442 if (package_ == nil)
7455 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7456 if (package_ == nil)
7459 _UISwitchSlider *slider([cell control]);
7460 BOOL value([slider value] != 0);
7461 NSMutableDictionary *metadata([package_ metadata]);
7464 if (NSNumber *number = [metadata objectForKey:key])
7465 before = [number boolValue];
7469 if (value != before) {
7470 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7472 [delegate_ updateData];
7476 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7477 [self onSomething:cell withKey:@"IsSubscribed"];
7480 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7481 [self onSomething:cell withKey:@"IsIgnored"];
7484 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7485 if (package_ == nil)
7489 case 0: switch (row) {
7491 return subscribedCell_;
7493 return ignoredCell_;
7497 case 1: switch (row) {
7499 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7500 [cell setShowSelection:NO];
7501 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7514 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7515 if ((self = [super initWithBook:book])) {
7516 database_ = database;
7517 name_ = [package retain];
7519 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7520 [self addSubview:table_];
7522 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7523 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7525 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7526 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7528 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7529 [subscribedCell_ setShowSelection:NO];
7530 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7531 [subscribedCell_ setControl:subscribedSwitch_];
7533 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7534 [ignoredCell_ setShowSelection:NO];
7535 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7536 [ignoredCell_ setControl:ignoredSwitch_];
7538 [table_ setDataSource:self];
7543 - (void) resetViewAnimated:(BOOL)animated {
7544 [table_ resetViewAnimated:animated];
7547 - (void) reloadData {
7548 if (package_ != nil)
7549 [package_ autorelease];
7550 package_ = [database_ packageWithName:name_];
7551 if (package_ != nil) {
7553 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7554 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7557 [table_ reloadData];
7560 - (NSString *) title {
7561 return UCLocalize("SETTINGS");
7567 /* Signature View {{{ */
7568 @interface SignatureView : CydiaBrowserView {
7569 _transient Database *database_;
7573 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7577 @implementation SignatureView
7584 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7586 [super webView:sender didClearWindowObject:window forFrame:frame];
7589 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7590 if ((self = [super initWithBook:book]) != nil) {
7591 database_ = database;
7592 package_ = [package retain];
7597 - (void) resetViewAnimated:(BOOL)animated {
7600 - (void) reloadData {
7601 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7607 @interface CydiaViewController : UIViewController {
7612 @implementation CydiaViewController
7614 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7615 return NO; // XXX: return YES;
7620 @interface Cydia : UIApplication <
7621 ConfirmationViewDelegate,
7622 ProgressViewDelegate,
7627 CydiaViewController *root_;
7638 NSMutableArray *essential_;
7639 NSMutableArray *broken_;
7641 Database *database_;
7642 ProgressView *progress_;
7646 UIKeyboard *keyboard_;
7647 UIProgressHUD *hud_;
7649 SectionsView *sections_;
7650 ChangesView *changes_;
7651 ManageView *manage_;
7652 SearchView *search_;
7654 #if RecyclePackageViews
7655 NSMutableArray *details_;
7659 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7660 - (void) setPage:(RVPage *)page;
7664 static _finline void _setHomePage(Cydia *self) {
7665 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeView class]]];
7668 @implementation Cydia
7670 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7675 if ([broken_ count] != 0) {
7676 int count = [broken_ count];
7678 UIAlertView *alert = [[[UIAlertView alloc]
7679 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7680 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7682 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7683 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7686 [alert setContext:@"fixhalf"];
7688 } else if (!Ignored_ && [essential_ count] != 0) {
7689 int count = [essential_ count];
7691 UIAlertView *alert = [[[UIAlertView alloc]
7692 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7693 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7695 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7696 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7699 [alert setContext:@"upgrade"];
7704 - (void) _saveConfig {
7707 NSString *error(nil);
7708 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7710 NSError *error(nil);
7711 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7712 NSLog(@"failure to save metadata data: %@", error);
7715 NSLog(@"failure to serialize metadata: %@", error);
7723 - (void) _updateData {
7726 /* XXX: this is just stupid */
7727 if (tag_ != 1 && sections_ != nil)
7728 [sections_ reloadData];
7729 if (tag_ != 2 && changes_ != nil)
7730 [changes_ reloadData];
7731 if (tag_ != 4 && search_ != nil)
7732 [search_ reloadData];
7737 - (void) _reloadData {
7740 static bool loaded(false);
7741 UIProgressHUD *hud([self addProgressHUD]);
7742 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7744 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7747 [self removeProgressHUD:hud];
7751 [essential_ removeAllObjects];
7752 [broken_ removeAllObjects];
7754 NSArray *packages([database_ packages]);
7755 for (Package *package in packages) {
7757 [broken_ addObject:package];
7758 if ([package upgradableAndEssential:NO]) {
7759 if ([package essential])
7760 [essential_ addObject:package];
7766 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7767 [[[toolbar_ items] objectAtIndex:2] setBadgeValue:badge];
7768 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7769 [[[toolbar_ items] objectAtIndex:2] setAnimatedBadge:YES];
7770 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7771 [self setApplicationBadge:badge];
7773 [self setApplicationBadgeString:badge];
7775 [[[toolbar_ items] objectAtIndex:2] setBadgeValue:nil];
7776 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7777 [[[toolbar_ items] objectAtIndex:2] setAnimatedBadge:NO];
7778 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7779 [self removeApplicationBadge];
7780 else // XXX: maybe use setApplicationBadgeString also?
7781 [self setApplicationIconBadgeNumber:0];
7785 [[[toolbar_ items] objectAtIndex:3] setBadgeValue:nil];
7789 if (loaded || ManualRefresh) loaded:
7794 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
7796 if (update != nil) {
7797 NSTimeInterval interval([update timeIntervalSinceNow]);
7798 if (interval <= 0 && interval > -(15*60))
7802 [book_ setUpdate:update];
7806 - (void) updateData {
7807 [database_ setVisible];
7816 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7817 _assert(file != NULL);
7819 for (NSString *key in [Sources_ allKeys]) {
7820 NSDictionary *source([Sources_ objectForKey:key]);
7822 fprintf(file, "%s %s %s\n",
7823 [[source objectForKey:@"Type"] UTF8String],
7824 [[source objectForKey:@"URI"] UTF8String],
7825 [[source objectForKey:@"Distribution"] UTF8String]
7834 detachNewThreadSelector:@selector(update_)
7837 title:UCLocalize("UPDATING_SOURCES")
7841 - (void) reloadData {
7842 @synchronized (self) {
7843 if (confirm_ == nil)
7849 pkgProblemResolver *resolver = [database_ resolver];
7851 resolver->InstallProtect();
7852 if (!resolver->Resolve(true))
7856 - (void) popUpBook:(RVBook *)book {
7857 [underlay_ popSubview:book];
7860 - (CGRect) popUpBounds {
7861 return [underlay_ bounds];
7865 if (![database_ prepare])
7868 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7869 [confirm_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7870 [confirm_ setDelegate:self];
7872 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7873 [page setDelegate:self];
7875 [confirm_ setPage:page];
7876 [self popUpBook:confirm_];
7882 @synchronized (self) {
7887 - (void) clearPackage:(Package *)package {
7888 @synchronized (self) {
7895 - (void) installPackages:(NSArray *)packages {
7896 @synchronized (self) {
7897 for (Package *package in packages)
7904 - (void) installPackage:(Package *)package {
7905 @synchronized (self) {
7912 - (void) removePackage:(Package *)package {
7913 @synchronized (self) {
7920 - (void) distUpgrade {
7921 @synchronized (self) {
7922 if (![database_ upgrade])
7929 @synchronized (self) {
7932 if (confirm_ != nil) {
7940 [overlay_ removeFromSuperview];
7944 detachNewThreadSelector:@selector(perform)
7947 title:UCLocalize("RUNNING")
7951 - (void) progressViewIsComplete:(ProgressView *)progress {
7952 if (confirm_ != nil) {
7953 [underlay_ addSubview:overlay_];
7954 [confirm_ popFromSuperviewAnimated:NO];
7960 - (void) setPage:(RVPage *)page {
7961 [page resetViewAnimated:NO];
7962 [page setDelegate:self];
7963 [book_ setPage:page];
7966 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7967 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7968 [browser loadURL:url];
7972 - (SectionsView *) sectionsView {
7973 if (sections_ == nil)
7974 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7978 - (ChangesView *) changesView {
7979 if (changes_ == nil)
7980 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_ delegate:self];
7984 - (ManageView *) manageView {
7986 manage_ = (ManageView *) [[self
7987 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7988 withClass:[ManageView class]
7993 - (SearchView *) searchView {
7995 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7999 - (void) tabBar:(UITabBar *)sender didSelectItem:(UITabBarItem *)item {
8000 int tag = [item tag];
8002 [book_ resetViewAnimated:YES];
8004 } else if (tag_ == 1)
8005 [[self sectionsView] resetView];
8008 case 0: _setHomePage(self); break;
8010 case 1: [self setPage:[self sectionsView]]; break;
8011 case 2: [self setPage:[self changesView]]; break;
8012 case 3: [self setPage:[self manageView]]; break;
8013 case 4: [self setPage:[self searchView]]; break;
8021 - (void) askForSettings {
8022 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
8024 CYActionSheet *role([[[CYActionSheet alloc]
8025 initWithTitle:UCLocalize("WHO_ARE_YOU")
8026 buttons:[NSArray arrayWithObjects:
8027 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
8028 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
8029 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
8031 defaultButtonIndex:-1
8034 [role setMessage:UCLocalize("ROLE_EX")];
8036 int button([role yieldToPopupAlertAnimated:YES]);
8039 case 1: Role_ = @"User"; break;
8040 case 2: Role_ = @"Hacker"; break;
8041 case 3: Role_ = @"Developer"; break;
8046 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8050 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8057 - (void) setPackageView:(PackageView *)view {
8059 [view setPackage:nil];
8060 #if RecyclePackageViews
8061 if ([details_ count] < 3)
8062 [details_ addObject:view];
8067 - (PackageView *) _packageView {
8068 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
8071 - (PackageView *) packageView {
8072 #if RecyclePackageViews
8074 size_t count([details_ count]);
8077 view = [self _packageView];
8079 [details_ addObject:[self _packageView]];
8081 view = [[[details_ lastObject] retain] autorelease];
8082 [details_ removeLastObject];
8089 return [self _packageView];
8093 - (void) cancelAndClear:(bool)clear {
8094 @synchronized (self) {
8099 [[[toolbar_ items] objectAtIndex:3] setBadgeValue:UCLocalize("Q_D")];
8105 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8106 NSString *context([alert context]);
8108 if ([context isEqualToString:@"fixhalf"]) {
8109 if (button == [alert firstOtherButtonIndex]) {
8110 @synchronized (self) {
8111 for (Package *broken in broken_) {
8114 NSString *id = [broken id];
8115 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8116 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8117 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8118 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8124 } else if (button == [alert cancelButtonIndex]) {
8125 [broken_ removeAllObjects];
8129 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8130 } else if ([context isEqualToString:@"upgrade"]) {
8131 if (button == [alert firstOtherButtonIndex]) {
8132 @synchronized (self) {
8133 for (Package *essential in essential_)
8134 [essential install];
8139 } else if (button == [alert firstOtherButtonIndex] + 1) {
8141 } else if (button == [alert cancelButtonIndex]) {
8145 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8149 - (void) system:(NSString *)command { _pooled
8150 system([command UTF8String]);
8153 - (void) applicationWillSuspend {
8155 [super applicationWillSuspend];
8158 - (void) applicationSuspend:(__GSEvent *)event {
8159 if (hud_ == nil && ![progress_ isRunning])
8160 [super applicationSuspend:event];
8163 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8165 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8168 - (void) _setSuspended:(BOOL)value {
8170 [super _setSuspended:value];
8173 - (UIProgressHUD *) addProgressHUD {
8174 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8175 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8177 [window_ setUserInteractionEnabled:NO];
8179 [progress_ addSubview:hud];
8183 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8185 [hud removeFromSuperview];
8186 [window_ setUserInteractionEnabled:YES];
8189 - (RVPage *) pageForPackage:(NSString *)name {
8190 if (Package *package = [database_ packageWithName:name]) {
8191 PackageView *view([self packageView]);
8192 [view setPackage:package];
8195 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8196 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8197 return [self _pageForURL:url withClass:[CydiaBrowserView class]];
8201 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8205 NSString *href([url absoluteString]);
8206 if ([href hasPrefix:@"apptapp://package/"])
8207 return [self pageForPackage:[href substringFromIndex:18]];
8209 NSString *scheme([[url scheme] lowercaseString]);
8210 if (![scheme isEqualToString:@"cydia"])
8212 NSString *path([url absoluteString]);
8213 if ([path length] < 8)
8215 path = [path substringFromIndex:8];
8216 if (![path hasPrefix:@"/"])
8217 path = [@"/" stringByAppendingString:path];
8219 if ([path isEqualToString:@"/add-source"])
8220 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8221 else if ([path isEqualToString:@"/storage"])
8222 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8223 else if ([path isEqualToString:@"/sources"])
8224 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8225 else if ([path isEqualToString:@"/packages"])
8226 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8227 else if ([path hasPrefix:@"/url/"])
8228 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8229 else if ([path hasPrefix:@"/launch/"])
8230 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8231 else if ([path hasPrefix:@"/package-settings/"])
8232 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8233 else if ([path hasPrefix:@"/package-signature/"])
8234 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8235 else if ([path hasPrefix:@"/package/"])
8236 return [self pageForPackage:[path substringFromIndex:9]];
8237 else if ([path hasPrefix:@"/files/"]) {
8238 NSString *name = [path substringFromIndex:7];
8240 if (Package *package = [database_ packageWithName:name]) {
8241 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8242 [files setPackage:package];
8250 - (void) applicationOpenURL:(NSURL *)url {
8251 [super applicationOpenURL:url];
8253 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8254 [self setPage:page];
8256 [toolbar_ setSelectedItem:(tag_ == -1 ? nil : [items_ objectAtIndex:tag_])];
8260 - (void) applicationDidFinishLaunching:(id)unused {
8261 [BrowserView _initialize];
8263 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8265 Font12_ = [[UIFont systemFontOfSize:12] retain];
8266 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8267 Font14_ = [[UIFont systemFontOfSize:14] retain];
8268 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8269 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8273 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8274 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8276 UIScreen *screen([UIScreen mainScreen]);
8278 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8279 [window_ orderFront:self];
8280 [window_ makeKey:self];
8281 [window_ setHidden:NO];
8283 root_ = [[CydiaViewController alloc] init];
8284 [window_ addSubview:[root_ view]];
8286 database_ = [Database sharedInstance];
8288 progress_ = [[ProgressView alloc] initWithFrame:[[root_ view] bounds] database:database_ delegate:self];
8289 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8290 [[root_ view] addSubview:progress_];
8292 [database_ setDelegate:progress_];
8294 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8295 [underlay_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8296 [progress_ setContentView:underlay_];
8298 [progress_ resetView];
8301 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8302 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8303 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8304 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8305 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8306 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8307 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8308 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8309 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8312 [self setIdleTimerDisabled:YES];
8314 hud_ = [self addProgressHUD];
8315 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8316 [self setStatusBarShowsProgress:YES];
8318 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8320 [self setStatusBarShowsProgress:NO];
8321 [self removeProgressHUD:hud_];
8324 if (ExecFork() == 0) {
8325 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8326 perror("launchctl stop");
8333 [self askForSettings];
8336 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
8337 [overlay_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8339 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8341 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
8342 0, 0, screenrect.size.width, screenrect.size.height - 48
8343 ) database:database_];
8345 [book_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8346 [overlay_ addSubview:book_];
8348 [book_ setDelegate:self];
8350 items_ = [[NSArray arrayWithObjects:
8351 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
8352 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:1] autorelease],
8353 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:2] autorelease],
8354 [[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:3] autorelease],
8355 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:4] autorelease],
8358 toolbar_ = [[UITabBar alloc]
8359 initWithFrame:CGRectMake(
8360 0, screenrect.size.height - ButtonBarHeight_,
8361 screenrect.size.width, ButtonBarHeight_
8365 [toolbar_ setItems:items_];
8367 [toolbar_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
8368 [overlay_ addSubview:toolbar_];
8370 [toolbar_ setDelegate:self];
8372 /*int buttons[5] = {1, 2, 3, 4, 5};
8373 [toolbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
8374 [toolbar_ showButtonGroup:0 withDuration:0];
8376 for (int i = 0; i != 5; ++i) {
8377 UIView *button([toolbar_ viewWithTag:(i + 1)]);
8379 [button setFrame:CGRectMake(
8380 i * (screenrect.size.width / 5) + (screenrect.size.width / 5 - ButtonBarWidth_) / 2, 1,
8381 ButtonBarWidth_, ButtonBarHeight_
8384 [button setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8387 [toolbar_ setSelectedItem:[items_ objectAtIndex:0]];
8389 [UIKeyboard initImplementationNow];
8390 /*CGSize keysize = [UIKeyboard defaultSize];
8391 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8392 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8393 [overlay_ addSubview:keyboard_];*/
8395 [underlay_ addSubview:overlay_];
8399 #if RecyclePackageViews
8400 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8401 [details_ addObject:[self _packageView]];
8402 [details_ addObject:[self _packageView]];
8410 - (void) showKeyboard:(BOOL)show {
8411 CGSize keysize([UIKeyboard defaultSize]);
8412 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8413 CGRect keyup(keydown);
8414 keyup.origin.y -= keysize.height;
8416 UIFrameAnimation *animation([[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease]);
8417 [animation setSignificantRectFields:2];
8420 [animation setStartFrame:keydown];
8421 [animation setEndFrame:keyup];
8422 [keyboard_ activate];
8424 [animation setStartFrame:keyup];
8425 [animation setEndFrame:keydown];
8426 [keyboard_ deactivate];
8429 [[UIAnimator sharedAnimator]
8430 addAnimations:[NSArray arrayWithObjects:animation, nil]
8431 withDuration:KeyboardTime_
8436 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIButton *)item {
8437 if (item != nil && IsWildcat_) {
8438 [sheet showFromRect:[[item superview] convertRect:[item frame] toView:window_] inView:window_ animated:YES];
8440 [sheet showInView:window_];
8447 id Alloc_(id self, SEL selector) {
8448 id object = alloc_(self, selector);
8449 lprintf("[%s]A-%p\n", self->isa->name, object);
8454 id Dealloc_(id self, SEL selector) {
8455 id object = dealloc_(self, selector);
8456 lprintf("[%s]D-%p\n", self->isa->name, object);
8460 Class $WebDefaultUIKitDelegate;
8462 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8463 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8464 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8465 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8468 int main(int argc, char *argv[]) { _pooled
8471 if (Class $UIDevice = objc_getClass("UIDevice")) {
8472 UIDevice *device([$UIDevice currentDevice]);
8473 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8477 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8479 /* Library Hacks {{{ */
8480 class_addMethod(objc_getClass("WebScriptObject"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &WebScriptObject$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8481 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8483 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8484 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8485 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8486 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8487 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8490 /* Set Locale {{{ */
8491 Locale_ = CFLocaleCopyCurrent();
8492 Languages_ = [NSLocale preferredLanguages];
8493 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8494 //NSLog(@"%@", [Languages_ description]);
8497 if (Languages_ == nil || [Languages_ count] == 0)
8498 // XXX: consider just setting to C and then falling through?
8501 lang = [[Languages_ objectAtIndex:0] UTF8String];
8502 setenv("LANG", lang, true);
8505 //std::setlocale(LC_ALL, lang);
8506 NSLog(@"Setting Language: %s", lang);
8509 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8511 /* Parse Arguments {{{ */
8512 bool substrate(false);
8518 for (int argi(1); argi != argc; ++argi)
8519 if (strcmp(argv[argi], "--") == 0) {
8521 argv[argi] = argv[0];
8527 for (int argi(1); argi != arge; ++argi)
8528 if (strcmp(args[argi], "--substrate") == 0)
8531 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8535 App_ = [[NSBundle mainBundle] bundlePath];
8536 Home_ = NSHomeDirectory();
8542 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8543 alloc_ = alloc->method_imp;
8544 alloc->method_imp = (IMP) &Alloc_;*/
8546 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8547 dealloc_ = dealloc->method_imp;
8548 dealloc->method_imp = (IMP) &Dealloc_;*/
8550 /* System Information {{{ */
8554 size = sizeof(maxproc);
8555 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8556 perror("sysctlbyname(\"kern.maxproc\", ?)");
8557 else if (maxproc < 64) {
8559 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8560 perror("sysctlbyname(\"kern.maxproc\", #)");
8563 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8564 char *osversion = new char[size];
8565 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8566 perror("sysctlbyname(\"kern.osversion\", ?)");
8568 System_ = [NSString stringWithUTF8String:osversion];
8570 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8571 char *machine = new char[size];
8572 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8573 perror("sysctlbyname(\"hw.machine\", ?)");
8577 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8578 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8579 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8580 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8584 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8585 NSData *data((NSData *) ecid);
8586 size_t length([data length]);
8587 uint8_t bytes[length];
8588 [data getBytes:bytes];
8589 char string[length * 2 + 1];
8590 for (size_t i(0); i != length; ++i)
8591 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8592 ChipID_ = [NSString stringWithUTF8String:string];
8596 IOObjectRelease(service);
8600 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8602 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8603 Build_ = [system objectForKey:@"ProductBuildVersion"];
8604 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8605 Product_ = [info objectForKey:@"SafariProductVersion"];
8606 Safari_ = [info objectForKey:@"CFBundleVersion"];
8609 /* Load Database {{{ */
8611 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8613 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8616 if (Metadata_ == NULL)
8617 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8619 Settings_ = [Metadata_ objectForKey:@"Settings"];
8621 Packages_ = [Metadata_ objectForKey:@"Packages"];
8622 Sections_ = [Metadata_ objectForKey:@"Sections"];
8623 Sources_ = [Metadata_ objectForKey:@"Sources"];
8625 Token_ = [Metadata_ objectForKey:@"Token"];
8628 if (Settings_ != nil)
8629 Role_ = [Settings_ objectForKey:@"Role"];
8631 if (Packages_ == nil) {
8632 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8633 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8636 if (Sections_ == nil) {
8637 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8638 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8641 if (Sources_ == nil) {
8642 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8643 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8648 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8651 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8653 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8654 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
8655 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8656 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8657 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8658 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8660 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8662 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8663 unlink("/tmp/.cydia.fw");
8665 } else if (access("/User", F_OK) != 0 || version < 2) {
8668 system("/usr/libexec/cydia/firmware.sh");
8672 _assert([[NSFileManager defaultManager]
8673 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8674 withIntermediateDirectories:YES
8679 if (access("/tmp/cydia.chk", F_OK) == 0) {
8680 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8681 _assert(errno == ENOENT);
8682 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8683 _assert(errno == ENOENT);
8686 /* APT Initialization {{{ */
8687 _assert(pkgInitConfig(*_config));
8688 _assert(pkgInitSystem(*_config, _system));
8691 _config->Set("APT::Acquire::Translation", lang);
8692 _config->Set("Acquire::http::Timeout", 15);
8693 _config->Set("Acquire::http::MaxParallel", 3);
8695 /* Color Choices {{{ */
8696 space_ = CGColorSpaceCreateDeviceRGB();
8698 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8699 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8700 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8701 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8702 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8703 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8704 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8705 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8706 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8708 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8709 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8711 /* UIKit Configuration {{{ */
8712 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8713 if ($GSFontSetUseLegacyFontMetrics != NULL)
8714 $GSFontSetUseLegacyFontMetrics(YES);
8716 // XXX: I have a feeling this was important
8717 //UIKeyboardDisableAutomaticAppearance();
8720 Colon_ = UCLocalize("COLON_DELIMITED");
8721 Error_ = UCLocalize("ERROR");
8722 Warning_ = UCLocalize("WARNING");
8725 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8727 CGColorSpaceRelease(space_);