1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2009 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #import "UICaboodle/UCPlatform.h"
45 #import "UICaboodle/UCLocalize.h"
47 #include <objc/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 : UIActionSheet {
288 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
291 @implementation CYActionSheet
293 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
294 if ((self = [super initWithTitle:title buttons:buttons defaultButtonIndex:index delegate:self context:nil]) != nil) {
298 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
302 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
304 [self popupAlertAnimated:animated];
305 NSRunLoop *loop([NSRunLoop currentRunLoop]);
306 NSDate *future([NSDate distantFuture]);
307 while (button_ == 0 && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
313 /* NSForcedOrderingSearch doesn't work on the iPhone */
314 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
315 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
316 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
318 /* Information Dictionaries {{{ */
319 @interface NSMutableArray (Cydia)
320 - (void) addInfoDictionary:(NSDictionary *)info;
323 @implementation NSMutableArray (Cydia)
325 - (void) addInfoDictionary:(NSDictionary *)info {
326 [self addObject:info];
331 @interface NSMutableDictionary (Cydia)
332 - (void) addInfoDictionary:(NSDictionary *)info;
335 @implementation NSMutableDictionary (Cydia)
337 - (void) addInfoDictionary:(NSDictionary *)info {
338 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
343 /* Pop Transitions {{{ */
344 @interface PopTransitionView : UITransitionView {
349 @implementation PopTransitionView
351 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
352 if (from != nil && to == nil)
353 [self removeFromSuperview];
358 @implementation UIView (PopUpView)
360 - (void) popFromSuperviewAnimated:(BOOL)animated {
361 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
364 - (void) popSubview:(UIView *)view {
365 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
366 [transition setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
367 [self addSubview:transition];
369 [transition setDelegate:transition];
371 UIView *blank([[[UIView alloc] initWithFrame:[transition bounds]] autorelease]);
372 [blank setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
374 [transition transition:UITransitionNone toView:blank];
375 [transition transition:UITransitionPushFromBottom toView:view];
381 #define lprintf(args...) fprintf(stderr, args)
384 #define TraceLogging (1 && !ForRelease)
385 #define HistogramInsertionSort (0 && !ForRelease)
386 #define ProfileTimes (0 && !ForRelease)
387 #define ForSaurik (0 && !ForRelease)
388 #define LogBrowser (0 && !ForRelease)
389 #define TrackResize (0 && !ForRelease)
390 #define ManualRefresh (0 && !ForRelease)
391 #define ShowInternals (0 && !ForRelease)
392 #define IgnoreInstall (0 && !ForRelease)
393 #define RecycleWebViews 0
394 #define RecyclePackageViews (1 && ForRelease)
395 #define AlwaysReload (0 && !ForRelease)
399 #define _trace(args...)
404 #define _profile(name) {
407 #define PrintTimes() do {} while (false)
411 typedef uint32_t (*SKRadixFunction)(id, void *);
413 @interface NSMutableArray (Radix)
414 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
415 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
423 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
424 struct RadixItem_ *lhs(swap), *rhs(swap + count);
426 static const size_t width = 32;
427 static const size_t bits = 11;
428 static const size_t slots = 1 << bits;
429 static const size_t passes = (width + (bits - 1)) / bits;
431 size_t *hist(new size_t[slots]);
433 for (size_t pass(0); pass != passes; ++pass) {
434 memset(hist, 0, sizeof(size_t) * slots);
436 for (size_t i(0); i != count; ++i) {
437 uint32_t key(lhs[i].key);
439 key &= _not(uint32_t) >> width - bits;
444 for (size_t i(0); i != slots; ++i) {
445 size_t local(offset);
450 for (size_t i(0); i != count; ++i) {
451 uint32_t key(lhs[i].key);
453 key &= _not(uint32_t) >> width - bits;
454 rhs[hist[key]++] = lhs[i];
457 RadixItem_ *tmp(lhs);
464 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
465 for (size_t i(0); i != count; ++i)
466 [values addObject:[self objectAtIndex:lhs[i].index]];
467 [self setArray:values];
472 @implementation NSMutableArray (Radix)
474 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
475 size_t count([self count]);
480 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
481 [invocation setSelector:selector];
482 [invocation setArgument:&object atIndex:2];
484 /* XXX: this is an unsafe optimization of doomy hell */
485 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
486 _assert(method != NULL);
487 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
488 _assert(imp != NULL);
491 struct RadixItem_ *swap(new RadixItem_[count * 2]);
493 for (size_t i(0); i != count; ++i) {
494 RadixItem_ &item(swap[i]);
497 id object([self objectAtIndex:i]);
500 [invocation setTarget:object];
502 [invocation getReturnValue:&item.key];
504 item.key = imp(object, selector, object);
508 RadixSort_(self, count, swap);
511 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
512 size_t count([self count]);
513 struct RadixItem_ *swap(new RadixItem_[count * 2]);
515 for (size_t i(0); i != count; ++i) {
516 RadixItem_ &item(swap[i]);
519 id object([self objectAtIndex:i]);
520 item.key = function(object, argument);
523 RadixSort_(self, count, swap);
528 /* Insertion Sort {{{ */
530 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
531 const char *ptr = (const char *)list;
533 CFIndex half = count / 2;
534 const char *probe = ptr + elementSize * half;
535 CFComparisonResult cr = comparator(element, probe, context);
536 if (0 == cr) return (probe - (const char *)list) / elementSize;
537 ptr = (cr < 0) ? ptr : probe + elementSize;
538 count = (cr < 0) ? half : (half + (count & 1) - 1);
540 return (ptr - (const char *)list) / elementSize;
543 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
544 const char *ptr = (const char *)list;
546 CFIndex half = count / 2;
547 const char *probe = ptr + elementSize * half;
548 CFComparisonResult cr = comparator(element, probe, context);
549 if (0 == cr) return (probe - (const char *)list) / elementSize;
550 ptr = (cr < 0) ? ptr : probe + elementSize;
551 count = (cr < 0) ? half : (half + (count & 1) - 1);
553 return (ptr - (const char *)list) / elementSize;
556 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
557 if (range.length == 0)
559 const void **values(new const void *[range.length]);
560 CFArrayGetValues(array, range, values);
562 #if HistogramInsertionSort
563 uint32_t total(0), *offsets(new uint32_t[range.length]);
566 for (CFIndex index(1); index != range.length; ++index) {
567 const void *value(values[index]);
568 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
569 CFIndex correct(index);
570 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
573 if (correct != index) {
574 size_t offset(index - correct);
575 #if HistogramInsertionSort
579 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
581 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
582 values[correct] = value;
586 CFArrayReplaceValues(array, range, values, range.length);
589 #if HistogramInsertionSort
590 for (CFIndex index(0); index != range.length; ++index)
591 if (offsets[index] != 0)
592 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
593 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
600 /* Apple Bug Fixes {{{ */
601 @implementation UIWebDocumentView (Cydia)
603 - (void) _setScrollerOffset:(CGPoint)offset {
604 UIScroller *scroller([self _scroller]);
606 CGSize size([scroller contentSize]);
607 CGSize bounds([scroller bounds].size);
610 max.x = size.width - bounds.width;
611 max.y = size.height - bounds.height;
619 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
620 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
622 [scroller setOffset:offset];
628 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
629 size_t length([self length] - state->state);
632 else if (length > count)
634 for (size_t i(0); i != length; ++i)
635 objects[i] = [self item:state->state++];
636 state->itemsPtr = objects;
637 state->mutationsPtr = (unsigned long *) self;
641 @interface NSString (UIKit)
642 - (NSString *) stringByAddingPercentEscapes;
645 /* Cydia NSString Additions {{{ */
646 @interface NSString (Cydia)
647 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
648 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
649 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
650 - (NSComparisonResult) compareByPath:(NSString *)other;
651 - (NSString *) stringByCachingURLWithCurrentCDN;
652 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
655 @implementation NSString (Cydia)
657 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
658 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
661 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
662 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
663 memcpy(data, bytes, length);
664 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
667 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
668 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
671 - (NSComparisonResult) compareByPath:(NSString *)other {
672 NSString *prefix = [self commonPrefixWithString:other options:0];
673 size_t length = [prefix length];
675 NSRange lrange = NSMakeRange(length, [self length] - length);
676 NSRange rrange = NSMakeRange(length, [other length] - length);
678 lrange = [self rangeOfString:@"/" options:0 range:lrange];
679 rrange = [other rangeOfString:@"/" options:0 range:rrange];
681 NSComparisonResult value;
683 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
684 value = NSOrderedSame;
685 else if (lrange.location == NSNotFound)
686 value = NSOrderedAscending;
687 else if (rrange.location == NSNotFound)
688 value = NSOrderedDescending;
690 value = NSOrderedSame;
692 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
693 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
694 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
695 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
697 NSComparisonResult result = [lpath compare:rpath];
698 return result == NSOrderedSame ? value : result;
701 - (NSString *) stringByCachingURLWithCurrentCDN {
703 stringByReplacingOccurrencesOfString:@"://"
704 withString:@"://ne.edgecastcdn.net/8003A4/"
706 /* XXX: this is somewhat inaccurate */
707 range:NSMakeRange(0, 10)
711 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
712 return [(id)CFURLCreateStringByAddingPercentEscapes(
717 kCFStringEncodingUTF8
724 /* C++ NSString Wrapper Cache {{{ */
731 _finline void clear_() {
732 if (cache_ != NULL) {
739 _finline bool empty() const {
743 _finline size_t size() const {
747 _finline char *data() const {
751 _finline void clear() {
756 _finline CYString() :
763 _finline ~CYString() {
767 void operator =(const CYString &rhs) {
771 if (rhs.cache_ == nil)
774 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
777 void set(apr_pool_t *pool, const char *data, size_t size) {
783 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
784 memcpy(temp, data, size);
791 _finline void set(apr_pool_t *pool, const char *data) {
792 set(pool, data, data == NULL ? 0 : strlen(data));
795 _finline void set(apr_pool_t *pool, const std::string &rhs) {
796 set(pool, rhs.data(), rhs.size());
799 bool operator ==(const CYString &rhs) const {
800 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
803 operator CFStringRef() {
804 if (cache_ == NULL) {
807 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
809 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
813 _finline operator id() {
814 return (NSString *) static_cast<CFStringRef>(*this);
818 /* C++ NSString Algorithm Adapters {{{ */
820 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
823 struct NSStringMapHash :
824 std::unary_function<NSString *, size_t>
826 _finline size_t operator ()(NSString *value) const {
827 return CFStringHashNSString((CFStringRef) value);
831 struct NSStringMapLess :
832 std::binary_function<NSString *, NSString *, bool>
834 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
835 return [lhs compare:rhs] == NSOrderedAscending;
839 struct NSStringMapEqual :
840 std::binary_function<NSString *, NSString *, bool>
842 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
843 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
844 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
845 //[lhs isEqualToString:rhs];
850 /* Perl-Compatible RegEx {{{ */
860 Pcre(const char *regex) :
865 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
868 lprintf("%d:%s\n", offset, error);
872 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
873 matches_ = new int[(capture_ + 1) * 3];
881 NSString *operator [](size_t match) {
882 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
885 bool operator ()(NSString *data) {
886 // XXX: length is for characters, not for bytes
887 return operator ()([data UTF8String], [data length]);
890 bool operator ()(const char *data, size_t size) {
892 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
896 /* Mime Addresses {{{ */
897 @interface Address : NSObject {
903 - (NSString *) address;
905 - (void) setAddress:(NSString *)address;
907 + (Address *) addressWithString:(NSString *)string;
908 - (Address *) initWithString:(NSString *)string;
911 @implementation Address
920 - (NSString *) name {
924 - (NSString *) address {
928 - (void) setAddress:(NSString *)address {
930 [address_ autorelease];
934 address_ = [address retain];
937 + (Address *) addressWithString:(NSString *)string {
938 return [[[Address alloc] initWithString:string] autorelease];
941 + (NSArray *) _attributeKeys {
942 return [NSArray arrayWithObjects:@"address", @"name", nil];
945 - (NSArray *) attributeKeys {
946 return [[self class] _attributeKeys];
949 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
950 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
953 - (Address *) initWithString:(NSString *)string {
954 if ((self = [super init]) != nil) {
955 const char *data = [string UTF8String];
956 size_t size = [string length];
958 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
960 if (address_r(data, size)) {
961 name_ = [address_r[1] retain];
962 address_ = [address_r[2] retain];
964 name_ = [string retain];
972 /* CoreGraphics Primitives {{{ */
983 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
986 Set(space, red, green, blue, alpha);
991 CGColorRelease(color_);
998 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1000 float color[] = {red, green, blue, alpha};
1001 color_ = CGColorCreate(space, color);
1004 operator CGColorRef() {
1010 /* Random Global Variables {{{ */
1011 static const int PulseInterval_ = 50000;
1012 static const int ButtonBarWidth_ = 60;
1013 static const int ButtonBarHeight_ = 48;
1014 static const float KeyboardTime_ = 0.3f;
1017 static NSArray *Finishes_;
1019 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1020 #define NotifyConfig_ "/etc/notify.conf"
1022 static bool Queuing_;
1024 static CGColor Blue_;
1025 static CGColor Blueish_;
1026 static CGColor Black_;
1027 static CGColor Off_;
1028 static CGColor White_;
1029 static CGColor Gray_;
1030 static CGColor Green_;
1031 static CGColor Purple_;
1032 static CGColor Purplish_;
1034 static UIColor *InstallingColor_;
1035 static UIColor *RemovingColor_;
1037 static NSString *App_;
1038 static NSString *Home_;
1040 static BOOL Advanced_;
1041 static BOOL Ignored_;
1043 static UIFont *Font12_;
1044 static UIFont *Font12Bold_;
1045 static UIFont *Font14_;
1046 static UIFont *Font18Bold_;
1047 static UIFont *Font22Bold_;
1049 static const char *Machine_ = NULL;
1050 static const NSString *System_ = NULL;
1051 static const NSString *SerialNumber_ = nil;
1052 static const NSString *ChipID_ = nil;
1053 static const NSString *Token_ = nil;
1054 static const NSString *UniqueID_ = nil;
1055 static const NSString *Build_ = nil;
1056 static const NSString *Product_ = nil;
1057 static const NSString *Safari_ = nil;
1059 static CFLocaleRef Locale_;
1060 static NSArray *Languages_;
1061 static CGColorSpaceRef space_;
1063 static bool reload_;
1065 static NSDictionary *SectionMap_;
1066 static NSMutableDictionary *Metadata_;
1067 static _transient NSMutableDictionary *Settings_;
1068 static _transient NSString *Role_;
1069 static _transient NSMutableDictionary *Packages_;
1070 static _transient NSMutableDictionary *Sections_;
1071 static _transient NSMutableDictionary *Sources_;
1072 static bool Changed_;
1073 static NSDate *now_;
1075 static bool IsWildcat_;
1078 static NSMutableArray *Documents_;
1082 /* Display Helpers {{{ */
1083 inline float Interpolate(float begin, float end, float fraction) {
1084 return (end - begin) * fraction + begin;
1087 /* XXX: localize this! */
1088 NSString *SizeString(double size) {
1089 bool negative = size < 0;
1094 while (size > 1024) {
1099 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1101 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1104 static _finline CFStringRef CFCString(const char *value) {
1105 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1108 const char *StripVersion_(const char *version) {
1109 const char *colon(strchr(version, ':'));
1111 version = colon + 1;
1115 CFStringRef StripVersion(const char *version) {
1116 const char *colon(strchr(version, ':'));
1118 version = colon + 1;
1119 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1121 return CFCString(version);
1124 NSString *LocalizeSection(NSString *section) {
1125 static Pcre title_r("^(.*?) \\((.*)\\)$");
1126 if (title_r(section)) {
1127 NSString *parent(title_r[1]);
1128 NSString *child(title_r[2]);
1130 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1131 LocalizeSection(parent),
1132 LocalizeSection(child)
1136 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1139 NSString *Simplify(NSString *title) {
1140 const char *data = [title UTF8String];
1141 size_t size = [title length];
1143 static Pcre square_r("^\\[(.*)\\]$");
1144 if (square_r(data, size))
1145 return Simplify(square_r[1]);
1147 static Pcre paren_r("^\\((.*)\\)$");
1148 if (paren_r(data, size))
1149 return Simplify(paren_r[1]);
1151 static Pcre title_r("^(.*?) \\((.*)\\)$");
1152 if (title_r(data, size))
1153 return Simplify(title_r[1]);
1159 NSString *GetLastUpdate() {
1160 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1163 return UCLocalize("NEVER_OR_UNKNOWN");
1165 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1166 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1168 CFRelease(formatter);
1170 return [(NSString *) formatted autorelease];
1173 bool isSectionVisible(NSString *section) {
1174 NSDictionary *metadata([Sections_ objectForKey:section]);
1175 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1176 return hidden == nil || ![hidden boolValue];
1179 /* Delegate Prototypes {{{ */
1183 @interface NSObject (ProgressDelegate)
1186 @protocol ProgressDelegate
1187 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1188 - (void) setProgressTitle:(NSString *)title;
1189 - (void) setProgressPercent:(float)percent;
1190 - (void) startProgress;
1191 - (void) addProgressOutput:(NSString *)output;
1192 - (bool) isCancelling:(size_t)received;
1195 @protocol ConfigurationDelegate
1196 - (void) repairWithSelector:(SEL)selector;
1197 - (void) setConfigurationData:(NSString *)data;
1202 @protocol CydiaDelegate
1203 - (void) setPackageView:(PackageView *)view;
1204 - (void) clearPackage:(Package *)package;
1205 - (void) installPackage:(Package *)package;
1206 - (void) removePackage:(Package *)package;
1207 - (void) slideUp:(UIActionSheet *)alert;
1208 - (void) distUpgrade;
1209 - (void) updateData;
1211 - (void) askForSettings;
1212 - (UIProgressHUD *) addProgressHUD;
1213 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1214 - (RVPage *) pageForPackage:(NSString *)name;
1215 - (PackageView *) packageView;
1219 /* Status Delegation {{{ */
1221 public pkgAcquireStatus
1224 _transient NSObject<ProgressDelegate> *delegate_;
1232 void setDelegate(id delegate) {
1233 delegate_ = delegate;
1236 NSObject<ProgressDelegate> *getDelegate() const {
1240 virtual bool MediaChange(std::string media, std::string drive) {
1244 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1247 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1248 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1249 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1252 virtual void Done(pkgAcquire::ItemDesc &item) {
1255 virtual void Fail(pkgAcquire::ItemDesc &item) {
1257 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1258 item.Owner->Status == pkgAcquire::Item::StatDone
1262 std::string &error(item.Owner->ErrorText);
1266 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1267 NSArray *fields([description componentsSeparatedByString:@" "]);
1268 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1270 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1271 withObject:[NSArray arrayWithObjects:
1272 [NSString stringWithUTF8String:error.c_str()],
1279 virtual bool Pulse(pkgAcquire *Owner) {
1280 bool value = pkgAcquireStatus::Pulse(Owner);
1283 double(CurrentBytes + CurrentItems) /
1284 double(TotalBytes + TotalItems)
1287 [delegate_ setProgressPercent:percent];
1288 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1291 virtual void Start() {
1292 [delegate_ startProgress];
1295 virtual void Stop() {
1299 /* Progress Delegation {{{ */
1304 _transient id<ProgressDelegate> delegate_;
1308 virtual void Update() {
1309 /*if (abs(Percent - percent_) > 2)
1310 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1314 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1315 [delegate_ setProgressPercent:(Percent / 100)];*/
1325 void setDelegate(id delegate) {
1326 delegate_ = delegate;
1329 id getDelegate() const {
1333 virtual void Done() {
1335 //[delegate_ setProgressPercent:1];
1340 /* Database Interface {{{ */
1341 typedef std::map< unsigned long, _H<Source> > SourceMap;
1343 @interface Database : NSObject {
1349 pkgCacheFile cache_;
1350 pkgDepCache::Policy *policy_;
1351 pkgRecords *records_;
1352 pkgProblemResolver *resolver_;
1353 pkgAcquire *fetcher_;
1355 SPtr<pkgPackageManager> manager_;
1356 pkgSourceList *list_;
1359 NSMutableArray *packages_;
1361 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1370 + (Database *) sharedInstance;
1373 - (void) _readCydia:(NSNumber *)fd;
1374 - (void) _readStatus:(NSNumber *)fd;
1375 - (void) _readOutput:(NSNumber *)fd;
1379 - (Package *) packageWithName:(NSString *)name;
1381 - (pkgCacheFile &) cache;
1382 - (pkgDepCache::Policy *) policy;
1383 - (pkgRecords *) records;
1384 - (pkgProblemResolver *) resolver;
1385 - (pkgAcquire &) fetcher;
1386 - (pkgSourceList &) list;
1387 - (NSArray *) packages;
1388 - (NSArray *) sources;
1389 - (void) reloadData;
1397 - (void) setVisible;
1399 - (void) updateWithStatus:(Status &)status;
1401 - (void) setDelegate:(id)delegate;
1402 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1405 /* Delegate Helpers {{{ */
1406 @implementation NSObject(ProgressDelegate)
1408 - (void) _setProgressErrorPackage:(NSArray *)args {
1409 [self performSelector:@selector(setProgressError:forPackage:)
1410 withObject:[args objectAtIndex:0]
1411 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1415 - (void) _setProgressErrorTitle:(NSArray *)args {
1416 [self performSelector:@selector(setProgressError:withTitle:)
1417 withObject:[args objectAtIndex:0]
1418 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1422 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1423 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1424 withObject:[NSArray arrayWithObjects:error, title, nil]
1429 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1430 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1431 // XXX: holy typecast batman!
1432 [(id<ProgressDelegate>)self setProgressError:error withTitle:(package == nil ? id : [package name])];
1438 /* Source Class {{{ */
1439 @interface Source : NSObject {
1440 CYString depiction_;
1441 CYString description_;
1447 CYString distribution_;
1452 NSString *authority_;
1454 CYString defaultIcon_;
1456 NSDictionary *record_;
1460 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1462 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1464 - (NSString *) depictionForPackage:(NSString *)package;
1465 - (NSString *) supportForPackage:(NSString *)package;
1467 - (NSDictionary *) record;
1471 - (NSString *) distribution;
1472 - (NSString *) type;
1474 - (NSString *) host;
1476 - (NSString *) name;
1477 - (NSString *) description;
1478 - (NSString *) label;
1479 - (NSString *) origin;
1480 - (NSString *) version;
1482 - (NSString *) defaultIcon;
1486 @implementation Source
1490 distribution_.clear();
1493 description_.clear();
1499 defaultIcon_.clear();
1501 if (record_ != nil) {
1511 if (authority_ != nil) {
1512 [authority_ release];
1522 + (NSArray *) _attributeKeys {
1523 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1526 - (NSArray *) attributeKeys {
1527 return [[self class] _attributeKeys];
1530 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1531 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1534 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1537 trusted_ = index->IsTrusted();
1539 uri_.set(pool, index->GetURI());
1540 distribution_.set(pool, index->GetDist());
1541 type_.set(pool, index->GetType());
1543 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1544 if (dindex != NULL) {
1546 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1549 pkgTagFile tags(&fd);
1551 pkgTagSection section;
1558 {"default-icon", &defaultIcon_},
1559 {"depiction", &depiction_},
1560 {"description", &description_},
1562 {"origin", &origin_},
1563 {"support", &support_},
1564 {"version", &version_},
1567 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1568 const char *start, *end;
1570 if (section.Find(names[i].name_, start, end)) {
1571 CYString &value(*names[i].value_);
1572 value.set(pool, start, end - start);
1578 record_ = [Sources_ objectForKey:[self key]];
1580 record_ = [record_ retain];
1582 NSURL *url([NSURL URLWithString:uri_]);
1586 host_ = [[host_ lowercaseString] retain];
1591 authority_ = [url path];
1593 if (authority_ != nil)
1594 authority_ = [authority_ retain];
1597 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1598 if ((self = [super init]) != nil) {
1599 [self setMetaIndex:index inPool:pool];
1603 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1604 NSDictionary *lhr = [self record];
1605 NSDictionary *rhr = [source record];
1608 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1610 NSString *lhs = [self name];
1611 NSString *rhs = [source name];
1613 if ([lhs length] != 0 && [rhs length] != 0) {
1614 unichar lhc = [lhs characterAtIndex:0];
1615 unichar rhc = [rhs characterAtIndex:0];
1617 if (isalpha(lhc) && !isalpha(rhc))
1618 return NSOrderedAscending;
1619 else if (!isalpha(lhc) && isalpha(rhc))
1620 return NSOrderedDescending;
1623 return [lhs compare:rhs options:LaxCompareOptions_];
1626 - (NSString *) depictionForPackage:(NSString *)package {
1627 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1630 - (NSString *) supportForPackage:(NSString *)package {
1631 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1634 - (NSDictionary *) record {
1642 - (NSString *) uri {
1646 - (NSString *) distribution {
1647 return distribution_;
1650 - (NSString *) type {
1654 - (NSString *) key {
1655 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1658 - (NSString *) host {
1662 - (NSString *) name {
1663 return origin_.empty() ? authority_ : origin_;
1666 - (NSString *) description {
1667 return description_;
1670 - (NSString *) label {
1671 return label_.empty() ? authority_ : label_;
1674 - (NSString *) origin {
1678 - (NSString *) version {
1682 - (NSString *) defaultIcon {
1683 return defaultIcon_;
1688 /* Relationship Class {{{ */
1689 @interface Relationship : NSObject {
1694 - (NSString *) type;
1696 - (NSString *) name;
1700 @implementation Relationship
1708 - (NSString *) type {
1716 - (NSString *) name {
1723 /* Package Class {{{ */
1724 @interface Package : NSObject {
1728 pkgCache::VerIterator version_;
1729 pkgCache::PkgIterator iterator_;
1730 _transient Database *database_;
1731 pkgCache::VerFileIterator file_;
1738 NSString *section$_;
1745 CYString installed_;
1751 CYString depiction_;
1762 NSMutableArray *tags_;
1765 NSArray *relationships_;
1767 NSMutableDictionary *metadata_;
1768 _transient NSDate *firstSeen_;
1769 _transient NSDate *lastSeen_;
1773 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1774 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1776 - (pkgCache::PkgIterator) iterator;
1779 - (NSString *) section;
1780 - (NSString *) simpleSection;
1782 - (NSString *) longSection;
1783 - (NSString *) shortSection;
1787 - (Address *) maintainer;
1789 - (NSString *) longDescription;
1790 - (NSString *) shortDescription;
1793 - (NSMutableDictionary *) metadata;
1795 - (BOOL) subscribed;
1798 - (NSString *) latest;
1799 - (NSString *) installed;
1800 - (BOOL) uninstalled;
1803 - (BOOL) upgradableAndEssential:(BOOL)essential;
1806 - (BOOL) unfiltered;
1810 - (BOOL) halfConfigured;
1811 - (BOOL) halfInstalled;
1813 - (NSString *) mode;
1815 - (void) setVisible;
1818 - (NSString *) name;
1820 - (NSString *) homepage;
1821 - (NSString *) depiction;
1822 - (Address *) author;
1824 - (NSString *) support;
1826 - (NSArray *) files;
1827 - (NSArray *) relationships;
1828 - (NSArray *) warnings;
1829 - (NSArray *) applications;
1831 - (Source *) source;
1832 - (NSString *) role;
1834 - (BOOL) matches:(NSString *)text;
1836 - (bool) hasSupportingRole;
1837 - (BOOL) hasTag:(NSString *)tag;
1838 - (NSString *) primaryPurpose;
1839 - (NSArray *) purposes;
1840 - (bool) isCommercial;
1842 - (CYString &) cyname;
1844 - (uint32_t) compareBySection:(NSArray *)sections;
1846 - (uint32_t) compareForChanges;
1851 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1852 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1853 - (bool) isInstalledAndVisible:(NSNumber *)number;
1854 - (bool) isVisibleInSection:(NSString *)section;
1855 - (bool) isVisibleInSource:(Source *)source;
1859 uint32_t PackageChangesRadix(Package *self, void *) {
1864 uint32_t timestamp : 30;
1865 uint32_t ignored : 1;
1866 uint32_t upgradable : 1;
1870 bool upgradable([self upgradableAndEssential:YES]);
1871 value.bits.upgradable = upgradable ? 1 : 0;
1874 value.bits.timestamp = 0;
1875 value.bits.ignored = [self ignored] ? 0 : 1;
1876 value.bits.upgradable = 1;
1878 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1879 value.bits.ignored = 0;
1880 value.bits.upgradable = 0;
1883 return _not(uint32_t) - value.key;
1886 _finline static void Stifle(uint8_t &value) {
1889 uint32_t PackagePrefixRadix(Package *self, void *context) {
1890 size_t offset(reinterpret_cast<size_t>(context));
1891 CYString &name([self cyname]);
1893 size_t size(name.size());
1896 char *text(name.data());
1899 if (!isdigit(text[0]))
1903 while (size != digits && isdigit(text[digits]))
1913 if (offset == 0 && zeros != 0) {
1914 memset(data, '0', zeros);
1915 memcpy(data + zeros, text, 4 - zeros);
1917 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1918 if (size <= offset - zeros)
1921 text += offset - zeros;
1922 size -= offset - zeros;
1925 memcpy(data, text, 4);
1927 memcpy(data, text, size);
1928 memset(data + size, 0, 4 - size);
1931 for (size_t i(0); i != 4; ++i)
1932 if (isalpha(data[i]))
1937 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1939 /* XXX: ntohl may be more honest */
1940 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1943 CYString &(*PackageName)(Package *self, SEL sel);
1945 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1946 _profile(PackageNameCompare)
1947 CYString &lhi(PackageName(lhs, @selector(cyname)));
1948 CYString &rhi(PackageName(rhs, @selector(cyname)));
1949 CFStringRef lhn(lhi), rhn(rhi);
1952 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1953 else if (rhn == NULL)
1954 return NSOrderedDescending;
1956 _profile(PackageNameCompare$NumbersLast)
1957 if (!lhi.empty() && !rhi.empty()) {
1958 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1959 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1960 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1961 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1962 return lha ? NSOrderedAscending : NSOrderedDescending;
1966 CFIndex length = CFStringGetLength(lhn);
1968 _profile(PackageNameCompare$Compare)
1969 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1974 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1975 return PackageNameCompare(*lhs, *rhs, context);
1978 struct PackageNameOrdering :
1979 std::binary_function<Package *, Package *, bool>
1981 _finline bool operator ()(Package *lhs, Package *rhs) const {
1982 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1986 @implementation Package
1988 - (NSString *) description {
1989 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1995 if (section$_ != nil)
1996 [section$_ release];
2001 if (sponsor$_ != nil)
2002 [sponsor$_ release];
2003 if (author$_ != nil)
2010 if (relationships_ != nil)
2011 [relationships_ release];
2012 if (metadata_ != nil)
2013 [metadata_ release];
2018 + (NSString *) webScriptNameForSelector:(SEL)selector {
2019 if (selector == @selector(hasTag:))
2025 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2026 return [self webScriptNameForSelector:selector] == nil;
2029 + (NSArray *) _attributeKeys {
2030 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];
2033 - (NSArray *) attributeKeys {
2034 return [[self class] _attributeKeys];
2037 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2038 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2048 _profile(Package$parse)
2049 pkgRecords::Parser *parser;
2051 _profile(Package$parse$Lookup)
2052 parser = &[database_ records]->Lookup(file_);
2057 _profile(Package$parse$Find)
2063 {"depiction", &depiction_},
2064 {"homepage", &homepage_},
2065 {"website", &website},
2067 {"support", &support_},
2068 {"sponsor", &sponsor_},
2069 {"author", &author_},
2072 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2073 const char *start, *end;
2075 if (parser->Find(names[i].name_, start, end)) {
2076 CYString &value(*names[i].value_);
2077 _profile(Package$parse$Value)
2078 value.set(pool_, start, end - start);
2084 _profile(Package$parse$Tagline)
2085 const char *start, *end;
2086 if (parser->ShortDesc(start, end)) {
2087 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2090 while (stop != start && stop[-1] == '\r')
2092 tagline_.set(pool_, start, stop - start);
2096 _profile(Package$parse$Retain)
2097 if (homepage_.empty())
2098 homepage_ = website;
2099 if (homepage_ == depiction_)
2105 - (void) setVisible {
2106 visible_ = required_ && [self unfiltered];
2109 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2110 if ((self = [super init]) != nil) {
2111 _profile(Package$initWithVersion)
2112 @synchronized (database) {
2113 era_ = [database era];
2117 iterator_ = version.ParentPkg();
2118 database_ = database;
2120 _profile(Package$initWithVersion$Latest)
2121 latest_ = (NSString *) StripVersion(version_.VerStr());
2124 pkgCache::VerIterator current;
2125 _profile(Package$initWithVersion$Versions)
2126 current = iterator_.CurrentVer();
2128 installed_.set(pool_, StripVersion_(current.VerStr()));
2130 if (!version_.end())
2131 file_ = version_.FileList();
2133 pkgCache &cache([database_ cache]);
2134 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2138 _profile(Package$initWithVersion$Name)
2139 id_.set(pool_, iterator_.Name());
2140 name_.set(pool, iterator_.Display());
2144 _profile(Package$initWithVersion$Source)
2145 source_ = [database_ getSource:file_.File()];
2154 _profile(Package$initWithVersion$Tags)
2155 pkgCache::TagIterator tag(iterator_.TagList());
2157 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2159 const char *name(tag.Name());
2160 [tags_ addObject:(NSString *)CFCString(name)];
2161 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2162 role_ = (NSString *) CFCString(name + 6);
2163 if (required_ && strncmp(name, "require::", 9) == 0 && (
2168 } while (!tag.end());
2172 bool changed(false);
2173 NSString *key([id_ lowercaseString]);
2175 _profile(Package$initWithVersion$Metadata)
2176 metadata_ = [Packages_ objectForKey:key];
2178 if (metadata_ == nil) {
2181 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2182 firstSeen_, @"FirstSeen",
2183 latest_, @"LastVersion",
2188 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2189 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2191 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2192 subscribed_ = [subscribed boolValue];
2194 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2196 if (firstSeen_ == nil) {
2197 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2198 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2202 if (version == nil) {
2203 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2205 } else if (![version isEqualToString:latest_]) {
2206 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2208 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2213 metadata_ = [metadata_ retain];
2216 [Packages_ setObject:metadata_ forKey:key];
2221 _profile(Package$initWithVersion$Section)
2222 section_.set(pool_, iterator_.Section());
2225 obsolete_ = [self hasTag:@"cydia::obsolete"];
2226 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2228 } _end } return self;
2231 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2232 @synchronized ([Database class]) {
2233 pkgCache::VerIterator version;
2235 _profile(Package$packageWithIterator$GetCandidateVer)
2236 version = [database policy]->GetCandidateVer(iterator);
2242 return [[[Package alloc]
2243 initWithVersion:version
2250 - (pkgCache::PkgIterator) iterator {
2254 - (NSString *) section {
2255 if (section$_ == nil) {
2256 if (section_.empty())
2259 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2260 NSString *name(section_);
2263 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2264 if (NSString *rename = [value objectForKey:@"Rename"]) {
2269 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2273 - (NSString *) simpleSection {
2274 if (NSString *section = [self section])
2275 return Simplify(section);
2280 - (NSString *) longSection {
2281 return LocalizeSection([self section]);
2284 - (NSString *) shortSection {
2285 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2288 - (NSString *) uri {
2291 pkgIndexFile *index;
2292 pkgCache::PkgFileIterator file(file_.File());
2293 if (![database_ list].FindIndex(file, index))
2295 return [NSString stringWithUTF8String:iterator_->Path];
2296 //return [NSString stringWithUTF8String:file.Site()];
2297 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2301 - (Address *) maintainer {
2304 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2305 const std::string &maintainer(parser->Maintainer());
2306 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2310 return version_.end() ? 0 : version_->InstalledSize;
2313 - (NSString *) longDescription {
2316 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2317 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2319 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2320 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2321 if ([lines count] < 2)
2324 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2325 for (size_t i(1), e([lines count]); i != e; ++i) {
2326 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2327 [trimmed addObject:trim];
2330 return [trimmed componentsJoinedByString:@"\n"];
2333 - (NSString *) shortDescription {
2338 _profile(Package$index)
2339 CFStringRef name((CFStringRef) [self name]);
2340 if (CFStringGetLength(name) == 0)
2342 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2343 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2345 return toupper(character);
2349 - (NSMutableDictionary *) metadata {
2354 if (subscribed_ && lastSeen_ != nil)
2359 - (BOOL) subscribed {
2364 NSDictionary *metadata([self metadata]);
2365 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2366 return [ignored boolValue];
2371 - (NSString *) latest {
2375 - (NSString *) installed {
2379 - (BOOL) uninstalled {
2380 return installed_.empty();
2384 return !version_.end();
2387 - (BOOL) upgradableAndEssential:(BOOL)essential {
2388 _profile(Package$upgradableAndEssential)
2389 pkgCache::VerIterator current(iterator_.CurrentVer());
2391 return essential && essential_ && visible_;
2393 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2397 - (BOOL) essential {
2402 return [database_ cache][iterator_].InstBroken();
2405 - (BOOL) unfiltered {
2406 NSString *section([self section]);
2407 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2415 unsigned char current(iterator_->CurrentState);
2416 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2419 - (BOOL) halfConfigured {
2420 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2423 - (BOOL) halfInstalled {
2424 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2428 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2429 return state.Mode != pkgDepCache::ModeKeep;
2432 - (NSString *) mode {
2433 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2435 switch (state.Mode) {
2436 case pkgDepCache::ModeDelete:
2437 if ((state.iFlags & pkgDepCache::Purge) != 0)
2441 case pkgDepCache::ModeKeep:
2442 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2443 return @"REINSTALL";
2444 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2448 case pkgDepCache::ModeInstall:
2449 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2450 return @"REINSTALL";
2451 else*/ switch (state.Status) {
2453 return @"DOWNGRADE";
2459 return @"NEW_INSTALL";
2470 - (NSString *) name {
2471 return name_.empty() ? id_ : name_;
2474 - (UIImage *) icon {
2475 NSString *section = [self simpleSection];
2479 if ([icon_ hasPrefix:@"file:///"])
2480 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2481 if (icon == nil) if (section != nil)
2482 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2483 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2484 if ([dicon hasPrefix:@"file:///"])
2485 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2487 icon = [UIImage applicationImageNamed:@"unknown.png"];
2491 - (NSString *) homepage {
2495 - (NSString *) depiction {
2496 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2499 - (Address *) sponsor {
2500 if (sponsor$_ == nil) {
2501 if (sponsor_.empty())
2503 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2507 - (Address *) author {
2508 if (author$_ == nil) {
2509 if (author_.empty())
2511 author$_ = [[Address addressWithString:author_] retain];
2515 - (NSString *) support {
2516 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2519 - (NSArray *) files {
2520 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2521 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2524 fin.open([path UTF8String]);
2529 while (std::getline(fin, line))
2530 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2535 - (NSArray *) relationships {
2536 return relationships_;
2539 - (NSArray *) warnings {
2540 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2541 const char *name(iterator_.Name());
2543 size_t length(strlen(name));
2544 if (length < 2) invalid:
2545 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2546 else for (size_t i(0); i != length; ++i)
2548 /* XXX: technically this is not allowed */
2549 (name[i] < 'A' || name[i] > 'Z') &&
2550 (name[i] < 'a' || name[i] > 'z') &&
2551 (name[i] < '0' || name[i] > '9') &&
2552 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2555 if (strcmp(name, "cydia") != 0) {
2558 bool _private = false;
2561 bool repository = [[self section] isEqualToString:@"Repositories"];
2563 if (NSArray *files = [self files])
2564 for (NSString *file in files)
2565 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2567 else if (!user && [file isEqualToString:@"/User"])
2569 else if (!_private && [file isEqualToString:@"/private"])
2571 else if (!stash && [file isEqualToString:@"/var/stash"])
2574 /* XXX: this is not sensitive enough. only some folders are valid. */
2575 if (cydia && !repository)
2576 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2578 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2580 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2582 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2585 return [warnings count] == 0 ? nil : warnings;
2588 - (NSArray *) applications {
2589 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2591 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2593 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2594 if (NSArray *files = [self files])
2595 for (NSString *file in files)
2596 if (application_r(file)) {
2597 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2598 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2599 if ([id isEqualToString:me])
2602 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2604 display = application_r[1];
2606 NSString *bundle([file stringByDeletingLastPathComponent]);
2607 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2608 if (icon == nil || [icon length] == 0)
2610 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2612 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2613 [applications addObject:application];
2615 [application addObject:id];
2616 [application addObject:display];
2617 [application addObject:url];
2620 return [applications count] == 0 ? nil : applications;
2623 - (Source *) source {
2625 @synchronized (database_) {
2626 if ([database_ era] != era_ || file_.end())
2629 source_ = [database_ getSource:file_.File()];
2641 - (NSString *) role {
2645 - (BOOL) matches:(NSString *)text {
2651 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2652 if (range.location != NSNotFound)
2655 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2656 if (range.location != NSNotFound)
2659 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2660 if (range.location != NSNotFound)
2666 - (bool) hasSupportingRole {
2669 if ([role_ isEqualToString:@"enduser"])
2671 if ([Role_ isEqualToString:@"User"])
2673 if ([role_ isEqualToString:@"hacker"])
2675 if ([Role_ isEqualToString:@"Hacker"])
2677 if ([role_ isEqualToString:@"developer"])
2679 if ([Role_ isEqualToString:@"Developer"])
2684 - (BOOL) hasTag:(NSString *)tag {
2685 return tags_ == nil ? NO : [tags_ containsObject:tag];
2688 - (NSString *) primaryPurpose {
2689 for (NSString *tag in tags_)
2690 if ([tag hasPrefix:@"purpose::"])
2691 return [tag substringFromIndex:9];
2695 - (NSArray *) purposes {
2696 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2697 for (NSString *tag in tags_)
2698 if ([tag hasPrefix:@"purpose::"])
2699 [purposes addObject:[tag substringFromIndex:9]];
2700 return [purposes count] == 0 ? nil : purposes;
2703 - (bool) isCommercial {
2704 return [self hasTag:@"cydia::commercial"];
2707 - (CYString &) cyname {
2708 return name_.empty() ? id_ : name_;
2711 - (uint32_t) compareBySection:(NSArray *)sections {
2712 NSString *section([self section]);
2713 for (size_t i(0), e([sections count]); i != e; ++i) {
2714 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2718 return _not(uint32_t);
2721 - (uint32_t) compareForChanges {
2726 uint32_t timestamp : 30;
2727 uint32_t ignored : 1;
2728 uint32_t upgradable : 1;
2732 bool upgradable([self upgradableAndEssential:YES]);
2733 value.bits.upgradable = upgradable ? 1 : 0;
2736 value.bits.timestamp = 0;
2737 value.bits.ignored = [self ignored] ? 0 : 1;
2738 value.bits.upgradable = 1;
2740 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2741 value.bits.ignored = 0;
2742 value.bits.upgradable = 0;
2745 return _not(uint32_t) - value.key;
2749 pkgProblemResolver *resolver = [database_ resolver];
2750 resolver->Clear(iterator_);
2751 resolver->Protect(iterator_);
2755 pkgProblemResolver *resolver = [database_ resolver];
2756 resolver->Clear(iterator_);
2757 resolver->Protect(iterator_);
2758 pkgCacheFile &cache([database_ cache]);
2759 cache->MarkInstall(iterator_, false);
2760 pkgDepCache::StateCache &state((*cache)[iterator_]);
2761 if (!state.Install())
2762 cache->SetReInstall(iterator_, true);
2766 pkgProblemResolver *resolver = [database_ resolver];
2767 resolver->Clear(iterator_);
2768 resolver->Protect(iterator_);
2769 resolver->Remove(iterator_);
2770 [database_ cache]->MarkDelete(iterator_, true);
2773 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2774 _profile(Package$isUnfilteredAndSearchedForBy)
2777 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2778 value &= [self unfiltered];
2781 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2782 value &= [self matches:search];
2789 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2790 if ([search length] == 0)
2793 _profile(Package$isUnfilteredAndSelectedForBy)
2796 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2797 value &= [self unfiltered];
2800 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2801 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2808 - (bool) isInstalledAndVisible:(NSNumber *)number {
2809 return (![number boolValue] || [self visible]) && ![self uninstalled];
2812 - (bool) isVisibleInSection:(NSString *)name {
2813 NSString *section = [self section];
2818 section == nil && [name length] == 0 ||
2819 [name isEqualToString:section]
2823 - (bool) isVisibleInSource:(Source *)source {
2824 return [self source] == source && [self visible];
2829 /* Section Class {{{ */
2830 @interface Section : NSObject {
2835 NSString *localized_;
2838 - (NSComparisonResult) compareByLocalized:(Section *)section;
2839 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2840 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2841 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2842 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2843 - (NSString *) name;
2850 - (void) addToCount;
2852 - (void) setCount:(size_t)count;
2853 - (NSString *) localized;
2857 @implementation Section
2861 if (localized_ != nil)
2862 [localized_ release];
2866 - (NSComparisonResult) compareByLocalized:(Section *)section {
2867 NSString *lhs(localized_);
2868 NSString *rhs([section localized]);
2870 /*if ([lhs length] != 0 && [rhs length] != 0) {
2871 unichar lhc = [lhs characterAtIndex:0];
2872 unichar rhc = [rhs characterAtIndex:0];
2874 if (isalpha(lhc) && !isalpha(rhc))
2875 return NSOrderedAscending;
2876 else if (!isalpha(lhc) && isalpha(rhc))
2877 return NSOrderedDescending;
2880 return [lhs compare:rhs options:LaxCompareOptions_];
2883 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2884 if ((self = [self initWithName:name localize:NO]) != nil) {
2885 if (localized != nil)
2886 localized_ = [localized retain];
2890 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2891 return [self initWithName:name row:0 localize:localize];
2894 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2895 if ((self = [super init]) != nil) {
2896 name_ = [name retain];
2900 localized_ = [LocalizeSection(name_) retain];
2904 /* XXX: localize the index thingees */
2905 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2906 if ((self = [super init]) != nil) {
2907 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2913 - (NSString *) name {
2933 - (void) addToCount {
2937 - (void) setCount:(size_t)count {
2941 - (NSString *) localized {
2948 static NSString *Colon_;
2949 static NSString *Error_;
2950 static NSString *Warning_;
2952 /* Database Implementation {{{ */
2953 @implementation Database
2955 + (Database *) sharedInstance {
2956 static Database *instance;
2957 if (instance == nil)
2958 instance = [[Database alloc] init];
2968 NSRecycleZone(zone_);
2969 // XXX: malloc_destroy_zone(zone_);
2970 apr_pool_destroy(pool_);
2974 - (void) _readCydia:(NSNumber *)fd { _pooled
2975 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2976 std::istream is(&ib);
2979 static Pcre finish_r("^finish:([^:]*)$");
2981 while (std::getline(is, line)) {
2982 const char *data(line.c_str());
2983 size_t size = line.size();
2984 lprintf("C:%s\n", data);
2986 if (finish_r(data, size)) {
2987 NSString *finish = finish_r[1];
2988 int index = [Finishes_ indexOfObject:finish];
2989 if (index != INT_MAX && index > Finish_)
2997 - (void) _readStatus:(NSNumber *)fd { _pooled
2998 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2999 std::istream is(&ib);
3002 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3003 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3005 while (std::getline(is, line)) {
3006 const char *data(line.c_str());
3007 size_t size(line.size());
3008 lprintf("S:%s\n", data);
3010 if (conffile_r(data, size)) {
3011 [delegate_ setConfigurationData:conffile_r[1]];
3012 } else if (strncmp(data, "status: ", 8) == 0) {
3013 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3014 [delegate_ setProgressTitle:string];
3015 } else if (pmstatus_r(data, size)) {
3016 std::string type([pmstatus_r[1] UTF8String]);
3017 NSString *id = pmstatus_r[2];
3019 float percent([pmstatus_r[3] floatValue]);
3020 [delegate_ setProgressPercent:(percent / 100)];
3022 NSString *string = pmstatus_r[4];
3024 if (type == "pmerror")
3025 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3026 withObject:[NSArray arrayWithObjects:string, id, nil]
3029 else if (type == "pmstatus") {
3030 [delegate_ setProgressTitle:string];
3031 } else if (type == "pmconffile")
3032 [delegate_ setConfigurationData:string];
3034 lprintf("E:unknown pmstatus\n");
3036 lprintf("E:unknown status\n");
3042 - (void) _readOutput:(NSNumber *)fd { _pooled
3043 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3044 std::istream is(&ib);
3047 while (std::getline(is, line)) {
3048 lprintf("O:%s\n", line.c_str());
3049 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3059 - (Package *) packageWithName:(NSString *)name {
3060 @synchronized ([Database class]) {
3061 if (static_cast<pkgDepCache *>(cache_) == NULL)
3063 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3064 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3067 - (Database *) init {
3068 if ((self = [super init]) != nil) {
3075 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3076 apr_pool_create(&pool_, NULL);
3078 packages_ = [[NSMutableArray alloc] init];
3082 _assert(pipe(fds) != -1);
3085 _config->Set("APT::Keep-Fds::", cydiafd_);
3086 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3089 detachNewThreadSelector:@selector(_readCydia:)
3091 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3094 _assert(pipe(fds) != -1);
3098 detachNewThreadSelector:@selector(_readStatus:)
3100 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3103 _assert(pipe(fds) != -1);
3104 _assert(dup2(fds[0], 0) != -1);
3105 _assert(close(fds[0]) != -1);
3107 input_ = fdopen(fds[1], "a");
3109 _assert(pipe(fds) != -1);
3110 _assert(dup2(fds[1], 1) != -1);
3111 _assert(close(fds[1]) != -1);
3114 detachNewThreadSelector:@selector(_readOutput:)
3116 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3121 - (pkgCacheFile &) cache {
3125 - (pkgDepCache::Policy *) policy {
3129 - (pkgRecords *) records {
3133 - (pkgProblemResolver *) resolver {
3137 - (pkgAcquire &) fetcher {
3141 - (pkgSourceList &) list {
3145 - (NSArray *) packages {
3149 - (NSArray *) sources {
3150 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3151 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3152 [sources addObject:i->second];
3156 - (NSArray *) issues {
3157 if (cache_->BrokenCount() == 0)
3160 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3162 for (Package *package in packages_) {
3163 if (![package broken])
3165 pkgCache::PkgIterator pkg([package iterator]);
3167 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3168 [entry addObject:[package name]];
3169 [issues addObject:entry];
3171 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3175 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3176 pkgCache::DepIterator start;
3177 pkgCache::DepIterator end;
3178 dep.GlobOr(start, end); // ++dep
3180 if (!cache_->IsImportantDep(end))
3182 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3185 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3186 [entry addObject:failure];
3187 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3189 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3190 if (Package *package = [self packageWithName:name])
3191 name = [package name];
3192 [failure addObject:name];
3194 pkgCache::PkgIterator target(start.TargetPkg());
3195 if (target->ProvidesList != 0)
3196 [failure addObject:@"?"];
3198 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3200 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3201 else if (!cache_[target].CandidateVerIter(cache_).end())
3202 [failure addObject:@"-"];
3203 else if (target->ProvidesList == 0)
3204 [failure addObject:@"!"];
3206 [failure addObject:@"%"];
3210 if (start.TargetVer() != 0)
3211 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3222 - (bool) popErrorWithTitle:(NSString *)title {
3224 std::string message;
3226 while (!_error->empty()) {
3228 bool warning(!_error->PopMessage(error));
3232 size_t size(error.size());
3233 if (size == 0 || error[size - 1] != '\n')
3235 error.resize(size - 1);
3237 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3239 if (!message.empty())
3244 if (fatal && !message.empty())
3245 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3250 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3251 return [self popErrorWithTitle:title] || !success;
3254 - (void) reloadData { _pooled
3255 @synchronized ([Database class]) {
3256 @synchronized (self) {
3260 [packages_ removeAllObjects];
3286 apr_pool_clear(pool_);
3287 NSRecycleZone(zone_);
3289 int chk(creat("/tmp/cydia.chk", 0644));
3293 NSString *title(UCLocalize("DATABASE"));
3296 if (!cache_.Open(progress_, true)) { pop:
3298 bool warning(!_error->PopMessage(error));
3299 lprintf("cache_.Open():[%s]\n", error.c_str());
3301 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3302 [delegate_ repairWithSelector:@selector(configure)];
3303 else if (error == "The package lists or status file could not be parsed or opened.")
3304 [delegate_ repairWithSelector:@selector(update)];
3305 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3306 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3307 // else if (error == "The list of sources could not be read.")
3309 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3318 unlink("/tmp/cydia.chk");
3320 now_ = [[NSDate date] retain];
3322 policy_ = new pkgDepCache::Policy();
3323 records_ = new pkgRecords(cache_);
3324 resolver_ = new pkgProblemResolver(cache_);
3325 fetcher_ = new pkgAcquire(&status_);
3328 list_ = new pkgSourceList();
3329 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3332 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3333 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3337 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3340 if (cache_->BrokenCount() != 0) {
3341 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3344 if (cache_->BrokenCount() != 0) {
3345 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3349 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3355 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3356 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3357 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3358 // XXX: this could be more intelligent
3359 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3360 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3362 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3369 /*std::vector<Package *> packages;
3370 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3371 [packages_ release];
3376 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3377 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3378 //packages.push_back(package);
3379 [packages_ addObject:package];
3383 /*if (packages.empty())
3384 packages_ = [[NSArray alloc] init];
3386 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3389 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3390 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3391 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3399 /*if (!packages.empty())
3400 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3401 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3403 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3405 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3407 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3413 - (void) configure {
3414 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3415 system([dpkg UTF8String]);
3419 // XXX: I don't remember this condition
3424 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3426 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3428 if ([self popErrorWithTitle:title])
3432 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3435 public pkgArchiveCleaner
3438 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3443 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3450 fetcher_->Shutdown();
3452 pkgRecords records(cache_);
3454 lock_ = new FileFd();
3455 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3457 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3459 if ([self popErrorWithTitle:title])
3463 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3466 manager_ = (_system->CreatePM(cache_));
3467 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3474 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3476 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3478 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3480 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3481 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3484 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3489 bool failed = false;
3490 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3491 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3493 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3496 std::string uri = (*item)->DescURI();
3497 std::string error = (*item)->ErrorText;
3499 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3502 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3503 withObject:[NSArray arrayWithObjects:
3504 [NSString stringWithUTF8String:error.c_str()],
3516 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3518 if (_error->PendingError()) {
3523 if (result == pkgPackageManager::Failed) {
3528 if (result != pkgPackageManager::Completed) {
3533 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3535 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3537 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3538 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3541 if (![before isEqualToArray:after])
3546 NSString *title(UCLocalize("UPGRADE"));
3547 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3553 [self updateWithStatus:status_];
3556 - (void) setVisible {
3557 for (Package *package in packages_)
3558 [package setVisible];
3561 - (void) updateWithStatus:(Status &)status {
3562 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3563 NSString *title(UCLocalize("REFRESHING_DATA"));
3566 if (!list.ReadMainList())
3567 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3570 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3571 if ([self popErrorWithTitle:title])
3574 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3575 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
3577 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3581 - (void) setDelegate:(id)delegate {
3582 delegate_ = delegate;
3583 status_.setDelegate(delegate);
3584 progress_.setDelegate(delegate);
3587 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3588 SourceMap::const_iterator i(sources_.find(file->ID));
3589 return i == sources_.end() ? nil : i->second;
3595 /* Confirmation View {{{ */
3596 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3597 if (!iterator.end())
3598 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3599 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3601 pkgCache::PkgIterator package(dep.TargetPkg());
3604 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3611 /* Web Scripting {{{ */
3612 @interface CydiaObject : NSObject {
3616 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3619 @implementation CydiaObject
3622 [indirect_ release];
3626 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3627 if ((self = [super init]) != nil) {
3628 indirect_ = [indirect retain];
3632 + (NSArray *) _attributeKeys {
3633 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3636 - (NSArray *) attributeKeys {
3637 return [[self class] _attributeKeys];
3640 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3641 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3644 - (NSString *) device {
3645 return [[UIDevice currentDevice] uniqueIdentifier];
3648 #if 0 // XXX: implement!
3649 - (NSString *) mac {
3650 if (![indirect_ promptForSensitive:@"Mac Address"])
3654 - (NSString *) serial {
3655 if (![indirect_ promptForSensitive:@"Serial #"])
3659 - (NSString *) firewire {
3660 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3664 - (NSString *) imei {
3665 if (![indirect_ promptForSensitive:@"IMEI"])
3670 + (NSString *) webScriptNameForSelector:(SEL)selector {
3671 if (selector == @selector(close))
3673 else if (selector == @selector(getInstalledPackages))
3674 return @"getInstalledPackages";
3675 else if (selector == @selector(getPackageById:))
3676 return @"getPackageById";
3677 else if (selector == @selector(setAutoPopup:))
3678 return @"setAutoPopup";
3679 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3680 return @"setButtonImage";
3681 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3682 return @"setButtonTitle";
3683 else if (selector == @selector(setFinishHook:))
3684 return @"setFinishHook";
3685 else if (selector == @selector(setPopupHook:))
3686 return @"setPopupHook";
3687 else if (selector == @selector(setSpecial:))
3688 return @"setSpecial";
3689 else if (selector == @selector(setToken:))
3691 else if (selector == @selector(setViewportWidth:))
3692 return @"setViewportWidth";
3693 else if (selector == @selector(supports:))
3695 else if (selector == @selector(stringWithFormat:arguments:))
3697 else if (selector == @selector(localizedStringForKey:value:table:))
3699 else if (selector == @selector(du:))
3701 else if (selector == @selector(statfs:))
3707 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3708 return [self webScriptNameForSelector:selector] == nil;
3711 - (BOOL) supports:(NSString *)feature {
3712 return [feature isEqualToString:@"window.open"];
3715 - (NSArray *) getInstalledPackages {
3716 NSArray *packages([[Database sharedInstance] packages]);
3717 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3718 for (Package *package in installed)
3719 if ([package installed] != nil)
3720 [installed addObject:package];
3724 - (Package *) getPackageById:(NSString *)id {
3725 Package *package([[Database sharedInstance] packageWithName:id]);
3730 - (NSArray *) statfs:(NSString *)path {
3733 if (path == nil || statfs([path UTF8String], &stat) == -1)
3736 return [NSArray arrayWithObjects:
3737 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3738 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3739 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3743 - (NSNumber *) du:(NSString *)path {
3744 NSNumber *value(nil);
3747 _assert(pipe(fds) != -1);
3749 pid_t pid(ExecFork());
3751 _assert(dup2(fds[1], 1) != -1);
3752 _assert(close(fds[0]) != -1);
3753 _assert(close(fds[1]) != -1);
3754 /* XXX: this should probably not use du */
3755 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3760 _assert(close(fds[1]) != -1);
3762 if (FILE *du = fdopen(fds[0], "r")) {
3764 while (fgets(line, sizeof(line), du) != NULL) {
3765 size_t length(strlen(line));
3766 while (length != 0 && line[length - 1] == '\n')
3767 line[--length] = '\0';
3768 if (char *tab = strchr(line, '\t')) {
3770 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3775 } else _assert(close(fds[0]));
3779 if (waitpid(pid, &status, 0) == -1)
3782 else _assert(false);
3791 - (void) setAutoPopup:(BOOL)popup {
3792 [indirect_ setAutoPopup:popup];
3795 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3796 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3799 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3800 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3803 - (void) setSpecial:(id)function {
3804 [indirect_ setSpecial:function];
3807 - (void) setToken:(NSString *)token {
3810 Token_ = [token retain];
3812 [Metadata_ setObject:Token_ forKey:@"Token"];
3816 - (void) setFinishHook:(id)function {
3817 [indirect_ setFinishHook:function];
3820 - (void) setPopupHook:(id)function {
3821 [indirect_ setPopupHook:function];
3824 - (void) setViewportWidth:(float)width {
3825 [indirect_ setViewportWidth:width];
3828 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3829 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3830 unsigned count([arguments count]);
3832 for (unsigned i(0); i != count; ++i)
3833 values[i] = [arguments objectAtIndex:i];
3834 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3837 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3838 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3840 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3842 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3848 @interface CydiaBrowserView : BrowserView {
3849 CydiaObject *cydia_;
3854 @implementation CydiaBrowserView
3861 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3864 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3865 [super webView:sender didClearWindowObject:window forFrame:frame];
3867 WebDataSource *source([frame dataSource]);
3868 NSURLResponse *response([source response]);
3869 NSURL *url([response URL]);
3870 NSString *scheme([url scheme]);
3872 NSHTTPURLResponse *http;
3873 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3874 http = (NSHTTPURLResponse *) response;
3878 NSDictionary *headers([http allHeaderFields]);
3879 NSString *host([url host]);
3880 [self setHeaders:headers forHost:host];
3882 if ([host isEqualToString:@"cydia.saurik.com"] || [scheme isEqualToString:@"file"])
3883 [window setValue:cydia_ forKey:@"cydia"];
3886 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3887 if (System_ != NULL)
3888 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3889 if (Machine_ != NULL)
3890 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3892 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3894 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3897 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3898 NSMutableURLRequest *copy = [request mutableCopy];
3899 [self _setMoreHeaders:copy];
3903 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3904 if ((self = [super initWithBook:book forWidth:width ofClass:[CydiaBrowserView class]]) != nil) {
3905 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3907 WebView *webview([webview_ webView]);
3909 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3911 NSString *application = package == nil ? @"Cydia" : [NSString
3912 stringWithFormat:@"Cydia/%@",
3917 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3919 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3920 if (Product_ != nil)
3921 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3923 [webview setApplicationNameForUserAgent:application];
3929 @protocol ConfirmationViewDelegate
3935 @interface ConfirmationView : CydiaBrowserView {
3936 _transient Database *database_;
3937 UIActionSheet *essential_;
3944 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3948 @implementation ConfirmationView
3955 if (essential_ != nil)
3956 [essential_ release];
3962 [book_ popFromSuperviewAnimated:YES];
3965 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3966 NSString *context([sheet context]);
3968 if ([context isEqualToString:@"remove"]) {
3976 [delegate_ confirm];
3982 } else if ([context isEqualToString:@"unable"]) {
3986 [super alertSheet:sheet buttonClicked:button];
3989 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3990 [super webView:sender didClearWindowObject:window forFrame:frame];
3991 [window setValue:changes_ forKey:@"changes"];
3992 [window setValue:issues_ forKey:@"issues"];
3993 [window setValue:sizes_ forKey:@"sizes"];
3996 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3997 if ((self = [super initWithBook:book]) != nil) {
3998 database_ = database;
4000 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4001 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4002 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4003 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4004 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4008 pkgDepCache::Policy *policy([database_ policy]);
4010 pkgCacheFile &cache([database_ cache]);
4011 NSArray *packages = [database_ packages];
4012 for (Package *package in packages) {
4013 pkgCache::PkgIterator iterator = [package iterator];
4014 pkgDepCache::StateCache &state(cache[iterator]);
4016 NSString *name([package name]);
4018 if (state.NewInstall())
4019 [installing addObject:name];
4020 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4021 [reinstalling addObject:name];
4022 else if (state.Upgrade())
4023 [upgrading addObject:name];
4024 else if (state.Downgrade())
4025 [downgrading addObject:name];
4026 else if (state.Delete()) {
4027 if ([package essential])
4029 [removing addObject:name];
4032 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4033 substrate_ |= DepSubstrate(iterator.CurrentVer());
4038 else if (Advanced_) {
4039 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4041 essential_ = [[UIActionSheet alloc]
4042 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4043 buttons:[NSArray arrayWithObjects:
4044 [NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")],
4045 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4047 defaultButtonIndex:0
4052 [essential_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
4054 [essential_ setDestructiveButtonIndex:1];
4055 [essential_ setBodyText:UCLocalize("REMOVING_ESSENTIALS_EX")];
4057 essential_ = [[UIActionSheet alloc]
4058 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4059 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4060 defaultButtonIndex:0
4065 [essential_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
4067 [essential_ setBodyText:UCLocalize("UNABLE_TO_COMPLY_EX")];
4070 changes_ = [[NSArray alloc] initWithObjects:
4078 issues_ = [database_ issues];
4080 issues_ = [issues_ retain];
4082 sizes_ = [[NSArray alloc] initWithObjects:
4083 SizeString([database_ fetcher].FetchNeeded()),
4084 SizeString([database_ fetcher].PartialPresent()),
4085 SizeString([database_ cache]->UsrSize()),
4088 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4090 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4094 - (NSString *) backButtonTitle {
4095 return UCLocalize("CONFIRM");
4098 - (NSString *) leftButtonTitle {
4099 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
4102 - (id) rightButtonTitle {
4103 return issues_ != nil ? nil : [super rightButtonTitle];
4106 - (id) _rightButtonTitle {
4107 #if AlwaysReload || IgnoreInstall
4108 return [super _rightButtonTitle];
4110 return UCLocalize("CONFIRM");
4114 - (void) _leftButtonClicked {
4119 - (void) _rightButtonClicked {
4121 return [super _rightButtonClicked];
4123 if (essential_ != nil)
4124 [essential_ popupAlertAnimated:YES];
4128 [delegate_ confirm];
4136 /* Progress Data {{{ */
4137 @interface ProgressData : NSObject {
4143 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4150 @implementation ProgressData
4152 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4153 if ((self = [super init]) != nil) {
4154 selector_ = selector;
4174 /* Progress View {{{ */
4175 @interface ProgressView : UIView <
4176 ConfigurationDelegate,
4179 _transient Database *database_;
4181 UIView *background_;
4182 UITransitionView *transition_;
4184 UINavigationBar *navbar_;
4185 UIProgressBar *progress_;
4186 UITextView *output_;
4187 UITextLabel *status_;
4188 UIPushButton *close_;
4191 SHA1SumValue springlist_;
4192 SHA1SumValue notifyconf_;
4196 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4197 - (void) setContentView:(UIView *)view;
4200 - (void) _retachThread;
4201 - (void) _detachNewThreadData:(ProgressData *)data;
4202 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4208 @protocol ProgressViewDelegate
4209 - (void) progressViewIsComplete:(ProgressView *)sender;
4212 @implementation ProgressView
4215 [transition_ setDelegate:nil];
4216 [navbar_ setDelegate:nil];
4219 if (background_ != nil)
4220 [background_ release];
4221 [transition_ release];
4224 [progress_ release];
4233 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4234 if ((self = [super initWithFrame:frame]) != nil) {
4235 database_ = database;
4236 delegate_ = delegate;
4238 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4239 [transition_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4240 [transition_ setDelegate:self];
4242 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4243 [overlay_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4245 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4246 [background_ setBackgroundColor:[UIColor blackColor]];
4247 [self addSubview:background_];
4249 [self addSubview:transition_];
4251 CGSize navsize = [UINavigationBar defaultSize];
4252 CGRect navrect = {{0, 0}, navsize};
4254 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4255 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
4256 [overlay_ addSubview:navbar_];
4258 [navbar_ setBarStyle:1];
4259 [navbar_ setDelegate:self];
4261 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4262 [navbar_ pushNavigationItem:navitem];
4264 CGRect bounds = [overlay_ bounds];
4265 CGSize prgsize = [UIProgressBar defaultSize];
4268 (bounds.size.width - prgsize.width) / 2,
4269 bounds.size.height - prgsize.height - 20
4272 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4273 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4274 [progress_ setStyle:0];
4276 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4278 bounds.size.height - prgsize.height - 50,
4279 bounds.size.width - 20,
4283 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4285 [status_ setColor:[UIColor whiteColor]];
4286 [status_ setBackgroundColor:[UIColor clearColor]];
4288 [status_ setCentersHorizontally:YES];
4289 //[status_ setFont:font];
4291 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4293 navrect.size.height + 20,
4294 bounds.size.width - 20,
4295 bounds.size.height - navsize.height - 62 - navrect.size.height
4298 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4299 [overlay_ addSubview:output_];
4301 //[output_ setTextFont:@"Courier New"];
4302 [output_ setFont:[[output_ font] fontWithSize:12]];
4304 [output_ setTextColor:[UIColor whiteColor]];
4305 [output_ setBackgroundColor:[UIColor clearColor]];
4307 [output_ setMarginTop:0];
4308 [output_ setAllowsRubberBanding:YES];
4309 [output_ setEditable:NO];
4311 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4313 bounds.size.height - prgsize.height - 50,
4314 bounds.size.width - 20,
4318 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4320 [close_ setAutosizesToFit:NO];
4321 [close_ setDrawsShadow:YES];
4322 [close_ setStretchBackground:YES];
4323 [close_ setEnabled:YES];
4325 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4326 [close_ setTitleFont:bold];
4328 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4329 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4330 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4334 - (void) setContentView:(UIView *)view {
4335 view_ = [view retain];
4338 - (void) resetView {
4339 [transition_ transition:6 toView:view_];
4342 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4343 NSString *context([sheet context]);
4345 if ([context isEqualToString:@"conffile"]) {
4346 FILE *input = [database_ input];
4350 fprintf(input, "N\n");
4354 fprintf(input, "Y\n");
4364 - (void) closeButtonPushed {
4373 [delegate_ terminateWithSuccess];
4374 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4375 [delegate_ suspendWithAnimation:YES];
4377 [delegate_ suspend];*/
4381 system("launchctl stop com.apple.SpringBoard");
4385 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4394 - (void) _retachThread {
4395 UINavigationItem *item([navbar_ topItem]);
4396 [item setTitle:UCLocalize("COMPLETE")];
4398 [overlay_ addSubview:close_];
4399 [progress_ removeFromSuperview];
4400 [status_ removeFromSuperview];
4402 [database_ popErrorWithTitle:title_];
4403 [delegate_ progressViewIsComplete:self];
4407 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4410 MMap mmap(file, MMap::ReadOnly);
4412 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4413 if (!(notifyconf_ == sha1.Result()))
4420 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4423 MMap mmap(file, MMap::ReadOnly);
4425 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4426 if (!(springlist_ == sha1.Result()))
4432 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4433 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4434 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4435 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4436 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4439 system("su -c /usr/bin/uicache mobile");
4441 [delegate_ setStatusBarShowsProgress:NO];
4444 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4445 [[data target] performSelector:[data selector] withObject:[data object]];
4448 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4451 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4457 title_ = [title retain];
4459 UINavigationItem *item([navbar_ topItem]);
4460 [item setTitle:title_];
4462 [status_ setText:nil];
4463 [output_ setText:@""];
4464 [progress_ setProgress:0];
4466 [close_ removeFromSuperview];
4467 [overlay_ addSubview:progress_];
4468 [overlay_ addSubview:status_];
4470 [delegate_ setStatusBarShowsProgress:YES];
4475 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4478 MMap mmap(file, MMap::ReadOnly);
4480 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4481 notifyconf_ = sha1.Result();
4487 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4490 MMap mmap(file, MMap::ReadOnly);
4492 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4493 springlist_ = sha1.Result();
4497 [transition_ transition:6 toView:overlay_];
4500 detachNewThreadSelector:@selector(_detachNewThreadData:)
4502 withObject:[[ProgressData alloc]
4503 initWithSelector:selector
4510 - (void) repairWithSelector:(SEL)selector {
4512 detachNewThreadSelector:selector
4515 title:UCLocalize("REPAIRING")
4519 - (void) setConfigurationData:(NSString *)data {
4521 performSelectorOnMainThread:@selector(_setConfigurationData:)
4527 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4528 CYActionSheet *sheet([[[CYActionSheet alloc]
4530 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4531 defaultButtonIndex:0
4534 [sheet setBodyText:error];
4535 [sheet yieldToPopupAlertAnimated:YES];
4539 - (void) setProgressTitle:(NSString *)title {
4541 performSelectorOnMainThread:@selector(_setProgressTitle:)
4547 - (void) setProgressPercent:(float)percent {
4549 performSelectorOnMainThread:@selector(_setProgressPercent:)
4550 withObject:[NSNumber numberWithFloat:percent]
4555 - (void) startProgress {
4558 - (void) addProgressOutput:(NSString *)output {
4560 performSelectorOnMainThread:@selector(_addProgressOutput:)
4566 - (bool) isCancelling:(size_t)received {
4570 - (void) _setConfigurationData:(NSString *)data {
4571 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4573 if (!conffile_r(data)) {
4574 lprintf("E:invalid conffile\n");
4578 NSString *ofile = conffile_r[1];
4579 //NSString *nfile = conffile_r[2];
4581 UIActionSheet *sheet = [[[UIActionSheet alloc]
4582 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4583 buttons:[NSArray arrayWithObjects:
4584 UCLocalize("KEEP_OLD_COPY"),
4585 UCLocalize("ACCEPT_NEW_COPY"),
4586 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4588 defaultButtonIndex:0
4593 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
4595 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4596 [sheet popupAlertAnimated:YES];
4599 - (void) _setProgressTitle:(NSString *)title {
4600 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4601 for (size_t i(0), e([words count]); i != e; ++i) {
4602 NSString *word([words objectAtIndex:i]);
4603 if (Package *package = [database_ packageWithName:word])
4604 [words replaceObjectAtIndex:i withObject:[package name]];
4607 [status_ setText:[words componentsJoinedByString:@" "]];
4610 - (void) _setProgressPercent:(NSNumber *)percent {
4611 [progress_ setProgress:[percent floatValue]];
4614 - (void) _addProgressOutput:(NSString *)output {
4615 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4616 CGSize size = [output_ contentSize];
4617 CGRect rect = {{0, size.height}, {size.width, 0}};
4618 [output_ scrollRectToVisible:rect animated:YES];
4621 - (BOOL) isRunning {
4628 /* Package Cell {{{ */
4629 @interface ContentView : UIView {
4630 _transient id delegate_;
4635 @interface PackageCell : UITableViewCell {
4638 NSString *description_;
4644 ContentView *content_;
4650 - (PackageCell *) init;
4651 - (void) setPackage:(Package *)package;
4653 + (int) heightForPackage:(Package *)package;
4654 - (void) drawContentRect:(CGRect)rect;
4658 @implementation ContentView
4660 - (id) initWithFrame:(CGRect)frame {
4661 if ((self = [super initWithFrame:frame]) != nil) {
4665 - (void) setDelegate:(id)delegate {
4666 delegate_ = delegate;
4669 - (void) drawRect:(CGRect)rect {
4670 [super drawRect:rect];
4671 [delegate_ drawContentRect:rect];
4676 @implementation PackageCell
4678 - (void) clearPackage {
4689 if (description_ != nil) {
4690 [description_ release];
4694 if (source_ != nil) {
4699 if (badge_ != nil) {
4704 if (placard_ != nil) {
4714 [self clearPackage];
4721 return faded_ ? [self selectionPercent] : fade_;
4724 - (PackageCell *) init {
4725 CGRect frame(CGRectMake(0, 0, 320, 74));
4726 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4727 UIView *content([self contentView]);
4728 CGRect bounds([content bounds]);
4730 content_ = [[ContentView alloc] initWithFrame:bounds];
4731 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4732 [content addSubview:content_];
4734 [content_ setDelegate:self];
4735 [content_ setOpaque:YES];
4736 if ([self respondsToSelector:@selector(selectionPercent)])
4739 [self setNeedsDisplayOnBoundsChange:YES];
4743 - (void) _setBackgroundColor {
4745 if (NSString *mode = [package_ mode]) {
4746 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4747 color = remove ? RemovingColor_ : InstallingColor_;
4749 color = [UIColor whiteColor];
4751 [content_ setBackgroundColor:color];
4752 [self setNeedsDisplay];
4755 - (void) setPackage:(Package *)package {
4756 [self clearPackage];
4759 Source *source = [package source];
4761 icon_ = [[package icon] retain];
4762 name_ = [[package name] retain];
4765 description_ = [package longDescription];
4766 if (description_ == nil)
4767 description_ = [package shortDescription];
4768 if (description_ != nil)
4769 description_ = [description_ retain];
4771 commercial_ = [package isCommercial];
4773 package_ = [package retain];
4775 NSString *label = nil;
4776 bool trusted = false;
4778 if (source != nil) {
4779 label = [source label];
4780 trusted = [source trusted];
4781 } else if ([[package id] isEqualToString:@"firmware"])
4782 label = UCLocalize("APPLE");
4784 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4786 NSString *from(label);
4788 NSString *section = [package simpleSection];
4789 if (section != nil && ![section isEqualToString:label]) {
4790 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4791 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4794 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4795 source_ = [from retain];
4797 if (NSString *purpose = [package primaryPurpose])
4798 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4799 badge_ = [badge_ retain];
4801 if ([package installed] != nil)
4802 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4803 placard_ = [placard_ retain];
4805 [self _setBackgroundColor];
4806 [content_ setNeedsDisplay];
4809 - (void) drawContentRect:(CGRect)rect {
4810 bool selected([self isSelected]);
4811 float width([self bounds].size.width);
4814 CGContextRef context(UIGraphicsGetCurrentContext());
4815 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4816 CGContextFillRect(context, rect);
4821 rect.size = [icon_ size];
4823 rect.size.width /= 2;
4824 rect.size.height /= 2;
4826 rect.origin.x = 25 - rect.size.width / 2;
4827 rect.origin.y = 25 - rect.size.height / 2;
4829 [icon_ drawInRect:rect];
4832 if (badge_ != nil) {
4833 CGSize size = [badge_ size];
4835 [badge_ drawAtPoint:CGPointMake(
4836 36 - size.width / 2,
4837 36 - size.height / 2
4845 UISetColor(commercial_ ? Purple_ : Black_);
4846 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ ellipsis:2];
4847 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
4850 UISetColor(commercial_ ? Purplish_ : Gray_);
4851 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ ellipsis:2];
4853 if (placard_ != nil)
4854 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4857 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4858 //[self _setBackgroundColor];
4859 [super setSelected:selected animated:fade];
4860 [content_ setNeedsDisplay];
4863 + (int) heightForPackage:(Package *)package {
4869 /* Section Cell {{{ */
4870 @interface SectionCell : UISimpleTableCell {
4876 _UISwitchSlider *switch_;
4881 - (void) setSection:(Section *)section editing:(BOOL)editing;
4885 @implementation SectionCell
4887 - (void) clearSection {
4888 if (basic_ != nil) {
4893 if (section_ != nil) {
4903 if (count_ != nil) {
4910 [self clearSection];
4917 if ((self = [super init]) != nil) {
4918 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4919 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4920 [switch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
4921 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventTouchUpInside];
4925 - (void) onSwitch:(id)sender {
4926 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4927 if (metadata == nil) {
4928 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4929 [Sections_ setObject:metadata forKey:basic_];
4933 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4936 - (void) setSection:(Section *)section editing:(BOOL)editing {
4937 if (editing != editing_) {
4939 [switch_ removeFromSuperview];
4941 [self addSubview:switch_];
4945 [self clearSection];
4947 if (section == nil) {
4948 name_ = [UCLocalize("ALL_PACKAGES") retain];
4951 basic_ = [section name];
4953 basic_ = [basic_ retain];
4955 section_ = [section localized];
4956 if (section_ != nil)
4957 section_ = [section_ retain];
4959 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4960 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4963 [switch_ setValue:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4967 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4968 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4976 float width(rect.size.width + 23);
4980 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ ellipsis:2];
4982 CGSize size = [count_ sizeWithFont:Font14_];
4986 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4988 [super drawContentInRect:rect selected:selected];
4994 /* File Table {{{ */
4995 @interface FileTable : RVPage {
4996 _transient Database *database_;
4999 NSMutableArray *files_;
5003 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5004 - (void) setPackage:(Package *)package;
5008 @implementation FileTable
5011 if (package_ != nil)
5020 - (int) numberOfRowsInTable:(UITable *)table {
5021 return files_ == nil ? 0 : [files_ count];
5024 - (float) table:(UITable *)table heightForRow:(int)row {
5028 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
5029 if (reusing == nil) {
5030 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
5031 UIFont *font = [UIFont systemFontOfSize:16];
5032 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
5034 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
5038 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5042 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5043 if ((self = [super initWithBook:book]) != nil) {
5044 database_ = database;
5046 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5048 list_ = [[UITable alloc] initWithFrame:[self bounds]];
5049 [self addSubview:list_];
5051 UITableColumn *column = [[[UITableColumn alloc]
5052 initWithTitle:UCLocalize("NAME")
5054 width:[self frame].size.width
5057 [list_ setDataSource:self];
5058 [list_ setSeparatorStyle:1];
5059 [list_ addTableColumn:column];
5060 [list_ setDelegate:self];
5061 [list_ setReusesTableCells:YES];
5065 - (void) setPackage:(Package *)package {
5066 if (package_ != nil) {
5067 [package_ autorelease];
5076 [files_ removeAllObjects];
5078 if (package != nil) {
5079 package_ = [package retain];
5080 name_ = [[package id] retain];
5082 if (NSArray *files = [package files])
5083 [files_ addObjectsFromArray:files];
5085 if ([files_ count] != 0) {
5086 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5087 [files_ removeObjectAtIndex:0];
5088 [files_ sortUsingSelector:@selector(compareByPath:)];
5090 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5091 [stack addObject:@"/"];
5093 for (int i(0), e([files_ count]); i != e; ++i) {
5094 NSString *file = [files_ objectAtIndex:i];
5095 while (![file hasPrefix:[stack lastObject]])
5096 [stack removeLastObject];
5097 NSString *directory = [stack lastObject];
5098 [stack addObject:[file stringByAppendingString:@"/"]];
5099 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5100 ([stack count] - 2) * 3, "",
5101 [file substringFromIndex:[directory length]]
5110 - (void) resetViewAnimated:(BOOL)animated {
5111 [list_ resetViewAnimated:animated];
5114 - (void) reloadData {
5115 [self setPackage:[database_ packageWithName:name_]];
5116 [self reloadButtons];
5119 - (NSString *) title {
5120 return UCLocalize("INSTALLED_FILES");
5123 - (NSString *) backButtonTitle {
5124 return UCLocalize("FILES");
5129 /* Package View {{{ */
5130 @interface PackageView : CydiaBrowserView {
5131 _transient Database *database_;
5135 NSMutableArray *buttons_;
5138 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5139 - (void) setPackage:(Package *)package;
5143 @implementation PackageView
5146 if (package_ != nil)
5155 if ([self retainCount] == 1)
5156 [delegate_ setPackageView:self];
5160 /* XXX: this is not safe at all... localization of /fail/ */
5161 - (void) _clickButtonWithName:(NSString *)name {
5162 if ([name isEqualToString:UCLocalize("CLEAR")])
5163 [delegate_ clearPackage:package_];
5164 else if ([name isEqualToString:UCLocalize("INSTALL")])
5165 [delegate_ installPackage:package_];
5166 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5167 [delegate_ installPackage:package_];
5168 else if ([name isEqualToString:UCLocalize("REMOVE")])
5169 [delegate_ removePackage:package_];
5170 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5171 [delegate_ installPackage:package_];
5172 else _assert(false);
5175 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5176 NSString *context([sheet context]);
5178 if ([context isEqualToString:@"modify"]) {
5179 int count = [buttons_ count];
5180 _assert(count != 0);
5181 _assert(button <= count + 1);
5183 if (count != button - 1)
5184 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
5188 [super alertSheet:sheet buttonClicked:button];
5191 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5192 return [super webView:sender didFinishLoadForFrame:frame];
5195 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5196 [super webView:sender didClearWindowObject:window forFrame:frame];
5197 [window setValue:package_ forKey:@"package"];
5200 - (bool) _allowJavaScriptPanel {
5205 - (void) __rightButtonClicked {
5206 int count([buttons_ count]);
5211 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5213 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
5214 [buttons addObjectsFromArray:buttons_];
5215 [buttons addObject:UCLocalize("CANCEL")];
5217 [delegate_ slideUp:[[[UIActionSheet alloc]
5220 defaultButtonIndex:([buttons count] - 1)
5227 - (void) _rightButtonClicked {
5229 [super _rightButtonClicked];
5231 [self __rightButtonClicked];
5235 - (id) _rightButtonTitle {
5236 int count = [buttons_ count];
5237 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5240 - (NSString *) backButtonTitle {
5244 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5245 if ((self = [super initWithBook:book]) != nil) {
5246 database_ = database;
5247 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5248 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5252 - (void) setPackage:(Package *)package {
5253 if (package_ != nil) {
5254 [package_ autorelease];
5263 [buttons_ removeAllObjects];
5265 if (package != nil) {
5268 package_ = [package retain];
5269 name_ = [[package id] retain];
5270 commercial_ = [package isCommercial];
5272 if ([package_ mode] != nil)
5273 [buttons_ addObject:UCLocalize("CLEAR")];
5274 if ([package_ source] == nil);
5275 else if ([package_ upgradableAndEssential:NO])
5276 [buttons_ addObject:UCLocalize("UPGRADE")];
5277 else if ([package_ uninstalled])
5278 [buttons_ addObject:UCLocalize("INSTALL")];
5280 [buttons_ addObject:UCLocalize("REINSTALL")];
5281 if (![package_ uninstalled])
5282 [buttons_ addObject:UCLocalize("REMOVE")];
5284 if (special_ != NULL) {
5285 CGRect frame([webview_ frame]);
5286 frame.size.width = 320;
5287 frame.size.height = 0;
5288 [webview_ setFrame:frame];
5290 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5291 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5293 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
5296 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5298 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5300 [self setFinishHook:nil];
5301 [self setPopupHook:nil];
5304 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5305 [super callFunction:special_];
5309 [self reloadButtons];
5312 - (bool) isLoading {
5313 return commercial_ ? [super isLoading] : false;
5316 - (void) reloadData {
5317 [self setPackage:[database_ packageWithName:name_]];
5322 /* Package Table {{{ */
5323 @interface PackageTable : RVPage {
5324 _transient Database *database_;
5326 NSMutableArray *packages_;
5327 NSMutableArray *sections_;
5329 NSMutableArray *index_;
5330 NSMutableDictionary *indices_;
5333 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5335 - (void) setDelegate:(id)delegate;
5337 - (void) reloadData;
5338 - (void) resetCursor;
5340 - (UITableView *) list;
5342 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5346 @implementation PackageTable
5349 [list_ setDataSource:nil];
5352 [packages_ release];
5353 [sections_ release];
5360 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5361 NSInteger count([sections_ count]);
5362 return count == 0 ? 1 : count;
5365 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5366 if ([sections_ count] == 0)
5368 return [[sections_ objectAtIndex:section] name];
5371 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5372 if ([sections_ count] == 0)
5374 return [[sections_ objectAtIndex:section] count];
5377 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5378 Section *section([sections_ objectAtIndex:[path section]]);
5379 NSInteger row([path row]);
5380 Package *package([packages_ objectAtIndex:([section row] + row)]);
5384 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5385 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5387 cell = [[[PackageCell alloc] init] autorelease];
5388 [cell setPackage:[self packageAtIndexPath:path]];
5392 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5394 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5397 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5398 Package *package([self packageAtIndexPath:path]);
5399 package = [database_ packageWithName:[package id]];
5400 PackageView *view([delegate_ packageView]);
5401 [view setPackage:package];
5402 [view setDelegate:delegate_];
5403 [book_ pushPage:view];
5407 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5408 return [packages_ count] > 20 ? index_ : nil;
5411 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5415 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5416 if ((self = [super initWithBook:book]) != nil) {
5417 database_ = database;
5418 title_ = [title retain];
5420 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5421 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5423 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5424 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5426 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5427 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5428 [self addSubview:list_];
5430 [list_ setDataSource:self];
5431 [list_ setDelegate:self];
5433 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5437 - (void) setDelegate:(id)delegate {
5438 delegate_ = delegate;
5441 - (bool) hasPackage:(Package *)package {
5445 - (void) reloadData {
5446 NSArray *packages = [database_ packages];
5448 [packages_ removeAllObjects];
5449 [sections_ removeAllObjects];
5451 _profile(PackageTable$reloadData$Filter)
5452 for (Package *package in packages)
5453 if ([self hasPackage:package])
5454 [packages_ addObject:package];
5457 [index_ removeAllObjects];
5458 [indices_ removeAllObjects];
5460 Section *section = nil;
5462 _profile(PackageTable$reloadData$Section)
5463 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5467 _profile(PackageTable$reloadData$Section$Package)
5468 package = [packages_ objectAtIndex:offset];
5469 index = [package index];
5472 if (section == nil || [section index] != index) {
5473 _profile(PackageTable$reloadData$Section$Allocate)
5474 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5477 [index_ addObject:[section name]];
5478 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5480 _profile(PackageTable$reloadData$Section$Add)
5481 [sections_ addObject:section];
5485 [section addToCount];
5489 _profile(PackageTable$reloadData$List)
5494 - (NSString *) title {
5498 - (void) resetViewAnimated:(BOOL)animated {
5499 [list_ resetViewAnimated:animated];
5502 - (void) resetCursor {
5503 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5506 - (UITableView *) list {
5510 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5511 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5516 /* Filtered Package Table {{{ */
5517 @interface FilteredPackageTable : PackageTable {
5523 - (void) setObject:(id)object;
5524 - (void) setObject:(id)object forFilter:(SEL)filter;
5526 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5530 @implementation FilteredPackageTable
5538 - (void) setFilter:(SEL)filter {
5541 /* XXX: this is an unsafe optimization of doomy hell */
5542 Method method(class_getInstanceMethod([Package class], filter));
5543 _assert(method != NULL);
5544 imp_ = method_getImplementation(method);
5545 _assert(imp_ != NULL);
5548 - (void) setObject:(id)object {
5554 object_ = [object retain];
5557 - (void) setObject:(id)object forFilter:(SEL)filter {
5558 [self setFilter:filter];
5559 [self setObject:object];
5563 - (bool) hasPackage:(Package *)package {
5564 _profile(FilteredPackageTable$hasPackage)
5565 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5569 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5570 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5571 [self setFilter:filter];
5572 object_ = object == nil ? nil : [object retain];
5580 /* Add Source View {{{ */
5581 @interface AddSourceView : RVPage {
5582 _transient Database *database_;
5585 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5589 @implementation AddSourceView
5591 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5592 if ((self = [super initWithBook:book]) != nil) {
5593 database_ = database;
5599 /* Source Cell {{{ */
5600 @interface SourceCell : UITableCell {
5603 NSString *description_;
5609 - (SourceCell *) initWithSource:(Source *)source;
5613 @implementation SourceCell
5618 [description_ release];
5623 - (SourceCell *) initWithSource:(Source *)source {
5624 if ((self = [super init]) != nil) {
5626 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5628 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5629 icon_ = [icon_ retain];
5631 origin_ = [[source name] retain];
5632 label_ = [[source uri] retain];
5633 description_ = [[source description] retain];
5637 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5638 float width(rect.size.width);
5641 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5648 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ ellipsis:2];
5652 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
5656 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ ellipsis:2];
5658 [super drawContentInRect:rect selected:selected];
5663 /* Source Table {{{ */
5664 @interface SourceTable : RVPage {
5665 _transient Database *database_;
5666 UISectionList *list_;
5667 NSMutableArray *sources_;
5668 UIActionSheet *alert_;
5672 UIProgressHUD *hud_;
5675 //NSURLConnection *installer_;
5676 NSURLConnection *trivial_;
5677 NSURLConnection *trivial_bz2_;
5678 NSURLConnection *trivial_gz_;
5679 //NSURLConnection *automatic_;
5684 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5688 @implementation SourceTable
5690 - (void) _deallocConnection:(NSURLConnection *)connection {
5691 if (connection != nil) {
5692 [connection cancel];
5693 //[connection setDelegate:nil];
5694 [connection release];
5699 [[list_ table] setDelegate:nil];
5700 [list_ setDataSource:nil];
5709 //[self _deallocConnection:installer_];
5710 [self _deallocConnection:trivial_];
5711 [self _deallocConnection:trivial_gz_];
5712 [self _deallocConnection:trivial_bz2_];
5713 //[self _deallocConnection:automatic_];
5720 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5721 return offset_ == 0 ? 1 : 2;
5724 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5725 switch (section + (offset_ == 0 ? 1 : 0)) {
5726 case 0: return UCLocalize("ENTERED_BY_USER");
5727 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5733 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5734 switch (section + (offset_ == 0 ? 1 : 0)) {
5736 case 1: return offset_;
5742 - (int) numberOfRowsInTable:(UITable *)table {
5743 return [sources_ count];
5746 - (float) table:(UITable *)table heightForRow:(int)row {
5747 Source *source = [sources_ objectAtIndex:row];
5748 return [source description] == nil ? 56 : 73;
5751 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5752 Source *source = [sources_ objectAtIndex:row];
5753 // XXX: weird warning, stupid selectors ;P
5754 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5757 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5761 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5765 - (void) tableRowSelected:(NSNotification*)notification {
5766 UITable *table([list_ table]);
5767 int row([table selectedRow]);
5771 Source *source = [sources_ objectAtIndex:row];
5773 PackageTable *packages = [[[FilteredPackageTable alloc]
5776 title:[source label]
5777 filter:@selector(isVisibleInSource:)
5781 [packages setDelegate:delegate_];
5783 [book_ pushPage:packages];
5786 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5787 Source *source = [sources_ objectAtIndex:row];
5788 return [source record] != nil;
5791 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5792 [[list_ table] setDeleteConfirmationRow:row];
5795 - (void) table:(UITable *)table deleteRow:(int)row {
5796 Source *source = [sources_ objectAtIndex:row];
5797 [Sources_ removeObjectForKey:[source key]];
5798 [delegate_ syncData];
5802 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5805 @"./", @"Distribution",
5806 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5808 [delegate_ syncData];
5811 - (NSString *) getWarning {
5812 NSString *href(href_);
5813 NSRange colon([href rangeOfString:@"://"]);
5814 if (colon.location != NSNotFound)
5815 href = [href substringFromIndex:(colon.location + 3)];
5816 href = [href stringByAddingPercentEscapes];
5817 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5818 href = [href stringByCachingURLWithCurrentCDN];
5820 NSURL *url([NSURL URLWithString:href]);
5822 NSStringEncoding encoding;
5823 NSError *error(nil);
5825 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5826 return [warning length] == 0 ? nil : warning;
5830 - (void) _endConnection:(NSURLConnection *)connection {
5831 NSURLConnection **field = NULL;
5832 if (connection == trivial_)
5834 else if (connection == trivial_bz2_)
5835 field = &trivial_bz2_;
5836 else if (connection == trivial_gz_)
5837 field = &trivial_gz_;
5838 _assert(field != NULL);
5839 [connection release];
5844 trivial_bz2_ == nil &&
5850 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5853 UIActionSheet *sheet = [[[UIActionSheet alloc]
5854 initWithTitle:UCLocalize("SOURCE_WARNING")
5855 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5856 defaultButtonIndex:0
5861 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
5863 [sheet setNumberOfRows:1];
5864 [sheet setBodyText:warning];
5865 [sheet popupAlertAnimated:YES];
5868 } else if (error_ != nil) {
5869 UIActionSheet *sheet = [[[UIActionSheet alloc]
5870 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5871 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5872 defaultButtonIndex:0
5877 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
5879 [sheet setBodyText:[error_ localizedDescription]];
5880 [sheet popupAlertAnimated:YES];
5882 UIActionSheet *sheet = [[[UIActionSheet alloc]
5883 initWithTitle:UCLocalize("NOT_REPOSITORY")
5884 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5885 defaultButtonIndex:0
5890 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
5892 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5893 [sheet popupAlertAnimated:YES];
5896 [delegate_ setStatusBarShowsProgress:NO];
5897 [delegate_ removeProgressHUD:hud_];
5907 if (error_ != nil) {
5914 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5915 switch ([response statusCode]) {
5921 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5922 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5924 error_ = [error retain];
5925 [self _endConnection:connection];
5928 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5929 [self _endConnection:connection];
5932 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5933 NSMutableURLRequest *request = [NSMutableURLRequest
5934 requestWithURL:[NSURL URLWithString:href]
5935 cachePolicy:NSURLRequestUseProtocolCachePolicy
5936 timeoutInterval:20.0
5939 [request setHTTPMethod:method];
5941 if (Machine_ != NULL)
5942 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5944 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
5946 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5948 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5951 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5952 NSString *context([sheet context]);
5954 if ([context isEqualToString:@"source"]) {
5957 NSString *href = [[sheet textField] text];
5959 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5961 if (![href hasSuffix:@"/"])
5962 href_ = [href stringByAppendingString:@"/"];
5965 href_ = [href_ retain];
5967 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
5968 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5969 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5970 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5974 hud_ = [[delegate_ addProgressHUD] retain];
5975 [hud_ setText:UCLocalize("VERIFYING_URL")];
5985 } else if ([context isEqualToString:@"trivial"])
5987 else if ([context isEqualToString:@"urlerror"])
5989 else if ([context isEqualToString:@"warning"]) {
6008 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6009 if ((self = [super initWithBook:book]) != nil) {
6010 database_ = database;
6011 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6013 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
6014 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6015 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6016 [self addSubview:list_];
6018 [list_ setShouldHideHeaderInShortLists:NO];
6019 [list_ setDataSource:self];
6021 UITableColumn *column = [[UITableColumn alloc]
6022 initWithTitle:UCLocalize("NAME")
6024 width:[self frame].size.width
6027 UITable *table = [list_ table];
6028 [table setSeparatorStyle:1];
6029 [table addTableColumn:column];
6030 [table setDelegate:self];
6034 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6038 - (void) reloadData {
6040 if (!list.ReadMainList())
6043 [sources_ removeAllObjects];
6044 [sources_ addObjectsFromArray:[database_ sources]];
6046 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6049 int count([sources_ count]);
6050 for (offset_ = 0; offset_ != count; ++offset_) {
6051 Source *source = [sources_ objectAtIndex:offset_];
6052 if ([source record] == nil)
6059 - (void) resetViewAnimated:(BOOL)animated {
6060 [list_ resetViewAnimated:animated];
6063 - (void) _leftButtonClicked {
6064 /*[book_ pushPage:[[[AddSourceView alloc]
6069 UIActionSheet *sheet = [[[UIActionSheet alloc]
6070 initWithTitle:UCLocalize("ENTER_APT_URL")
6071 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
6072 defaultButtonIndex:0
6077 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6079 [sheet setNumberOfRows:1];
6080 [sheet addTextFieldWithValue:@"http://" label:@""];
6082 UITextInputTraits *traits = [[sheet textField] textInputTraits];
6083 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6084 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6085 [traits setKeyboardType:UIKeyboardTypeURL];
6086 // XXX: UIReturnKeyDone
6087 [traits setReturnKeyType:UIReturnKeyNext];
6089 [sheet popupAlertAnimated:YES];
6092 - (void) _rightButtonClicked {
6093 UITable *table = [list_ table];
6094 BOOL editing = [table isRowDeletionEnabled];
6095 [table enableRowDeletion:!editing animated:YES];
6096 [book_ reloadButtonsForPage:self];
6099 - (NSString *) title {
6100 return UCLocalize("SOURCES");
6103 - (NSString *) leftButtonTitle {
6104 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
6107 - (id) rightButtonTitle {
6108 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
6111 - (UINavigationButtonStyle) rightButtonStyle {
6112 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6118 /* Installed View {{{ */
6119 @interface InstalledView : RVPage {
6120 _transient Database *database_;
6121 FilteredPackageTable *packages_;
6125 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6129 @implementation InstalledView
6132 [packages_ release];
6136 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6137 if ((self = [super initWithBook:book]) != nil) {
6138 database_ = database;
6140 packages_ = [[FilteredPackageTable alloc]
6144 filter:@selector(isInstalledAndVisible:)
6145 with:[NSNumber numberWithBool:YES]
6148 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6149 [self addSubview:packages_];
6151 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6155 - (void) resetViewAnimated:(BOOL)animated {
6156 [packages_ resetViewAnimated:animated];
6159 - (void) reloadData {
6160 [packages_ reloadData];
6163 - (void) _rightButtonClicked {
6164 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6165 [packages_ reloadData];
6167 [book_ reloadButtonsForPage:self];
6170 - (NSString *) title {
6171 return UCLocalize("INSTALLED");
6174 - (NSString *) backButtonTitle {
6175 return UCLocalize("PACKAGES");
6178 - (id) rightButtonTitle {
6179 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6182 - (UINavigationButtonStyle) rightButtonStyle {
6183 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6186 - (void) setDelegate:(id)delegate {
6187 [super setDelegate:delegate];
6188 [packages_ setDelegate:delegate];
6195 @interface HomeView : CydiaBrowserView {
6200 @implementation HomeView
6202 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6203 NSString *context([sheet context]);
6205 if ([context isEqualToString:@"about"])
6208 [super alertSheet:sheet buttonClicked:button];
6211 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6212 [super _setMoreHeaders:request];
6214 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6215 if (UniqueID_ != nil)
6216 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6219 - (void) _leftButtonClicked {
6220 UIActionSheet *sheet = [[[UIActionSheet alloc]
6221 initWithTitle:UCLocalize("ABOUT_CYDIA")
6222 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6223 defaultButtonIndex:0
6228 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6231 @"Copyright (C) 2008-2009\n"
6232 "Jay Freeman (saurik)\n"
6233 "saurik@saurik.com\n"
6234 "http://www.saurik.com/\n"
6237 "http://www.theokorigroup.com/\n"
6239 "College of Creative Studies,\n"
6240 "University of California,\n"
6242 "http://www.ccs.ucsb.edu/"
6245 [sheet popupAlertAnimated:YES];
6248 - (NSString *) leftButtonTitle {
6249 return UCLocalize("ABOUT");
6254 /* Manage View {{{ */
6255 @interface ManageView : CydiaBrowserView {
6260 @implementation ManageView
6262 - (NSString *) title {
6263 return UCLocalize("MANAGE");
6266 - (void) _leftButtonClicked {
6267 [delegate_ askForSettings];
6268 [delegate_ updateData];
6271 - (NSString *) leftButtonTitle {
6272 return UCLocalize("SETTINGS");
6276 - (id) _rightButtonTitle {
6277 return Queuing_ ? UCLocalize("QUEUE") : nil;
6280 - (UINavigationButtonStyle) rightButtonStyle {
6281 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6284 - (void) _rightButtonClicked {
6289 - (bool) isLoading {
6296 /* Cydia Book {{{ */
6297 @interface CYBook : RVBook <
6300 _transient Database *database_;
6301 UINavigationBar *overlay_;
6302 UINavigationBar *underlay_;
6303 UIProgressIndicator *indicator_;
6304 UITextLabel *prompt_;
6305 UIProgressBar *progress_;
6306 UINavigationButton *cancel_;
6311 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6314 - (void) setUpdate:(NSDate *)date;
6318 @implementation CYBook
6322 [indicator_ release];
6324 [progress_ release];
6329 - (NSString *) getTitleForPage:(RVPage *)page {
6330 return [super getTitleForPage:page];
6342 [UIView beginAnimations:nil context:NULL];
6344 CGRect ovrframe = [overlay_ frame];
6345 ovrframe.origin.y = 0;
6346 [overlay_ setFrame:ovrframe];
6348 CGRect barframe = [navbar_ frame];
6349 barframe.origin.y += ovrframe.size.height;
6350 [navbar_ setFrame:barframe];
6352 CGRect trnframe = [transition_ frame];
6353 trnframe.origin.y += ovrframe.size.height;
6354 trnframe.size.height -= ovrframe.size.height;
6355 [transition_ setFrame:trnframe];
6357 [UIView endAnimations];
6365 [UIView beginAnimations:nil context:NULL];
6367 CGRect ovrframe = [overlay_ frame];
6368 ovrframe.origin.y = -ovrframe.size.height;
6369 [overlay_ setFrame:ovrframe];
6371 CGRect barframe = [navbar_ frame];
6372 barframe.origin.y -= ovrframe.size.height;
6373 [navbar_ setFrame:barframe];
6375 CGRect trnframe = [transition_ frame];
6376 trnframe.origin.y -= ovrframe.size.height;
6377 trnframe.size.height += ovrframe.size.height;
6378 [transition_ setFrame:trnframe];
6380 [UIView commitAnimations];
6383 - (void) setUpdate:(NSDate *)date {
6390 [indicator_ startAnimation];
6391 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6392 [progress_ setProgress:0];
6395 [overlay_ addSubview:cancel_];
6398 detachNewThreadSelector:@selector(_update)
6404 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6405 NSString *context([sheet context]);
6407 if ([context isEqualToString:@"refresh"])
6414 [indicator_ stopAnimation];
6418 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6421 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6422 if ((self = [super initWithFrame:frame]) != nil) {
6423 database_ = database;
6425 CGRect ovrrect([navbar_ bounds]);
6426 ovrrect.size.height = [UINavigationBar defaultSize].height;
6427 ovrrect.origin.y = -ovrrect.size.height;
6429 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6430 [overlay_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6431 [self addSubview:overlay_];
6433 ovrrect.origin.y = frame.size.height;
6434 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6435 [underlay_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6436 [self addSubview:underlay_];
6438 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6440 [overlay_ setBarStyle:1];
6441 [underlay_ setBarStyle:1];
6443 int barstyle([overlay_ _barStyle:NO]);
6444 bool ugly(barstyle == 0);
6446 UIProgressIndicatorStyle style = ugly ?
6447 UIProgressIndicatorStyleMediumBrown :
6448 UIProgressIndicatorStyleMediumWhite;
6450 CGSize indsize([UIProgressIndicator defaultSizeForStyle:style]);
6451 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6452 CGRect indrect = {{indoffset, indoffset}, indsize};
6454 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6455 [indicator_ setStyle:style];
6456 [overlay_ addSubview:indicator_];
6458 CGSize prmsize = {215, indsize.height + 4};
6461 indoffset * 2 + indsize.width,
6462 unsigned(ovrrect.size.height - prmsize.height) / 2 - 1
6465 UIFont *font([UIFont systemFontOfSize:15]);
6467 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6469 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6470 [prompt_ setBackgroundColor:[UIColor clearColor]];
6471 [prompt_ setFont:font];
6473 [overlay_ addSubview:prompt_];
6475 CGSize prgsize = {75, 100};
6478 ovrrect.size.width - prgsize.width - 10,
6479 (ovrrect.size.height - prgsize.height) / 2
6482 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6483 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6484 [overlay_ addSubview:progress_];
6486 [progress_ setStyle:0];
6488 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6489 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6490 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6492 CGRect frame = [cancel_ frame];
6493 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6494 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6495 [cancel_ setFrame:frame];
6497 [cancel_ setBarStyle:barstyle];
6501 - (void) _onCancel {
6503 [cancel_ removeFromSuperview];
6506 - (void) _update { _pooled
6508 status.setDelegate(self);
6509 [database_ updateWithStatus:status];
6512 performSelectorOnMainThread:@selector(_update_)
6518 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6519 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6523 UIActionSheet *sheet = [[[UIActionSheet alloc]
6524 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6525 buttons:[NSArray arrayWithObjects:
6528 defaultButtonIndex:0
6533 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6535 [sheet setBodyText:error];
6536 [sheet popupAlertAnimated:YES];
6538 [self reloadButtons];
6541 - (void) setProgressTitle:(NSString *)title {
6543 performSelectorOnMainThread:@selector(_setProgressTitle:)
6549 - (void) setProgressPercent:(float)percent {
6551 performSelectorOnMainThread:@selector(_setProgressPercent:)
6552 withObject:[NSNumber numberWithFloat:percent]
6557 - (void) startProgress {
6560 - (void) addProgressOutput:(NSString *)output {
6562 performSelectorOnMainThread:@selector(_addProgressOutput:)
6568 - (bool) isCancelling:(size_t)received {
6572 - (void) _setProgressTitle:(NSString *)title {
6573 [prompt_ setText:title];
6576 - (void) _setProgressPercent:(NSNumber *)percent {
6577 [progress_ setProgress:[percent floatValue]];
6580 - (void) _addProgressOutput:(NSString *)output {
6585 /* Cydia:// Protocol {{{ */
6586 @interface CydiaURLProtocol : NSURLProtocol {
6591 @implementation CydiaURLProtocol
6593 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6594 NSURL *url([request URL]);
6597 NSString *scheme([[url scheme] lowercaseString]);
6598 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6603 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6607 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6608 id<NSURLProtocolClient> client([self client]);
6610 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6612 NSData *data(UIImagePNGRepresentation(icon));
6614 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6615 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6616 [client URLProtocol:self didLoadData:data];
6617 [client URLProtocolDidFinishLoading:self];
6621 - (void) startLoading {
6622 id<NSURLProtocolClient> client([self client]);
6623 NSURLRequest *request([self request]);
6625 NSURL *url([request URL]);
6626 NSString *href([url absoluteString]);
6628 NSString *path([href substringFromIndex:8]);
6629 NSRange slash([path rangeOfString:@"/"]);
6632 if (slash.location == NSNotFound) {
6636 command = [path substringToIndex:slash.location];
6637 path = [path substringFromIndex:(slash.location + 1)];
6640 Database *database([Database sharedInstance]);
6642 if ([command isEqualToString:@"package-icon"]) {
6645 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6646 Package *package([database packageWithName:path]);
6649 UIImage *icon([package icon]);
6650 [self _returnPNGWithImage:icon forRequest:request];
6651 } else if ([command isEqualToString:@"source-icon"]) {
6654 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6655 NSString *source(Simplify(path));
6656 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6658 icon = [UIImage applicationImageNamed:@"unknown.png"];
6659 [self _returnPNGWithImage:icon forRequest:request];
6660 } else if ([command isEqualToString:@"uikit-image"]) {
6663 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6664 UIImage *icon(_UIImageWithName(path));
6665 [self _returnPNGWithImage:icon forRequest:request];
6666 } else if ([command isEqualToString:@"section-icon"]) {
6669 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6670 NSString *section(Simplify(path));
6671 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6673 icon = [UIImage applicationImageNamed:@"unknown.png"];
6674 [self _returnPNGWithImage:icon forRequest:request];
6676 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6680 - (void) stopLoading {
6686 /* Sections View {{{ */
6687 @interface SectionsView : RVPage {
6688 _transient Database *database_;
6689 NSMutableArray *sections_;
6690 NSMutableArray *filtered_;
6696 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6697 - (void) reloadData;
6702 @implementation SectionsView
6705 [list_ setDataSource:nil];
6706 [list_ setDelegate:nil];
6708 [sections_ release];
6709 [filtered_ release];
6711 [accessory_ release];
6715 - (int) numberOfRowsInTable:(UITable *)table {
6716 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6719 - (float) table:(UITable *)table heightForRow:(int)row {
6723 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6725 reusing = [[[SectionCell alloc] init] autorelease];
6726 [(SectionCell *)reusing setSection:(editing_ ?
6727 [sections_ objectAtIndex:row] :
6728 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6729 ) editing:editing_];
6733 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6737 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6741 - (void) tableRowSelected:(NSNotification *)notification {
6742 int row = [[notification object] selectedRow];
6753 title = UCLocalize("ALL_PACKAGES");
6755 section = [filtered_ objectAtIndex:(row - 1)];
6756 name = [section name];
6759 name = [NSString stringWithString:name];
6760 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6763 title = UCLocalize("NO_SECTION");
6767 PackageTable *table = [[[FilteredPackageTable alloc]
6771 filter:@selector(isVisibleInSection:)
6775 [table setDelegate:delegate_];
6777 [book_ pushPage:table];
6780 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6781 if ((self = [super initWithBook:book]) != nil) {
6782 database_ = database;
6784 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6785 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6787 list_ = [[UITable alloc] initWithFrame:[self bounds]];
6788 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6789 [self addSubview:list_];
6791 UITableColumn *column = [[[UITableColumn alloc]
6792 initWithTitle:UCLocalize("NAME")
6794 width:[self frame].size.width
6797 [list_ setDataSource:self];
6798 [list_ setSeparatorStyle:1];
6799 [list_ addTableColumn:column];
6800 [list_ setDelegate:self];
6801 [list_ setReusesTableCells:YES];
6805 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6809 - (void) reloadData {
6810 NSArray *packages = [database_ packages];
6812 [sections_ removeAllObjects];
6813 [filtered_ removeAllObjects];
6816 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6817 SectionMap sections;
6818 sections.resize(64);
6820 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6824 for (Package *package in packages) {
6825 NSString *name([package section]);
6826 NSString *key(name == nil ? @"" : name);
6831 _profile(SectionsView$reloadData$Section)
6832 section = §ions[key];
6833 if (*section == nil) {
6834 _profile(SectionsView$reloadData$Section$Allocate)
6835 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6840 [*section addToCount];
6842 _profile(SectionsView$reloadData$Filter)
6843 if (![package valid] || ![package visible])
6847 [*section addToRow];
6851 _profile(SectionsView$reloadData$Section)
6852 section = [sections objectForKey:key];
6853 if (section == nil) {
6854 _profile(SectionsView$reloadData$Section$Allocate)
6855 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6856 [sections setObject:section forKey:key];
6861 [section addToCount];
6863 _profile(SectionsView$reloadData$Filter)
6864 if (![package valid] || ![package visible])
6874 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6875 [sections_ addObject:i->second];
6877 [sections_ addObjectsFromArray:[sections allValues]];
6880 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6882 for (Section *section in sections_) {
6883 size_t count([section row]);
6887 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6888 [section setCount:count];
6889 [filtered_ addObject:section];
6896 - (void) resetView {
6898 [self _rightButtonClicked];
6901 - (void) resetViewAnimated:(BOOL)animated {
6902 [list_ resetViewAnimated:animated];
6905 - (void) _rightButtonClicked {
6906 if ((editing_ = !editing_))
6909 [delegate_ updateData];
6910 [book_ reloadTitleForPage:self];
6911 [book_ reloadButtonsForPage:self];
6914 - (NSString *) title {
6915 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS");
6918 - (NSString *) backButtonTitle {
6919 return UCLocalize("SECTIONS");
6922 - (id) rightButtonTitle {
6923 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6926 - (UINavigationButtonStyle) rightButtonStyle {
6927 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6930 - (UIView *) accessoryView {
6936 /* Changes View {{{ */
6937 @interface ChangesView : RVPage {
6938 _transient Database *database_;
6939 NSMutableArray *packages_;
6940 NSMutableArray *sections_;
6945 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6946 - (void) reloadData;
6950 @implementation ChangesView
6953 [list_ setDelegate:nil];
6954 [list_ setDataSource:nil];
6956 [packages_ release];
6957 [sections_ release];
6962 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6963 NSInteger count([sections_ count]);
6964 return count == 0 ? 1 : count;
6967 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6968 if ([sections_ count] == 0)
6970 return [[sections_ objectAtIndex:section] name];
6973 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6974 if ([sections_ count] == 0)
6976 return [[sections_ objectAtIndex:section] count];
6979 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6980 Section *section([sections_ objectAtIndex:[path section]]);
6981 NSInteger row([path row]);
6982 return [packages_ objectAtIndex:([section row] + row)];
6985 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6986 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6988 cell = [[[PackageCell alloc] init] autorelease];
6989 [cell setPackage:[self packageAtIndexPath:path]];
6993 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6995 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6998 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6999 Package *package([self packageAtIndexPath:path]);
7000 PackageView *view([delegate_ packageView]);
7001 [view setDelegate:delegate_];
7002 [view setPackage:package];
7003 [book_ pushPage:view];
7007 - (void) _leftButtonClicked {
7008 [(CYBook *)book_ update];
7009 [self reloadButtons];
7012 - (void) _rightButtonClicked {
7013 [delegate_ distUpgrade];
7016 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7017 if ((self = [super initWithBook:book]) != nil) {
7018 database_ = database;
7020 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7021 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7023 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
7024 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7025 [self addSubview:list_];
7027 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
7028 [list_ setDataSource:self];
7029 [list_ setDelegate:self];
7030 //[list_ setSectionListStyle:1];
7034 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7038 - (void) reloadData {
7039 NSArray *packages = [database_ packages];
7041 [packages_ removeAllObjects];
7042 [sections_ removeAllObjects];
7045 for (Package *package in packages)
7047 [package uninstalled] && [package valid] && [package visible] ||
7048 [package upgradableAndEssential:YES]
7050 [packages_ addObject:package];
7053 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7056 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7057 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7058 Section *section = nil;
7062 bool unseens = false;
7064 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7066 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7067 Package *package = [packages_ objectAtIndex:offset];
7069 BOOL uae = [package upgradableAndEssential:YES];
7075 _profile(ChangesView$reloadData$Remember)
7076 seen = [package seen];
7079 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7084 name = UCLocalize("UNKNOWN");
7086 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7090 _profile(ChangesView$reloadData$Allocate)
7091 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7092 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7093 [sections_ addObject:section];
7097 [section addToCount];
7098 } else if ([package ignored])
7099 [ignored addToCount];
7102 [upgradable addToCount];
7107 CFRelease(formatter);
7110 Section *last = [sections_ lastObject];
7111 size_t count = [last count];
7112 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7113 [sections_ removeLastObject];
7116 if ([ignored count] != 0)
7117 [sections_ insertObject:ignored atIndex:0];
7119 [sections_ insertObject:upgradable atIndex:0];
7122 [self reloadButtons];
7125 - (void) resetViewAnimated:(BOOL)animated {
7126 [list_ resetViewAnimated:animated];
7129 - (NSString *) leftButtonTitle {
7130 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
7133 - (id) rightButtonTitle {
7134 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
7137 - (NSString *) title {
7138 return UCLocalize("CHANGES");
7143 /* Search View {{{ */
7144 @protocol SearchViewDelegate
7145 - (void) showKeyboard:(BOOL)show;
7148 @interface SearchView : RVPage {
7150 UISearchField *field_;
7151 FilteredPackageTable *table_;
7155 - (id) initWithBook:(RVBook *)book database:(Database *)database;
7156 - (void) reloadData;
7160 @implementation SearchView
7163 [field_ setDelegate:nil];
7165 [accessory_ release];
7171 - (void) _showKeyboard:(BOOL)show {
7172 CGSize keysize = [UIKeyboard defaultSize];
7173 CGRect keydown = [book_ pageBounds];
7174 CGRect keyup = keydown;
7175 keyup.size.height -= keysize.height - ButtonBarHeight_;
7177 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7179 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7180 [animation setSignificantRectFields:8];
7183 [animation setStartFrame:keydown];
7184 [animation setEndFrame:keyup];
7186 [animation setStartFrame:keyup];
7187 [animation setEndFrame:keydown];
7190 UIAnimator *animator = [UIAnimator sharedAnimator];
7193 addAnimations:[NSArray arrayWithObjects:animation, nil]
7194 withDuration:(KeyboardTime_ - delay)
7199 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7201 //[delegate_ showKeyboard:show];
7204 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7205 [self _showKeyboard:YES];
7206 [table_ setObject:[field_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7210 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7211 [self _showKeyboard:NO];
7212 [table_ setObject:[field_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7216 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7218 NSString *text([field_ text]);
7219 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7220 [table_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7226 - (void) textFieldClearButtonPressed:(UITextField *)field {
7230 - (void) keyboardInputShouldDelete:(id)input {
7234 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7235 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7239 [field_ resignFirstResponder];
7244 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7245 if ((self = [super initWithBook:book]) != nil) {
7246 CGRect pageBounds = [book_ pageBounds];
7248 table_ = [[FilteredPackageTable alloc]
7252 filter:@selector(isUnfilteredAndSearchedForBy:)
7256 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7257 [self addSubview:table_];
7259 [table_ setShouldHideHeaderInShortLists:NO];
7261 CGRect cnfrect = {{7, 38}, {17, 18}};
7268 area.size.width = [self bounds].size.width - area.origin.x * 2;
7269 area.size.height = [UISearchField defaultHeight];
7271 field_ = [[UISearchField alloc] initWithFrame:area];
7272 [field_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7274 UIFont *font = [UIFont systemFontOfSize:16];
7275 [field_ setFont:font];
7277 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7278 [field_ setDelegate:self];
7280 [field_ setPaddingTop:5];
7282 UITextInputTraits *traits([field_ textInputTraits]);
7283 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7284 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7285 [traits setReturnKeyType:UIReturnKeySearch];
7287 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7289 accessory_ = [[UIView alloc] initWithFrame:accrect];
7290 [accessory_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7291 [accessory_ addSubview:field_];
7293 [self setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7297 - (void) resetViewAnimated:(BOOL)animated {
7298 [table_ resetViewAnimated:animated];
7301 - (void) _reloadData {
7304 - (void) reloadData {
7305 _profile(SearchView$reloadData)
7306 [table_ reloadData];
7309 [table_ resetCursor];
7312 - (UIView *) accessoryView {
7316 - (NSString *) title {
7320 - (NSString *) backButtonTitle {
7321 return UCLocalize("SEARCH");
7324 - (void) setDelegate:(id)delegate {
7325 [table_ setDelegate:delegate];
7326 [super setDelegate:delegate];
7331 /* Settings View {{{ */
7332 @interface SettingsView : RVPage {
7333 _transient Database *database_;
7336 UIPreferencesTable *table_;
7337 _UISwitchSlider *subscribedSwitch_;
7338 _UISwitchSlider *ignoredSwitch_;
7339 UIPreferencesControlTableCell *subscribedCell_;
7340 UIPreferencesControlTableCell *ignoredCell_;
7343 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7347 @implementation SettingsView
7350 [table_ setDataSource:nil];
7353 if (package_ != nil)
7356 [subscribedSwitch_ release];
7357 [ignoredSwitch_ release];
7358 [subscribedCell_ release];
7359 [ignoredCell_ release];
7363 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7364 if (package_ == nil)
7370 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7371 if (package_ == nil)
7384 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7385 if (package_ == nil)
7398 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7399 if (package_ == nil)
7412 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7413 if (package_ == nil)
7416 _UISwitchSlider *slider([cell control]);
7417 BOOL value([slider value] != 0);
7418 NSMutableDictionary *metadata([package_ metadata]);
7421 if (NSNumber *number = [metadata objectForKey:key])
7422 before = [number boolValue];
7426 if (value != before) {
7427 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7429 [delegate_ updateData];
7433 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7434 [self onSomething:cell withKey:@"IsSubscribed"];
7437 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7438 [self onSomething:cell withKey:@"IsIgnored"];
7441 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7442 if (package_ == nil)
7446 case 0: switch (row) {
7448 return subscribedCell_;
7450 return ignoredCell_;
7454 case 1: switch (row) {
7456 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7457 [cell setShowSelection:NO];
7458 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7471 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7472 if ((self = [super initWithBook:book])) {
7473 database_ = database;
7474 name_ = [package retain];
7476 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7477 [self addSubview:table_];
7479 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7480 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7482 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7483 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7485 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7486 [subscribedCell_ setShowSelection:NO];
7487 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7488 [subscribedCell_ setControl:subscribedSwitch_];
7490 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7491 [ignoredCell_ setShowSelection:NO];
7492 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7493 [ignoredCell_ setControl:ignoredSwitch_];
7495 [table_ setDataSource:self];
7500 - (void) resetViewAnimated:(BOOL)animated {
7501 [table_ resetViewAnimated:animated];
7504 - (void) reloadData {
7505 if (package_ != nil)
7506 [package_ autorelease];
7507 package_ = [database_ packageWithName:name_];
7508 if (package_ != nil) {
7510 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7511 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7514 [table_ reloadData];
7517 - (NSString *) title {
7518 return UCLocalize("SETTINGS");
7524 /* Signature View {{{ */
7525 @interface SignatureView : CydiaBrowserView {
7526 _transient Database *database_;
7530 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7534 @implementation SignatureView
7541 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7543 [super webView:sender didClearWindowObject:window forFrame:frame];
7546 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7547 if ((self = [super initWithBook:book]) != nil) {
7548 database_ = database;
7549 package_ = [package retain];
7554 - (void) resetViewAnimated:(BOOL)animated {
7557 - (void) reloadData {
7558 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7564 @interface CydiaViewController : UIViewController {
7569 @implementation CydiaViewController
7571 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7572 return NO; // XXX: return YES;
7577 @interface Cydia : UIApplication <
7578 ConfirmationViewDelegate,
7579 ProgressViewDelegate,
7584 CydiaViewController *root_;
7589 UIToolbar *toolbar_;
7593 NSMutableArray *essential_;
7594 NSMutableArray *broken_;
7596 Database *database_;
7597 ProgressView *progress_;
7601 UIKeyboard *keyboard_;
7602 UIProgressHUD *hud_;
7604 SectionsView *sections_;
7605 ChangesView *changes_;
7606 ManageView *manage_;
7607 SearchView *search_;
7609 #if RecyclePackageViews
7610 NSMutableArray *details_;
7614 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7615 - (void) setPage:(RVPage *)page;
7619 static _finline void _setHomePage(Cydia *self) {
7620 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeView class]]];
7623 @implementation Cydia
7625 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7630 if ([broken_ count] != 0) {
7631 int count = [broken_ count];
7633 UIActionSheet *sheet = [[[UIActionSheet alloc]
7634 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7635 buttons:[NSArray arrayWithObjects:
7636 UCLocalize("FORCIBLY_CLEAR"),
7637 UCLocalize("TEMPORARY_IGNORE"),
7639 defaultButtonIndex:0
7644 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7646 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7647 [sheet popupAlertAnimated:YES];
7648 } else if (!Ignored_ && [essential_ count] != 0) {
7649 int count = [essential_ count];
7651 UIActionSheet *sheet = [[[UIActionSheet alloc]
7652 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7653 buttons:[NSArray arrayWithObjects:
7654 UCLocalize("UPGRADE_ESSENTIAL"),
7655 UCLocalize("COMPLETE_UPGRADE"),
7656 UCLocalize("TEMPORARY_IGNORE"),
7658 defaultButtonIndex:0
7663 [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7665 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7666 [sheet popupAlertAnimated:YES];
7670 - (void) _saveConfig {
7673 NSString *error(nil);
7674 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7676 NSError *error(nil);
7677 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7678 NSLog(@"failure to save metadata data: %@", error);
7681 NSLog(@"failure to serialize metadata: %@", error);
7689 - (void) _updateData {
7692 /* XXX: this is just stupid */
7693 if (tag_ != 2 && sections_ != nil)
7694 [sections_ reloadData];
7695 if (tag_ != 3 && changes_ != nil)
7696 [changes_ reloadData];
7697 if (tag_ != 5 && search_ != nil)
7698 [search_ reloadData];
7703 - (void) _reloadData {
7706 static bool loaded(false);
7707 UIProgressHUD *hud([self addProgressHUD]);
7708 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7710 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7713 [self removeProgressHUD:hud];
7717 [essential_ removeAllObjects];
7718 [broken_ removeAllObjects];
7720 NSArray *packages([database_ packages]);
7721 for (Package *package in packages) {
7723 [broken_ addObject:package];
7724 if ([package upgradableAndEssential:NO]) {
7725 if ([package essential])
7726 [essential_ addObject:package];
7732 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7733 [toolbar_ setBadgeValue:badge forButton:3];
7734 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7735 [toolbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7736 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7737 [self setApplicationBadge:badge];
7739 [self setApplicationBadgeString:badge];
7741 [toolbar_ setBadgeValue:nil forButton:3];
7742 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7743 [toolbar_ setBadgeAnimated:NO forButton:3];
7744 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7745 [self removeApplicationBadge];
7746 else // XXX: maybe use setApplicationBadgeString also?
7747 [self setApplicationIconBadgeNumber:0];
7751 [toolbar_ setBadgeValue:nil forButton:4];
7755 if (loaded || ManualRefresh) loaded:
7760 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
7762 if (update != nil) {
7763 NSTimeInterval interval([update timeIntervalSinceNow]);
7764 if (interval <= 0 && interval > -(15*60))
7768 [book_ setUpdate:update];
7772 - (void) updateData {
7773 [database_ setVisible];
7782 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7783 _assert(file != NULL);
7785 for (NSString *key in [Sources_ allKeys]) {
7786 NSDictionary *source([Sources_ objectForKey:key]);
7788 fprintf(file, "%s %s %s\n",
7789 [[source objectForKey:@"Type"] UTF8String],
7790 [[source objectForKey:@"URI"] UTF8String],
7791 [[source objectForKey:@"Distribution"] UTF8String]
7800 detachNewThreadSelector:@selector(update_)
7803 title:UCLocalize("UPDATING_SOURCES")
7807 - (void) reloadData {
7808 @synchronized (self) {
7809 if (confirm_ == nil)
7815 pkgProblemResolver *resolver = [database_ resolver];
7817 resolver->InstallProtect();
7818 if (!resolver->Resolve(true))
7822 - (void) popUpBook:(RVBook *)book {
7823 [underlay_ popSubview:book];
7826 - (CGRect) popUpBounds {
7827 return [underlay_ bounds];
7831 if (![database_ prepare])
7834 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7835 [confirm_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7836 [confirm_ setDelegate:self];
7838 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7839 [page setDelegate:self];
7841 [confirm_ setPage:page];
7842 [self popUpBook:confirm_];
7848 @synchronized (self) {
7853 - (void) clearPackage:(Package *)package {
7854 @synchronized (self) {
7861 - (void) installPackage:(Package *)package {
7862 @synchronized (self) {
7869 - (void) removePackage:(Package *)package {
7870 @synchronized (self) {
7877 - (void) distUpgrade {
7878 @synchronized (self) {
7879 if (![database_ upgrade])
7886 [self slideUp:[[[UIActionSheet alloc]
7888 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7889 defaultButtonIndex:1
7896 @synchronized (self) {
7899 if (confirm_ != nil) {
7907 [overlay_ removeFromSuperview];
7911 detachNewThreadSelector:@selector(perform)
7914 title:UCLocalize("RUNNING")
7918 - (void) progressViewIsComplete:(ProgressView *)progress {
7919 if (confirm_ != nil) {
7920 [underlay_ addSubview:overlay_];
7921 [confirm_ popFromSuperviewAnimated:NO];
7927 - (void) setPage:(RVPage *)page {
7928 [page resetViewAnimated:NO];
7929 [page setDelegate:self];
7930 [book_ setPage:page];
7933 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7934 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7935 [browser loadURL:url];
7939 - (SectionsView *) sectionsView {
7940 if (sections_ == nil)
7941 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7945 - (ChangesView *) changesView {
7946 if (changes_ == nil)
7947 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7951 - (ManageView *) manageView {
7953 manage_ = (ManageView *) [[self
7954 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7955 withClass:[ManageView class]
7960 - (SearchView *) searchView {
7962 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7966 - (void) buttonBarItemTapped:(id)sender {
7967 unsigned tag = [sender tag];
7969 [book_ resetViewAnimated:YES];
7971 } else if (tag_ == 2)
7972 [[self sectionsView] resetView];
7975 case 1: _setHomePage(self); break;
7977 case 2: [self setPage:[self sectionsView]]; break;
7978 case 3: [self setPage:[self changesView]]; break;
7979 case 4: [self setPage:[self manageView]]; break;
7980 case 5: [self setPage:[self searchView]]; break;
7988 - (void) askForSettings {
7989 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7991 CYActionSheet *role([[[CYActionSheet alloc]
7992 initWithTitle:UCLocalize("WHO_ARE_YOU")
7993 buttons:[NSArray arrayWithObjects:
7994 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7995 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7996 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7998 defaultButtonIndex:-1
8001 [role setBodyText:UCLocalize("ROLE_EX")];
8003 int button([role yieldToPopupAlertAnimated:YES]);
8006 case 1: Role_ = @"User"; break;
8007 case 2: Role_ = @"Hacker"; break;
8008 case 3: Role_ = @"Developer"; break;
8013 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8017 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8024 - (void) setPackageView:(PackageView *)view {
8026 [view setPackage:nil];
8027 #if RecyclePackageViews
8028 if ([details_ count] < 3)
8029 [details_ addObject:view];
8034 - (PackageView *) _packageView {
8035 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
8038 - (PackageView *) packageView {
8039 #if RecyclePackageViews
8041 size_t count([details_ count]);
8044 view = [self _packageView];
8046 [details_ addObject:[self _packageView]];
8048 view = [[[details_ lastObject] retain] autorelease];
8049 [details_ removeLastObject];
8056 return [self _packageView];
8060 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
8061 NSString *context([sheet context]);
8063 if ([context isEqualToString:@"missing"])
8065 else if ([context isEqualToString:@"cancel"]) {
8082 @synchronized (self) {
8087 [toolbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
8091 if (confirm_ != nil) {
8096 } else if ([context isEqualToString:@"fixhalf"]) {
8099 @synchronized (self) {
8100 for (Package *broken in broken_) {
8103 NSString *id = [broken id];
8104 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8105 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8106 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8107 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8116 [broken_ removeAllObjects];
8124 } else if ([context isEqualToString:@"upgrade"]) {
8127 @synchronized (self) {
8128 for (Package *essential in essential_)
8129 [essential install];
8151 - (void) system:(NSString *)command { _pooled
8152 system([command UTF8String]);
8155 - (void) applicationWillSuspend {
8157 [super applicationWillSuspend];
8160 - (void) applicationSuspend:(__GSEvent *)event {
8161 if (hud_ == nil && ![progress_ isRunning])
8162 [super applicationSuspend:event];
8165 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8167 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8170 - (void) _setSuspended:(BOOL)value {
8172 [super _setSuspended:value];
8175 - (UIProgressHUD *) addProgressHUD {
8176 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8177 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8179 [window_ setUserInteractionEnabled:NO];
8181 [progress_ addSubview:hud];
8185 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8187 [hud removeFromSuperview];
8188 [window_ setUserInteractionEnabled:YES];
8191 - (RVPage *) pageForPackage:(NSString *)name {
8192 if (Package *package = [database_ packageWithName:name]) {
8193 PackageView *view([self packageView]);
8194 [view setPackage:package];
8197 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8198 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8199 return [self _pageForURL:url withClass:[CydiaBrowserView class]];
8203 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8207 NSString *href([url absoluteString]);
8208 if ([href hasPrefix:@"apptapp://package/"])
8209 return [self pageForPackage:[href substringFromIndex:18]];
8211 NSString *scheme([[url scheme] lowercaseString]);
8212 if (![scheme isEqualToString:@"cydia"])
8214 NSString *path([url absoluteString]);
8215 if ([path length] < 8)
8217 path = [path substringFromIndex:8];
8218 if (![path hasPrefix:@"/"])
8219 path = [@"/" stringByAppendingString:path];
8221 if ([path isEqualToString:@"/add-source"])
8222 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8223 else if ([path isEqualToString:@"/storage"])
8224 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8225 else if ([path isEqualToString:@"/sources"])
8226 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8227 else if ([path isEqualToString:@"/packages"])
8228 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8229 else if ([path hasPrefix:@"/url/"])
8230 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8231 else if ([path hasPrefix:@"/launch/"])
8232 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8233 else if ([path hasPrefix:@"/package-settings/"])
8234 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8235 else if ([path hasPrefix:@"/package-signature/"])
8236 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8237 else if ([path hasPrefix:@"/package/"])
8238 return [self pageForPackage:[path substringFromIndex:9]];
8239 else if ([path hasPrefix:@"/files/"]) {
8240 NSString *name = [path substringFromIndex:7];
8242 if (Package *package = [database_ packageWithName:name]) {
8243 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8244 [files setPackage:package];
8252 - (void) applicationOpenURL:(NSURL *)url {
8253 [super applicationOpenURL:url];
8255 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8256 [self setPage:page];
8257 [toolbar_ showSelectionForButton:tag];
8262 - (void) applicationDidFinishLaunching:(id)unused {
8263 [BrowserView _initialize];
8265 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8267 Font12_ = [[UIFont systemFontOfSize:12] retain];
8268 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8269 Font14_ = [[UIFont systemFontOfSize:14] retain];
8270 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8271 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8275 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8276 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8278 UIScreen *screen([UIScreen mainScreen]);
8280 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8281 [window_ orderFront:self];
8282 [window_ makeKey:self];
8283 [window_ setHidden:NO];
8285 root_ = [[CydiaViewController alloc] init];
8286 [window_ addSubview:[root_ view]];
8288 database_ = [Database sharedInstance];
8290 progress_ = [[ProgressView alloc] initWithFrame:[[root_ view] bounds] database:database_ delegate:self];
8291 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8292 [[root_ view] addSubview:progress_];
8294 [database_ setDelegate:progress_];
8296 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8297 [underlay_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8298 [progress_ setContentView:underlay_];
8300 [progress_ resetView];
8303 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8304 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8305 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8306 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8307 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8308 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8309 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8310 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8311 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8314 [self setIdleTimerDisabled:YES];
8316 hud_ = [self addProgressHUD];
8317 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8318 [self setStatusBarShowsProgress:YES];
8320 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8322 [self setStatusBarShowsProgress:NO];
8323 [self removeProgressHUD:hud_];
8326 if (ExecFork() == 0) {
8327 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8328 perror("launchctl stop");
8335 [self askForSettings];
8338 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
8339 [overlay_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8341 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8343 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
8344 0, 0, screenrect.size.width, screenrect.size.height - 48
8345 ) database:database_];
8347 [book_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8348 [overlay_ addSubview:book_];
8350 [book_ setDelegate:self];
8352 NSArray *buttonitems = [NSArray arrayWithObjects:
8353 [NSDictionary dictionaryWithObjectsAndKeys:
8354 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8355 @"home-up.png", kUIButtonBarButtonInfo,
8356 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
8357 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
8358 self, kUIButtonBarButtonTarget,
8359 @"Cydia", kUIButtonBarButtonTitle,
8360 @"0", kUIButtonBarButtonType,
8363 [NSDictionary dictionaryWithObjectsAndKeys:
8364 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8365 @"install-up.png", kUIButtonBarButtonInfo,
8366 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
8367 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
8368 self, kUIButtonBarButtonTarget,
8369 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
8370 @"0", kUIButtonBarButtonType,
8373 [NSDictionary dictionaryWithObjectsAndKeys:
8374 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8375 @"changes-up.png", kUIButtonBarButtonInfo,
8376 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
8377 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
8378 self, kUIButtonBarButtonTarget,
8379 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
8380 @"0", kUIButtonBarButtonType,
8383 [NSDictionary dictionaryWithObjectsAndKeys:
8384 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8385 @"manage-up.png", kUIButtonBarButtonInfo,
8386 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
8387 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
8388 self, kUIButtonBarButtonTarget,
8389 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
8390 @"0", kUIButtonBarButtonType,
8393 [NSDictionary dictionaryWithObjectsAndKeys:
8394 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8395 @"search-up.png", kUIButtonBarButtonInfo,
8396 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
8397 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
8398 self, kUIButtonBarButtonTarget,
8399 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
8400 @"0", kUIButtonBarButtonType,
8404 toolbar_ = [[UIToolbar alloc]
8406 withFrame:CGRectMake(
8407 0, screenrect.size.height - ButtonBarHeight_,
8408 screenrect.size.width, ButtonBarHeight_
8410 withItemList:buttonitems
8413 [toolbar_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
8414 [overlay_ addSubview:toolbar_];
8416 [toolbar_ setDelegate:self];
8417 [toolbar_ setBarStyle:1];
8418 [toolbar_ setButtonBarTrackingMode:2];
8420 int buttons[5] = {1, 2, 3, 4, 5};
8421 [toolbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
8422 [toolbar_ showButtonGroup:0 withDuration:0];
8424 for (int i = 0; i != 5; ++i) {
8425 UIView *button([toolbar_ viewWithTag:(i + 1)]);
8427 [button setFrame:CGRectMake(
8428 i * (screenrect.size.width / 5) + (screenrect.size.width / 5 - ButtonBarWidth_) / 2, 1,
8429 ButtonBarWidth_, ButtonBarHeight_
8432 [button setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8435 [toolbar_ showSelectionForButton:1];
8437 [UIKeyboard initImplementationNow];
8438 /*CGSize keysize = [UIKeyboard defaultSize];
8439 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8440 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8441 [overlay_ addSubview:keyboard_];*/
8443 [underlay_ addSubview:overlay_];
8447 #if RecyclePackageViews
8448 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8449 [details_ addObject:[self _packageView]];
8450 [details_ addObject:[self _packageView]];
8458 - (void) showKeyboard:(BOOL)show {
8459 CGSize keysize([UIKeyboard defaultSize]);
8460 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8461 CGRect keyup(keydown);
8462 keyup.origin.y -= keysize.height;
8464 UIFrameAnimation *animation([[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease]);
8465 [animation setSignificantRectFields:2];
8468 [animation setStartFrame:keydown];
8469 [animation setEndFrame:keyup];
8470 [keyboard_ activate];
8472 [animation setStartFrame:keyup];
8473 [animation setEndFrame:keydown];
8474 [keyboard_ deactivate];
8477 [[UIAnimator sharedAnimator]
8478 addAnimations:[NSArray arrayWithObjects:animation, nil]
8479 withDuration:KeyboardTime_
8484 - (void) slideUp:(UIActionSheet *)alert {
8485 [alert setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8486 [alert presentSheetInView:overlay_];
8492 id Alloc_(id self, SEL selector) {
8493 id object = alloc_(self, selector);
8494 lprintf("[%s]A-%p\n", self->isa->name, object);
8499 id Dealloc_(id self, SEL selector) {
8500 id object = dealloc_(self, selector);
8501 lprintf("[%s]D-%p\n", self->isa->name, object);
8505 Class $WebDefaultUIKitDelegate;
8507 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8508 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8509 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8510 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8513 int main(int argc, char *argv[]) { _pooled
8516 if (Class $UIDevice = objc_getClass("UIDevice")) {
8517 UIDevice *device([$UIDevice currentDevice]);
8518 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8522 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8524 /* Library Hacks {{{ */
8525 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8527 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8528 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8529 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8530 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8531 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8534 /* Set Locale {{{ */
8535 Locale_ = CFLocaleCopyCurrent();
8536 Languages_ = [NSLocale preferredLanguages];
8537 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8538 //NSLog(@"%@", [Languages_ description]);
8541 if (Languages_ == nil || [Languages_ count] == 0)
8542 // XXX: consider just setting to C and then falling through?
8545 lang = [[Languages_ objectAtIndex:0] UTF8String];
8546 setenv("LANG", lang, true);
8549 //std::setlocale(LC_ALL, lang);
8550 NSLog(@"Setting Language: %s", lang);
8553 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8555 /* Parse Arguments {{{ */
8556 bool substrate(false);
8562 for (int argi(1); argi != argc; ++argi)
8563 if (strcmp(argv[argi], "--") == 0) {
8565 argv[argi] = argv[0];
8571 for (int argi(1); argi != arge; ++argi)
8572 if (strcmp(args[argi], "--substrate") == 0)
8575 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8579 App_ = [[NSBundle mainBundle] bundlePath];
8580 Home_ = NSHomeDirectory();
8586 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8587 alloc_ = alloc->method_imp;
8588 alloc->method_imp = (IMP) &Alloc_;*/
8590 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8591 dealloc_ = dealloc->method_imp;
8592 dealloc->method_imp = (IMP) &Dealloc_;*/
8594 /* System Information {{{ */
8598 size = sizeof(maxproc);
8599 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8600 perror("sysctlbyname(\"kern.maxproc\", ?)");
8601 else if (maxproc < 64) {
8603 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8604 perror("sysctlbyname(\"kern.maxproc\", #)");
8607 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8608 char *osversion = new char[size];
8609 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8610 perror("sysctlbyname(\"kern.osversion\", ?)");
8612 System_ = [NSString stringWithUTF8String:osversion];
8614 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8615 char *machine = new char[size];
8616 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8617 perror("sysctlbyname(\"hw.machine\", ?)");
8621 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8622 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8623 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8624 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8628 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8629 NSData *data((NSData *) ecid);
8630 size_t length([data length]);
8631 uint8_t bytes[length];
8632 [data getBytes:bytes];
8633 char string[length * 2 + 1];
8634 for (size_t i(0); i != length; ++i)
8635 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8636 ChipID_ = [NSString stringWithUTF8String:string];
8640 IOObjectRelease(service);
8644 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8646 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8647 Build_ = [system objectForKey:@"ProductBuildVersion"];
8648 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8649 Product_ = [info objectForKey:@"SafariProductVersion"];
8650 Safari_ = [info objectForKey:@"CFBundleVersion"];
8653 /* Load Database {{{ */
8655 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8657 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8660 if (Metadata_ == NULL)
8661 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8663 Settings_ = [Metadata_ objectForKey:@"Settings"];
8665 Packages_ = [Metadata_ objectForKey:@"Packages"];
8666 Sections_ = [Metadata_ objectForKey:@"Sections"];
8667 Sources_ = [Metadata_ objectForKey:@"Sources"];
8669 Token_ = [Metadata_ objectForKey:@"Token"];
8672 if (Settings_ != nil)
8673 Role_ = [Settings_ objectForKey:@"Role"];
8675 if (Packages_ == nil) {
8676 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8677 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8680 if (Sections_ == nil) {
8681 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8682 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8685 if (Sources_ == nil) {
8686 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8687 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8692 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8695 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8697 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8698 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
8699 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8700 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8701 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8702 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8704 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8706 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8707 unlink("/tmp/.cydia.fw");
8709 } else if (access("/User", F_OK) != 0 || version < 1) {
8712 system("/usr/libexec/cydia/firmware.sh");
8716 _assert([[NSFileManager defaultManager]
8717 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8718 withIntermediateDirectories:YES
8723 if (access("/tmp/cydia.chk", F_OK) == 0) {
8724 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8725 _assert(errno == ENOENT);
8726 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8727 _assert(errno == ENOENT);
8730 /* APT Initialization {{{ */
8731 _assert(pkgInitConfig(*_config));
8732 _assert(pkgInitSystem(*_config, _system));
8735 _config->Set("APT::Acquire::Translation", lang);
8736 _config->Set("Acquire::http::Timeout", 15);
8737 _config->Set("Acquire::http::MaxParallel", 3);
8739 /* Color Choices {{{ */
8740 space_ = CGColorSpaceCreateDeviceRGB();
8742 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8743 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8744 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8745 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8746 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8747 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8748 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8749 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8750 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8752 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8753 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8755 /* UIKit Configuration {{{ */
8756 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8757 if ($GSFontSetUseLegacyFontMetrics != NULL)
8758 $GSFontSetUseLegacyFontMetrics(YES);
8760 // XXX: I have a feeling this was important
8761 //UIKeyboardDisableAutomaticAppearance();
8764 Colon_ = UCLocalize("COLON_DELIMITED");
8765 Error_ = UCLocalize("ERROR");
8766 Warning_ = UCLocalize("WARNING");
8769 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8771 CGColorSpaceRelease(space_);