1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
111 #include <mach-o/nlist.h>
121 #include <Cytore.hpp>
123 #include "UICaboodle/BrowserView.h"
124 #include "SDURLCache/SDURLCache.h"
126 #include "substrate.h"
133 #define _timestamp ({ \
135 gettimeofday(&tv, NULL); \
136 tv.tv_sec * 1000000 + tv.tv_usec; \
139 typedef std::vector<class ProfileTime *> TimeList;
149 ProfileTime(const char *name) :
153 times_.push_back(this);
156 void AddTime(uint64_t time) {
163 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
175 ProfileTimer(ProfileTime &time) :
182 time_.AddTime(_timestamp - start_);
187 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
189 std::cerr << "========" << std::endl;
192 #define _profile(name) { \
193 static ProfileTime name(#name); \
194 ProfileTimer _ ## name(name);
199 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
201 #define CYPoolStart() \
202 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
204 #define CYPoolEnd() \
208 // Hash Functions/Structures {{{
209 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
217 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
219 void NSLogPoint(const char *fix, const CGPoint &point) {
220 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
223 void NSLogRect(const char *fix, const CGRect &rect) {
224 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
227 static _finline NSString *CydiaURL(NSString *path) {
229 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
230 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
231 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
232 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
233 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
234 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
237 static _finline void UpdateExternalStatus(uint64_t newStatus) {
239 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
240 notify_set_state(notify_token, newStatus);
241 notify_cancel(notify_token);
243 notify_post("com.saurik.Cydia.status");
246 /* [NSObject yieldToSelector:(withObject:)] {{{*/
247 @interface NSObject (Cydia)
248 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
249 - (id) yieldToSelector:(SEL)selector;
252 @implementation NSObject (Cydia)
257 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
258 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
259 id object([[context objectAtIndex:1] nonretainedObjectValue]);
260 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
262 /* XXX: deal with exceptions */
263 id value([self performSelector:selector withObject:object]);
265 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
266 [context removeAllObjects];
267 if ([signature methodReturnLength] != 0 && value != nil)
268 [context addObject:value];
273 performSelectorOnMainThread:@selector(doNothing)
279 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
280 volatile bool stopped(false);
282 NSMutableArray *context([NSMutableArray arrayWithObjects:
283 [NSValue valueWithPointer:selector],
284 [NSValue valueWithNonretainedObject:object],
285 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
288 NSThread *thread([[[NSThread alloc]
290 selector:@selector(_yieldToContext:)
296 NSRunLoop *loop([NSRunLoop currentRunLoop]);
297 NSDate *future([NSDate distantFuture]);
299 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
301 return [context count] == 0 ? nil : [context objectAtIndex:0];
304 - (id) yieldToSelector:(SEL)selector {
305 return [self yieldToSelector:selector withObject:nil];
311 /* Cydia Action Sheet {{{ */
312 @interface CYActionSheet : UIAlertView {
316 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
319 @implementation CYActionSheet
321 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
322 if ((self = [super init])) {
323 [self setTitle:title];
324 [self setDelegate:self];
325 for (NSString *button in buttons) [self addButtonWithTitle:button];
326 [self setCancelButtonIndex:index];
330 - (void) _updateFrameForDisplay {
331 [super _updateFrameForDisplay];
332 if ([self cancelButtonIndex] == -1) {
333 NSArray *buttons = [self buttons];
334 if ([buttons count]) {
335 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
336 for (UIThreePartButton *button in buttons)
337 [button setBackground:background forState:0];
342 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
343 button_ = buttonIndex + 1;
347 [self dismissWithClickedButtonIndex:-1 animated:YES];
350 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
351 [self setRunsModal:YES];
360 /* NSForcedOrderingSearch doesn't work on the iPhone */
361 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
362 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
363 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
365 /* Information Dictionaries {{{ */
366 @interface NSMutableArray (Cydia)
367 - (void) addInfoDictionary:(NSDictionary *)info;
370 @implementation NSMutableArray (Cydia)
372 - (void) addInfoDictionary:(NSDictionary *)info {
373 [self addObject:info];
378 @interface NSMutableDictionary (Cydia)
379 - (void) addInfoDictionary:(NSDictionary *)info;
382 @implementation NSMutableDictionary (Cydia)
384 - (void) addInfoDictionary:(NSDictionary *)info {
385 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
391 #define lprintf(args...) fprintf(stderr, args)
394 #define TraceLogging (1 && !ForRelease)
395 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
396 #define ProfileTimes (0 && !ForRelease)
397 #define ForSaurik (0 && !ForRelease)
398 #define LogBrowser (0 && !ForRelease)
399 #define TrackResize (0 && !ForRelease)
400 #define ManualRefresh (1 && !ForRelease)
401 #define ShowInternals (0 && !ForRelease)
402 #define IgnoreInstall (0 && !ForRelease)
403 #define AlwaysReload (0 && !ForRelease)
407 #define _trace(args...)
412 #define _profile(name) {
415 #define PrintTimes() do {} while (false)
419 typedef uint32_t (*SKRadixFunction)(id, void *);
421 @interface NSMutableArray (Radix)
422 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
430 @implementation NSMutableArray (Radix)
432 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
433 size_t count([self count]);
434 struct RadixItem_ *swap(new RadixItem_[count * 2]);
436 for (size_t i(0); i != count; ++i) {
437 RadixItem_ &item(swap[i]);
440 id object([self objectAtIndex:i]);
441 item.key = function(object, argument);
444 struct RadixItem_ *lhs(swap), *rhs(swap + count);
446 static const size_t width = 32;
447 static const size_t bits = 11;
448 static const size_t slots = 1 << bits;
449 static const size_t passes = (width + (bits - 1)) / bits;
451 size_t *hist(new size_t[slots]);
453 for (size_t pass(0); pass != passes; ++pass) {
454 memset(hist, 0, sizeof(size_t) * slots);
456 for (size_t i(0); i != count; ++i) {
457 uint32_t key(lhs[i].key);
459 key &= _not(uint32_t) >> width - bits;
464 for (size_t i(0); i != slots; ++i) {
465 size_t local(offset);
470 for (size_t i(0); i != count; ++i) {
471 uint32_t key(lhs[i].key);
473 key &= _not(uint32_t) >> width - bits;
474 rhs[hist[key]++] = lhs[i];
477 RadixItem_ *tmp(lhs);
484 const void **values(new const void *[count]);
485 for (size_t i(0); i != count; ++i)
486 values[i] = [self objectAtIndex:lhs[i].index];
487 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
495 /* Insertion Sort {{{ */
497 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
498 const char *ptr = (const char *)list;
500 CFIndex half = count / 2;
501 const char *probe = ptr + elementSize * half;
502 CFComparisonResult cr = comparator(element, probe, context);
503 if (0 == cr) return (probe - (const char *)list) / elementSize;
504 ptr = (cr < 0) ? ptr : probe + elementSize;
505 count = (cr < 0) ? half : (half + (count & 1) - 1);
507 return (ptr - (const char *)list) / elementSize;
510 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
511 const char *ptr = (const char *)list;
513 CFIndex half = count / 2;
514 const char *probe = ptr + elementSize * half;
515 CFComparisonResult cr = comparator(element, probe, context);
516 if (0 == cr) return (probe - (const char *)list) / elementSize;
517 ptr = (cr < 0) ? ptr : probe + elementSize;
518 count = (cr < 0) ? half : (half + (count & 1) - 1);
520 return (ptr - (const char *)list) / elementSize;
523 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
524 if (range.length == 0)
526 const void **values(new const void *[range.length]);
527 CFArrayGetValues(array, range, values);
529 #if HistogramInsertionSort > 0
530 uint32_t total(0), *offsets(new uint32_t[range.length]);
533 for (CFIndex index(1); index != range.length; ++index) {
534 const void *value(values[index]);
535 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
536 CFIndex correct(index);
537 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
538 #if HistogramInsertionSort > 1
539 NSLog(@"%@ < %@", value, values[correct - 1]);
544 if (correct != index) {
545 size_t offset(index - correct);
546 #if HistogramInsertionSort
550 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
552 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
553 values[correct] = value;
557 CFArrayReplaceValues(array, range, values, range.length);
560 #if HistogramInsertionSort > 0
561 for (CFIndex index(0); index != range.length; ++index)
562 if (offsets[index] != 0)
563 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
564 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
571 /* Apple Bug Fixes {{{ */
572 @implementation UIWebDocumentView (Cydia)
574 - (void) _setScrollerOffset:(CGPoint)offset {
575 UIScroller *scroller([self _scroller]);
577 CGSize size([scroller contentSize]);
578 CGSize bounds([scroller bounds].size);
581 max.x = size.width - bounds.width;
582 max.y = size.height - bounds.height;
590 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
591 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
593 [scroller setOffset:offset];
599 @implementation WebScriptObject (NSFastEnumeration)
601 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
602 size_t length([self count] - state->state);
605 else if (length > count)
607 for (size_t i(0); i != length; ++i)
608 objects[i] = [self objectAtIndex:state->state++];
609 state->itemsPtr = objects;
610 state->mutationsPtr = (unsigned long *) self;
616 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
617 size_t length([self length] - state->state);
620 else if (length > count)
622 for (size_t i(0); i != length; ++i)
623 objects[i] = [self item:state->state++];
624 state->itemsPtr = objects;
625 state->mutationsPtr = (unsigned long *) self;
629 /* Cydia NSString Additions {{{ */
630 @interface NSString (Cydia)
631 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
632 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
633 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
634 - (NSComparisonResult) compareByPath:(NSString *)other;
635 - (NSString *) stringByCachingURLWithCurrentCDN;
636 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
639 @implementation NSString (Cydia)
641 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
642 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
645 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
646 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
647 memcpy(data, bytes, length);
648 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
651 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
652 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
655 - (NSComparisonResult) compareByPath:(NSString *)other {
656 NSString *prefix = [self commonPrefixWithString:other options:0];
657 size_t length = [prefix length];
659 NSRange lrange = NSMakeRange(length, [self length] - length);
660 NSRange rrange = NSMakeRange(length, [other length] - length);
662 lrange = [self rangeOfString:@"/" options:0 range:lrange];
663 rrange = [other rangeOfString:@"/" options:0 range:rrange];
665 NSComparisonResult value;
667 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
668 value = NSOrderedSame;
669 else if (lrange.location == NSNotFound)
670 value = NSOrderedAscending;
671 else if (rrange.location == NSNotFound)
672 value = NSOrderedDescending;
674 value = NSOrderedSame;
676 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
677 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
678 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
679 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
681 NSComparisonResult result = [lpath compare:rpath];
682 return result == NSOrderedSame ? value : result;
685 - (NSString *) stringByCachingURLWithCurrentCDN {
687 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
688 withString:@"://cache.cydia.saurik.com/"
692 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
693 return [(id)CFURLCreateStringByAddingPercentEscapes(
698 kCFStringEncodingUTF8
705 /* C++ NSString Wrapper Cache {{{ */
706 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
707 return size == 0 ? NULL :
708 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
709 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
712 static _finline CFStringRef CYStringCreate(const char *data) {
713 return CYStringCreate(data, strlen(data));
722 _finline void clear_() {
723 if (cache_ != NULL) {
730 _finline bool empty() const {
734 _finline size_t size() const {
738 _finline char *data() const {
742 _finline void clear() {
747 _finline CYString() :
754 _finline ~CYString() {
758 void operator =(const CYString &rhs) {
762 if (rhs.cache_ == nil)
765 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
768 void copy(apr_pool_t *pool) {
769 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
770 memcpy(temp, data_, size_);
775 void set(apr_pool_t *pool, const char *data, size_t size) {
781 data_ = const_cast<char *>(data);
789 _finline void set(apr_pool_t *pool, const char *data) {
790 set(pool, data, data == NULL ? 0 : strlen(data));
793 _finline void set(apr_pool_t *pool, const std::string &rhs) {
794 set(pool, rhs.data(), rhs.size());
797 bool operator ==(const CYString &rhs) const {
798 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
801 _finline operator CFStringRef() {
803 cache_ = CYStringCreate(data_, size_);
807 _finline operator id() {
808 return (NSString *) static_cast<CFStringRef>(*this);
811 _finline operator const char *() {
812 return reinterpret_cast<const char *>(data_);
816 /* C++ NSString Algorithm Adapters {{{ */
818 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
821 struct NSStringMapHash :
822 std::unary_function<NSString *, size_t>
824 _finline size_t operator ()(NSString *value) const {
825 return CFStringHashNSString((CFStringRef) value);
829 struct NSStringMapLess :
830 std::binary_function<NSString *, NSString *, bool>
832 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
833 return [lhs compare:rhs] == NSOrderedAscending;
837 struct NSStringMapEqual :
838 std::binary_function<NSString *, NSString *, bool>
840 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
841 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
842 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
843 //[lhs isEqualToString:rhs];
848 /* Perl-Compatible RegEx {{{ */
858 Pcre(const char *regex) :
863 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
866 lprintf("%d:%s\n", offset, error);
870 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
871 matches_ = new int[(capture_ + 1) * 3];
879 NSString *operator [](size_t match) {
880 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
883 bool operator ()(NSString *data) {
884 // XXX: length is for characters, not for bytes
885 return operator ()([data UTF8String], [data length]);
888 bool operator ()(const char *data, size_t size) {
890 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
894 /* Mime Addresses {{{ */
895 @interface Address : NSObject {
901 - (NSString *) address;
903 - (void) setAddress:(NSString *)address;
905 + (Address *) addressWithString:(NSString *)string;
906 - (Address *) initWithString:(NSString *)string;
909 @implementation Address
918 - (NSString *) name {
922 - (NSString *) address {
926 - (void) setAddress:(NSString *)address {
928 [address_ autorelease];
932 address_ = [address retain];
935 + (Address *) addressWithString:(NSString *)string {
936 return [[[Address alloc] initWithString:string] autorelease];
939 + (NSArray *) _attributeKeys {
940 return [NSArray arrayWithObjects:@"address", @"name", nil];
943 - (NSArray *) attributeKeys {
944 return [[self class] _attributeKeys];
947 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
948 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
951 - (Address *) initWithString:(NSString *)string {
952 if ((self = [super init]) != nil) {
953 const char *data = [string UTF8String];
954 size_t size = [string length];
956 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
958 if (address_r(data, size)) {
959 name_ = [address_r[1] retain];
960 address_ = [address_r[2] retain];
962 name_ = [string retain];
970 /* CoreGraphics Primitives {{{ */
975 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
976 CGFloat color[] = {red, green, blue, alpha};
977 return CGColorCreate(space, color);
986 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
987 color_(Create_(space, red, green, blue, alpha))
989 Set(space, red, green, blue, alpha);
994 CGColorRelease(color_);
1001 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1003 color_ = Create_(space, red, green, blue, alpha);
1006 operator CGColorRef() {
1012 /* Random Global Variables {{{ */
1013 static const int PulseInterval_ = 50000;
1014 static const int ButtonBarWidth_ = 60;
1015 static const int ButtonBarHeight_ = 48;
1016 static const float KeyboardTime_ = 0.3f;
1019 static NSArray *Finishes_;
1021 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1022 #define NotifyConfig_ "/etc/notify.conf"
1024 static bool Queuing_;
1026 static CYColor Blue_;
1027 static CYColor Blueish_;
1028 static CYColor Black_;
1029 static CYColor Off_;
1030 static CYColor White_;
1031 static CYColor Gray_;
1032 static CYColor Green_;
1033 static CYColor Purple_;
1034 static CYColor Purplish_;
1036 static UIColor *InstallingColor_;
1037 static UIColor *RemovingColor_;
1039 static NSString *App_;
1040 static NSString *Home_;
1042 static BOOL Advanced_;
1043 static BOOL Ignored_;
1045 static UIFont *Font12_;
1046 static UIFont *Font12Bold_;
1047 static UIFont *Font14_;
1048 static UIFont *Font18Bold_;
1049 static UIFont *Font22Bold_;
1051 static const char *Machine_ = NULL;
1052 static NSString *System_ = nil;
1053 static NSString *SerialNumber_ = nil;
1054 static NSString *ChipID_ = nil;
1055 static NSString *Token_ = nil;
1056 static NSString *UniqueID_ = nil;
1057 static NSString *PLMN_ = nil;
1058 static NSString *Build_ = nil;
1059 static NSString *Product_ = nil;
1060 static NSString *Safari_ = nil;
1062 static CFLocaleRef Locale_;
1063 static NSArray *Languages_;
1064 static CGColorSpaceRef space_;
1066 static NSDictionary *SectionMap_;
1067 static NSMutableDictionary *Metadata_;
1068 static _transient NSMutableDictionary *Settings_;
1069 static _transient NSString *Role_;
1070 static _transient NSMutableDictionary *Packages_;
1071 static _transient NSMutableDictionary *Sections_;
1072 static _transient NSMutableDictionary *Sources_;
1073 static bool Changed_;
1076 static bool IsWildcat_;
1079 /* Display Helpers {{{ */
1080 inline float Interpolate(float begin, float end, float fraction) {
1081 return (end - begin) * fraction + begin;
1084 /* XXX: localize this! */
1085 NSString *SizeString(double size) {
1086 bool negative = size < 0;
1091 while (size > 1024) {
1096 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1098 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1101 static _finline const char *StripVersion_(const char *version) {
1102 const char *colon(strchr(version, ':'));
1103 return colon == NULL ? version : colon + 1;
1106 NSString *LocalizeSection(NSString *section) {
1107 static Pcre title_r("^(.*?) \\((.*)\\)$");
1108 if (title_r(section)) {
1109 NSString *parent(title_r[1]);
1110 NSString *child(title_r[2]);
1112 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1113 LocalizeSection(parent),
1114 LocalizeSection(child)
1118 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1121 NSString *Simplify(NSString *title) {
1122 const char *data = [title UTF8String];
1123 size_t size = [title length];
1125 static Pcre square_r("^\\[(.*)\\]$");
1126 if (square_r(data, size))
1127 return Simplify(square_r[1]);
1129 static Pcre paren_r("^\\((.*)\\)$");
1130 if (paren_r(data, size))
1131 return Simplify(paren_r[1]);
1133 static Pcre title_r("^(.*?) \\((.*)\\)$");
1134 if (title_r(data, size))
1135 return Simplify(title_r[1]);
1141 NSString *GetLastUpdate() {
1142 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1145 return UCLocalize("NEVER_OR_UNKNOWN");
1147 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1148 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1150 CFRelease(formatter);
1152 return [(NSString *) formatted autorelease];
1155 bool isSectionVisible(NSString *section) {
1156 NSDictionary *metadata([Sections_ objectForKey:section]);
1157 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1158 return hidden == nil || ![hidden boolValue];
1163 /* Delegate Prototypes {{{ */
1167 @interface NSObject (ProgressDelegate)
1170 @protocol ProgressDelegate
1171 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1172 - (void) setProgressTitle:(NSString *)title;
1173 - (void) setProgressPercent:(float)percent;
1174 - (void) startProgress;
1175 - (void) addProgressOutput:(NSString *)output;
1176 - (bool) isCancelling:(size_t)received;
1179 @protocol ConfigurationDelegate
1180 - (void) repairWithSelector:(SEL)selector;
1181 - (void) setConfigurationData:(NSString *)data;
1184 @class PackageController;
1186 @protocol CydiaDelegate
1187 - (void) setPackageController:(PackageController *)view;
1188 - (void) clearPackage:(Package *)package;
1189 - (void) installPackage:(Package *)package;
1190 - (void) installPackages:(NSArray *)packages;
1191 - (void) removePackage:(Package *)package;
1192 - (void) beginUpdate;
1194 - (void) distUpgrade;
1196 - (void) updateData;
1198 - (void) showSettings;
1199 - (UIProgressHUD *) addProgressHUD;
1200 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1201 - (CYViewController *) pageForPackage:(NSString *)name;
1202 - (PackageController *) packageController;
1203 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1207 /* Status Delegation {{{ */
1209 public pkgAcquireStatus
1212 _transient NSObject<ProgressDelegate> *delegate_;
1220 void setDelegate(id delegate) {
1221 delegate_ = delegate;
1224 NSObject<ProgressDelegate> *getDelegate() const {
1228 virtual bool MediaChange(std::string media, std::string drive) {
1232 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1235 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1236 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1237 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1240 virtual void Done(pkgAcquire::ItemDesc &item) {
1243 virtual void Fail(pkgAcquire::ItemDesc &item) {
1245 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1246 item.Owner->Status == pkgAcquire::Item::StatDone
1250 std::string &error(item.Owner->ErrorText);
1254 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1255 NSArray *fields([description componentsSeparatedByString:@" "]);
1256 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1258 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1259 withObject:[NSArray arrayWithObjects:
1260 [NSString stringWithUTF8String:error.c_str()],
1267 virtual bool Pulse(pkgAcquire *Owner) {
1268 bool value = pkgAcquireStatus::Pulse(Owner);
1271 double(CurrentBytes + CurrentItems) /
1272 double(TotalBytes + TotalItems)
1275 [delegate_ setProgressPercent:percent];
1276 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1279 virtual void Start() {
1280 [delegate_ startProgress];
1283 virtual void Stop() {
1287 /* Progress Delegation {{{ */
1292 _transient id<ProgressDelegate> delegate_;
1296 virtual void Update() {
1297 /*if (abs(Percent - percent_) > 2)
1298 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1302 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1303 [delegate_ setProgressPercent:(Percent / 100)];*/
1313 void setDelegate(id delegate) {
1314 delegate_ = delegate;
1317 id getDelegate() const {
1321 virtual void Done() {
1323 //[delegate_ setProgressPercent:1];
1328 /* Database Interface {{{ */
1329 typedef std::map< unsigned long, _H<Source> > SourceMap;
1331 @interface Database : NSObject {
1337 pkgCacheFile cache_;
1338 pkgDepCache::Policy *policy_;
1339 pkgRecords *records_;
1340 pkgProblemResolver *resolver_;
1341 pkgAcquire *fetcher_;
1343 SPtr<pkgPackageManager> manager_;
1344 pkgSourceList *list_;
1347 CFMutableArrayRef packages_;
1349 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1358 + (Database *) sharedInstance;
1361 - (void) _readCydia:(NSNumber *)fd;
1362 - (void) _readStatus:(NSNumber *)fd;
1363 - (void) _readOutput:(NSNumber *)fd;
1367 - (Package *) packageWithName:(NSString *)name;
1369 - (pkgCacheFile &) cache;
1370 - (pkgDepCache::Policy *) policy;
1371 - (pkgRecords *) records;
1372 - (pkgProblemResolver *) resolver;
1373 - (pkgAcquire &) fetcher;
1374 - (pkgSourceList &) list;
1375 - (NSArray *) packages;
1376 - (NSArray *) sources;
1377 - (void) reloadData;
1385 - (void) updateWithStatus:(Status &)status;
1387 - (void) setDelegate:(id)delegate;
1388 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1391 /* Delegate Helpers {{{ */
1392 @implementation NSObject (ProgressDelegate)
1394 - (void) _setProgressErrorPackage:(NSArray *)args {
1395 [self performSelector:@selector(setProgressError:forPackage:)
1396 withObject:[args objectAtIndex:0]
1397 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1401 - (void) _setProgressErrorTitle:(NSArray *)args {
1402 [self performSelector:@selector(setProgressError:withTitle:)
1403 withObject:[args objectAtIndex:0]
1404 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1408 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1409 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1410 withObject:[NSArray arrayWithObjects:error, title, nil]
1415 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1416 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1418 [self performSelector:@selector(setProgressError:withTitle:)
1420 withObject:(package == nil ? id : [package name])
1427 // Cytore Definitions {{{
1428 struct PackageValue :
1431 Cytore::Offset<PackageValue> next_;
1433 uint32_t index_ : 23;
1434 uint32_t subscribed_ : 1;
1451 Cytore::Offset<PackageValue> packages_[1 << 16];
1454 static Cytore::File<MetaValue> MetaFile_;
1456 // Cytore Helper Functions {{{
1457 static PackageValue *PackageFind(const char *name, size_t length) {
1458 SplitHash nhash = { hashlittle(name, length) };
1460 PackageValue *metadata;
1462 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1463 offset: if (offset->IsNull()) {
1464 *offset = MetaFile_.New<PackageValue>(length + 1);
1465 metadata = &MetaFile_.Get(*offset);
1467 memcpy(metadata->name_, name, length + 1);
1468 metadata->nhash_ = nhash.u16[1];
1470 metadata = &MetaFile_.Get(*offset);
1472 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1473 offset = &metadata->next_;
1481 static void PackageImport(const void *key, const void *value, void *context) {
1483 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1484 NSLog(@"failed to import package %@", key);
1488 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1489 NSDictionary *package((NSDictionary *) value);
1491 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1492 if ([subscribed boolValue])
1493 metadata->subscribed_ = true;
1495 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1496 time_t time([date timeIntervalSince1970]);
1497 if (metadata->first_ > time || metadata->first_ == 0)
1498 metadata->first_ = time;
1501 bool versioned(false);
1503 if (NSDate *date = [package objectForKey:@"LastSeen"]) {
1504 time_t time([date timeIntervalSince1970]);
1505 if (metadata->last_ < time || metadata->last_ == 0) {
1506 metadata->last_ = time;
1509 } else if (metadata->last_ == 0) {
1510 metadata->last_ = metadata->first_;
1511 if (metadata->version_[0] == '\0')
1516 if (NSString *version = [package objectForKey:@"LastVersion"])
1517 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1518 size_t length(strlen(buffer));
1519 uint16_t vhash(hashlittle(buffer, length));
1521 size_t capped(std::min<size_t>(8, length));
1522 char *latest(buffer + length - capped);
1524 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1525 metadata->vhash_ = vhash;
1530 /* Source Class {{{ */
1531 @interface Source : NSObject {
1532 CYString depiction_;
1533 CYString description_;
1539 CYString distribution_;
1544 NSString *authority_;
1546 CYString defaultIcon_;
1548 NSDictionary *record_;
1552 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1554 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1556 - (NSString *) depictionForPackage:(NSString *)package;
1557 - (NSString *) supportForPackage:(NSString *)package;
1559 - (NSDictionary *) record;
1563 - (NSString *) distribution;
1564 - (NSString *) type;
1566 - (NSString *) host;
1568 - (NSString *) name;
1569 - (NSString *) description;
1570 - (NSString *) label;
1571 - (NSString *) origin;
1572 - (NSString *) version;
1574 - (NSString *) defaultIcon;
1578 @implementation Source
1582 distribution_.clear();
1585 description_.clear();
1591 defaultIcon_.clear();
1593 if (record_ != nil) {
1603 if (authority_ != nil) {
1604 [authority_ release];
1610 // XXX: this is a very inefficient way to call these deconstructors
1615 + (NSArray *) _attributeKeys {
1616 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1619 - (NSArray *) attributeKeys {
1620 return [[self class] _attributeKeys];
1623 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1624 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1627 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1630 trusted_ = index->IsTrusted();
1632 uri_.set(pool, index->GetURI());
1633 distribution_.set(pool, index->GetDist());
1634 type_.set(pool, index->GetType());
1636 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1637 if (dindex != NULL) {
1639 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1642 pkgTagFile tags(&fd);
1644 pkgTagSection section;
1651 {"default-icon", &defaultIcon_},
1652 {"depiction", &depiction_},
1653 {"description", &description_},
1655 {"origin", &origin_},
1656 {"support", &support_},
1657 {"version", &version_},
1660 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1661 const char *start, *end;
1663 if (section.Find(names[i].name_, start, end)) {
1664 CYString &value(*names[i].value_);
1665 value.set(pool, start, end - start);
1671 record_ = [Sources_ objectForKey:[self key]];
1673 record_ = [record_ retain];
1675 NSURL *url([NSURL URLWithString:uri_]);
1679 host_ = [[host_ lowercaseString] retain];
1684 authority_ = [url path];
1686 if (authority_ != nil)
1687 authority_ = [authority_ retain];
1690 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1691 if ((self = [super init]) != nil) {
1692 [self setMetaIndex:index inPool:pool];
1696 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1697 NSDictionary *lhr = [self record];
1698 NSDictionary *rhr = [source record];
1701 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1703 NSString *lhs = [self name];
1704 NSString *rhs = [source name];
1706 if ([lhs length] != 0 && [rhs length] != 0) {
1707 unichar lhc = [lhs characterAtIndex:0];
1708 unichar rhc = [rhs characterAtIndex:0];
1710 if (isalpha(lhc) && !isalpha(rhc))
1711 return NSOrderedAscending;
1712 else if (!isalpha(lhc) && isalpha(rhc))
1713 return NSOrderedDescending;
1716 return [lhs compare:rhs options:LaxCompareOptions_];
1719 - (NSString *) depictionForPackage:(NSString *)package {
1720 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1723 - (NSString *) supportForPackage:(NSString *)package {
1724 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1727 - (NSDictionary *) record {
1735 - (NSString *) uri {
1739 - (NSString *) distribution {
1740 return distribution_;
1743 - (NSString *) type {
1747 - (NSString *) key {
1748 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1751 - (NSString *) host {
1755 - (NSString *) name {
1756 return origin_.empty() ? authority_ : origin_;
1759 - (NSString *) description {
1760 return description_;
1763 - (NSString *) label {
1764 return label_.empty() ? authority_ : label_;
1767 - (NSString *) origin {
1771 - (NSString *) version {
1775 - (NSString *) defaultIcon {
1776 return defaultIcon_;
1781 /* Relationship Class {{{ */
1782 @interface Relationship : NSObject {
1787 - (NSString *) type;
1789 - (NSString *) name;
1793 @implementation Relationship
1801 - (NSString *) type {
1809 - (NSString *) name {
1816 /* Package Class {{{ */
1817 struct ParsedPackage {
1822 CYString depiction_;
1832 @interface Package : NSObject {
1834 uint32_t essential_ : 1;
1835 uint32_t obsolete_ : 1;
1836 uint32_t ignored_ : 1;
1840 _transient Database *database_;
1842 pkgCache::VerIterator version_;
1843 pkgCache::PkgIterator iterator_;
1844 pkgCache::VerFileIterator file_;
1850 CYString installed_;
1853 _transient NSString *section$_;
1857 PackageValue *metadata_;
1858 ParsedPackage *parsed_;
1860 NSMutableArray *tags_;
1864 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1865 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1867 - (pkgCache::PkgIterator) iterator;
1870 - (NSString *) section;
1871 - (NSString *) simpleSection;
1873 - (NSString *) longSection;
1874 - (NSString *) shortSection;
1878 - (Address *) maintainer;
1880 - (NSString *) longDescription;
1881 - (NSString *) shortDescription;
1884 - (PackageValue *) metadata;
1887 - (bool) subscribed;
1888 - (bool) setSubscribed:(bool)subscribed;
1892 - (NSString *) latest;
1893 - (NSString *) installed;
1894 - (BOOL) uninstalled;
1897 - (BOOL) upgradableAndEssential:(BOOL)essential;
1900 - (BOOL) unfiltered;
1904 - (BOOL) halfConfigured;
1905 - (BOOL) halfInstalled;
1907 - (NSString *) mode;
1910 - (NSString *) name;
1912 - (NSString *) homepage;
1913 - (NSString *) depiction;
1914 - (Address *) author;
1916 - (NSString *) support;
1918 - (NSArray *) files;
1919 - (NSArray *) warnings;
1920 - (NSArray *) applications;
1922 - (Source *) source;
1923 - (NSString *) role;
1925 - (BOOL) matches:(NSString *)text;
1927 - (bool) hasSupportingRole;
1928 - (BOOL) hasTag:(NSString *)tag;
1929 - (NSString *) primaryPurpose;
1930 - (NSArray *) purposes;
1931 - (bool) isCommercial;
1933 - (void) setIndex:(size_t)index;
1935 - (CYString &) cyname;
1937 - (uint32_t) compareBySection:(NSArray *)sections;
1942 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1943 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1944 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1945 - (bool) isVisibleInSection:(NSString *)section;
1946 - (bool) isVisibleInSource:(Source *)source;
1950 uint32_t PackageChangesRadix(Package *self, void *) {
1955 uint32_t timestamp : 30;
1956 uint32_t ignored : 1;
1957 uint32_t upgradable : 1;
1961 bool upgradable([self upgradableAndEssential:YES]);
1962 value.bits.upgradable = upgradable ? 1 : 0;
1965 value.bits.timestamp = 0;
1966 value.bits.ignored = [self ignored] ? 0 : 1;
1967 value.bits.upgradable = 1;
1969 value.bits.timestamp = [self seen] >> 2;
1970 value.bits.ignored = 0;
1971 value.bits.upgradable = 0;
1974 return _not(uint32_t) - value.key;
1977 uint32_t PackagePrefixRadix(Package *self, void *context) {
1978 size_t offset(reinterpret_cast<size_t>(context));
1979 CYString &name([self cyname]);
1981 size_t size(name.size());
1984 char *text(name.data());
1987 if (!isdigit(text[0]))
1991 while (size != digits && isdigit(text[digits]))
1999 if (offset == 0 && zeros != 0) {
2000 memset(data, '0', zeros);
2001 memcpy(data + zeros, text, 4 - zeros);
2003 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2004 if (size <= offset - zeros)
2007 text += offset - zeros;
2008 size -= offset - zeros;
2011 memcpy(data, text, 4);
2013 memcpy(data, text, size);
2014 memset(data + size, 0, 4 - size);
2017 for (size_t i(0); i != 4; ++i)
2018 if (isalpha(data[i]))
2026 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2028 /* XXX: ntohl may be more honest */
2029 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2032 CYString &(*PackageName)(Package *self, SEL sel);
2034 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2035 _profile(PackageNameCompare)
2036 CYString &lhi(PackageName(lhs, @selector(cyname)));
2037 CYString &rhi(PackageName(rhs, @selector(cyname)));
2038 CFStringRef lhn(lhi), rhn(rhi);
2041 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2042 else if (rhn == NULL)
2043 return NSOrderedDescending;
2045 _profile(PackageNameCompare$NumbersLast)
2046 if (!lhi.empty() && !rhi.empty()) {
2047 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2048 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2049 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2050 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2051 return lha ? NSOrderedAscending : NSOrderedDescending;
2055 CFIndex length = CFStringGetLength(lhn);
2057 _profile(PackageNameCompare$Compare)
2058 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2063 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2064 return PackageNameCompare(*lhs, *rhs, context);
2067 struct PackageNameOrdering :
2068 std::binary_function<Package *, Package *, bool>
2070 _finline bool operator ()(Package *lhs, Package *rhs) const {
2071 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2075 @implementation Package
2077 - (NSString *) description {
2078 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2082 if (parsed_ != NULL)
2096 + (NSString *) webScriptNameForSelector:(SEL)selector {
2097 if (selector == @selector(hasTag:))
2103 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2104 return [self webScriptNameForSelector:selector] == nil;
2107 + (NSArray *) _attributeKeys {
2108 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];
2111 - (NSArray *) attributeKeys {
2112 return [[self class] _attributeKeys];
2115 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2116 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2120 if (parsed_ != NULL)
2122 @synchronized (database_) {
2123 if ([database_ era] != era_ || file_.end())
2126 ParsedPackage *parsed(new ParsedPackage);
2129 _profile(Package$parse)
2130 pkgRecords::Parser *parser;
2132 _profile(Package$parse$Lookup)
2133 parser = &[database_ records]->Lookup(file_);
2138 _profile(Package$parse$Find)
2143 {"icon", &parsed->icon_},
2144 {"depiction", &parsed->depiction_},
2145 {"homepage", &parsed->homepage_},
2146 {"website", &website},
2147 {"bugs", &parsed->bugs_},
2148 {"support", &parsed->support_},
2149 {"sponsor", &parsed->sponsor_},
2150 {"author", &parsed->author_},
2153 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2154 const char *start, *end;
2156 if (parser->Find(names[i].name_, start, end)) {
2157 CYString &value(*names[i].value_);
2158 _profile(Package$parse$Value)
2159 value.set(pool_, start, end - start);
2165 _profile(Package$parse$Tagline)
2166 const char *start, *end;
2167 if (parser->ShortDesc(start, end)) {
2168 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2171 while (stop != start && stop[-1] == '\r')
2173 parsed->tagline_.set(pool_, start, stop - start);
2177 _profile(Package$parse$Retain)
2178 if (parsed->homepage_.empty())
2179 parsed->homepage_ = website;
2180 if (parsed->homepage_ == parsed->depiction_)
2181 parsed->homepage_.clear();
2186 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2187 if ((self = [super init]) != nil) {
2188 _profile(Package$initWithVersion)
2191 database_ = database;
2192 era_ = [database era];
2196 pkgCache::PkgIterator iterator(version.ParentPkg());
2197 iterator_ = iterator;
2199 _profile(Package$initWithVersion$Version)
2200 if (!version_.end())
2201 file_ = version_.FileList();
2203 pkgCache &cache([database_ cache]);
2204 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2208 _profile(Package$initWithVersion$Cache)
2209 name_.set(NULL, iterator.Display());
2211 latest_.set(NULL, StripVersion_(version_.VerStr()));
2213 pkgCache::VerIterator current(iterator.CurrentVer());
2215 installed_.set(NULL, StripVersion_(current.VerStr()));
2218 _profile(Package$initWithVersion$Tags)
2219 pkgCache::TagIterator tag(iterator.TagList());
2221 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2223 const char *name(tag.Name());
2224 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2226 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2227 role_ = (NSString *) CYStringCreate(name + 6);
2229 if (strncmp(name, "cydia::", 7) == 0) {
2230 if (strcmp(name + 7, "essential") == 0)
2232 else if (strcmp(name + 7, "obsolete") == 0)
2237 } while (!tag.end());
2241 _profile(Package$initWithVersion$Metadata)
2242 const char *mixed(iterator.Name());
2243 size_t size(strlen(mixed));
2244 char lower[size + 1];
2246 for (size_t i(0); i != size; ++i)
2247 lower[i] = mixed[i] | 0x20;
2250 PackageValue *metadata(PackageFind(lower, size));
2251 metadata_ = metadata;
2253 id_.set(NULL, metadata->name_, size);
2255 const char *latest(version_.VerStr());
2256 size_t length(strlen(latest));
2258 uint16_t vhash(hashlittle(latest, length));
2260 size_t capped(std::min<size_t>(8, length));
2261 latest = latest + length - capped;
2263 if (metadata->first_ == 0)
2264 metadata->first_ = now_;
2266 if (metadata->last_ == 0)
2267 metadata->last_ = metadata->first_;
2269 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2270 if (metadata->version_[0] != '\0')
2271 metadata->last_ = now_;
2272 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2273 metadata->vhash_ = vhash;
2277 _profile(Package$initWithVersion$Section)
2278 section_.set(NULL, iterator.Section());
2281 _profile(Package$initWithVersion$Flags)
2282 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2283 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2288 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2289 pkgCache::VerIterator version;
2291 _profile(Package$packageWithIterator$GetCandidateVer)
2292 version = [database policy]->GetCandidateVer(iterator);
2300 _profile(Package$packageWithIterator$Allocate)
2301 package = [Package allocWithZone:zone];
2304 _profile(Package$packageWithIterator$Initialize)
2306 initWithVersion:version
2313 _profile(Package$packageWithIterator$Autorelease)
2314 package = [package autorelease];
2320 - (pkgCache::PkgIterator) iterator {
2324 - (NSString *) section {
2325 if (section$_ == nil) {
2326 if (section_.empty())
2329 _profile(Package$section)
2330 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2331 NSString *name(section_);
2332 section$_ = [SectionMap_ objectForKey:name] ?: name;
2337 - (NSString *) simpleSection {
2338 if (NSString *section = [self section])
2339 return Simplify(section);
2344 - (NSString *) longSection {
2345 return LocalizeSection([self section]);
2348 - (NSString *) shortSection {
2349 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2352 - (NSString *) uri {
2355 pkgIndexFile *index;
2356 pkgCache::PkgFileIterator file(file_.File());
2357 if (![database_ list].FindIndex(file, index))
2359 return [NSString stringWithUTF8String:iterator_->Path];
2360 //return [NSString stringWithUTF8String:file.Site()];
2361 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2365 - (Address *) maintainer {
2366 @synchronized (database_) {
2367 if ([database_ era] != era_ || file_.end())
2370 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2371 const std::string &maintainer(parser->Maintainer());
2372 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2376 @synchronized (database_) {
2377 if ([database_ era] != era_ || version_.end())
2380 return version_->InstalledSize;
2383 - (NSString *) longDescription {
2384 @synchronized (database_) {
2385 if ([database_ era] != era_ || file_.end())
2388 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2389 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2391 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2392 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2393 if ([lines count] < 2)
2396 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2397 for (size_t i(1), e([lines count]); i != e; ++i) {
2398 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2399 [trimmed addObject:trim];
2402 return [trimmed componentsJoinedByString:@"\n"];
2405 - (NSString *) shortDescription {
2406 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2410 _profile(Package$index)
2411 CFStringRef name((CFStringRef) [self name]);
2412 if (CFStringGetLength(name) == 0)
2414 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2415 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2417 return toupper(character);
2421 - (PackageValue *) metadata {
2426 PackageValue *metadata([self metadata]);
2427 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2430 - (bool) subscribed {
2431 return [self metadata]->subscribed_;
2434 - (bool) setSubscribed:(bool)subscribed {
2435 PackageValue *metadata([self metadata]);
2436 if (metadata->subscribed_ == subscribed)
2438 metadata->subscribed_ = subscribed;
2446 - (NSString *) latest {
2450 - (NSString *) installed {
2454 - (BOOL) uninstalled {
2455 return installed_.empty();
2459 return !version_.end();
2462 - (BOOL) upgradableAndEssential:(BOOL)essential {
2463 _profile(Package$upgradableAndEssential)
2464 pkgCache::VerIterator current(iterator_.CurrentVer());
2466 return essential && essential_;
2468 return !version_.end() && version_ != current;
2472 - (BOOL) essential {
2477 return [database_ cache][iterator_].InstBroken();
2480 - (BOOL) unfiltered {
2481 _profile(Package$unfiltered$obsolete)
2486 _profile(Package$unfiltered$hasSupportingRole)
2487 if (![self hasSupportingRole])
2495 if (![self unfiltered])
2498 NSString *section([self section]);
2500 _profile(Package$visible$isSectionVisible)
2501 if (section != nil && !isSectionVisible(section))
2509 unsigned char current(iterator_->CurrentState);
2510 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2513 - (BOOL) halfConfigured {
2514 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2517 - (BOOL) halfInstalled {
2518 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2522 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2523 return state.Mode != pkgDepCache::ModeKeep;
2526 - (NSString *) mode {
2527 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2529 switch (state.Mode) {
2530 case pkgDepCache::ModeDelete:
2531 if ((state.iFlags & pkgDepCache::Purge) != 0)
2535 case pkgDepCache::ModeKeep:
2536 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2537 return @"REINSTALL";
2538 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2542 case pkgDepCache::ModeInstall:
2543 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2544 return @"REINSTALL";
2545 else*/ switch (state.Status) {
2547 return @"DOWNGRADE";
2553 return @"NEW_INSTALL";
2564 - (NSString *) name {
2565 return name_.empty() ? id_ : name_;
2568 - (UIImage *) icon {
2569 NSString *section = [self simpleSection];
2572 if (parsed_ != NULL)
2573 if (NSString *href = parsed_->icon_)
2574 if ([href hasPrefix:@"file:///"])
2575 // XXX: correct escaping
2576 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2577 if (icon == nil) if (section != nil)
2578 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2579 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2580 if ([dicon hasPrefix:@"file:///"])
2581 // XXX: correct escaping
2582 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2584 icon = [UIImage applicationImageNamed:@"unknown.png"];
2588 - (NSString *) homepage {
2589 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2592 - (NSString *) depiction {
2593 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2596 - (Address *) sponsor {
2597 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2600 - (Address *) author {
2601 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2604 - (NSString *) support {
2605 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2608 - (NSArray *) files {
2609 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2610 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2613 fin.open([path UTF8String]);
2618 while (std::getline(fin, line))
2619 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2624 - (NSArray *) warnings {
2625 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2626 const char *name(iterator_.Name());
2628 size_t length(strlen(name));
2629 if (length < 2) invalid:
2630 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2631 else for (size_t i(0); i != length; ++i)
2633 /* XXX: technically this is not allowed */
2634 (name[i] < 'A' || name[i] > 'Z') &&
2635 (name[i] < 'a' || name[i] > 'z') &&
2636 (name[i] < '0' || name[i] > '9') &&
2637 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2640 if (strcmp(name, "cydia") != 0) {
2643 bool _private = false;
2646 bool repository = [[self section] isEqualToString:@"Repositories"];
2648 if (NSArray *files = [self files])
2649 for (NSString *file in files)
2650 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2652 else if (!user && [file isEqualToString:@"/User"])
2654 else if (!_private && [file isEqualToString:@"/private"])
2656 else if (!stash && [file isEqualToString:@"/var/stash"])
2659 /* XXX: this is not sensitive enough. only some folders are valid. */
2660 if (cydia && !repository)
2661 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2663 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2665 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2667 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2670 return [warnings count] == 0 ? nil : warnings;
2673 - (NSArray *) applications {
2674 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2676 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2678 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2679 if (NSArray *files = [self files])
2680 for (NSString *file in files)
2681 if (application_r(file)) {
2682 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2683 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2684 if ([id isEqualToString:me])
2687 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2689 display = application_r[1];
2691 NSString *bundle([file stringByDeletingLastPathComponent]);
2692 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2693 if (icon == nil || [icon length] == 0)
2695 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2697 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2698 [applications addObject:application];
2700 [application addObject:id];
2701 [application addObject:display];
2702 [application addObject:url];
2705 return [applications count] == 0 ? nil : applications;
2708 - (Source *) source {
2709 if (source_ == nil) {
2710 @synchronized (database_) {
2711 if ([database_ era] != era_ || file_.end())
2712 source_ = (Source *) [NSNull null];
2714 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2718 return source_ == (Source *) [NSNull null] ? nil : source_;
2721 - (NSString *) role {
2725 - (BOOL) matches:(NSString *)text {
2731 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2732 if (range.location != NSNotFound)
2735 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2736 if (range.location != NSNotFound)
2739 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2740 if (range.location != NSNotFound)
2746 - (bool) hasSupportingRole {
2749 if ([role_ isEqualToString:@"enduser"])
2751 if ([Role_ isEqualToString:@"User"])
2753 if ([role_ isEqualToString:@"hacker"])
2755 if ([Role_ isEqualToString:@"Hacker"])
2757 if ([role_ isEqualToString:@"developer"])
2759 if ([Role_ isEqualToString:@"Developer"])
2764 - (BOOL) hasTag:(NSString *)tag {
2765 return tags_ == nil ? NO : [tags_ containsObject:tag];
2768 - (NSString *) primaryPurpose {
2769 for (NSString *tag in tags_)
2770 if ([tag hasPrefix:@"purpose::"])
2771 return [tag substringFromIndex:9];
2775 - (NSArray *) purposes {
2776 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2777 for (NSString *tag in tags_)
2778 if ([tag hasPrefix:@"purpose::"])
2779 [purposes addObject:[tag substringFromIndex:9]];
2780 return [purposes count] == 0 ? nil : purposes;
2783 - (bool) isCommercial {
2784 return [self hasTag:@"cydia::commercial"];
2787 - (void) setIndex:(size_t)index {
2788 if (metadata_->index_ != index)
2789 metadata_->index_ = index;
2792 - (CYString &) cyname {
2793 return name_.empty() ? id_ : name_;
2796 - (uint32_t) compareBySection:(NSArray *)sections {
2797 NSString *section([self section]);
2798 for (size_t i(0), e([sections count]); i != e; ++i) {
2799 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2803 return _not(uint32_t);
2807 @synchronized (database_) {
2808 pkgProblemResolver *resolver = [database_ resolver];
2809 resolver->Clear(iterator_);
2811 pkgCacheFile &cache([database_ cache]);
2812 cache->SetReInstall(iterator_, false);
2813 cache->MarkKeep(iterator_, false);
2817 @synchronized (database_) {
2818 pkgProblemResolver *resolver = [database_ resolver];
2819 resolver->Clear(iterator_);
2820 resolver->Protect(iterator_);
2822 pkgCacheFile &cache([database_ cache]);
2823 cache->SetReInstall(iterator_, false);
2824 cache->MarkInstall(iterator_, false);
2826 pkgDepCache::StateCache &state((*cache)[iterator_]);
2827 if (!state.Install())
2828 cache->SetReInstall(iterator_, true);
2832 @synchronized (database_) {
2833 pkgProblemResolver *resolver = [database_ resolver];
2834 resolver->Clear(iterator_);
2835 resolver->Remove(iterator_);
2836 resolver->Protect(iterator_);
2838 pkgCacheFile &cache([database_ cache]);
2839 cache->SetReInstall(iterator_, false);
2840 cache->MarkDelete(iterator_, true);
2843 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2844 _profile(Package$isUnfilteredAndSearchedForBy)
2847 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2848 value &= [self unfiltered];
2851 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2852 value &= [self matches:search];
2859 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2860 if ([search length] == 0)
2863 _profile(Package$isUnfilteredAndSelectedForBy)
2866 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2867 value &= [self unfiltered];
2870 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2871 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2878 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2879 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2882 - (bool) isVisibleInSection:(NSString *)name {
2883 NSString *section([self section]);
2887 section == nil && [name length] == 0 ||
2888 [name isEqualToString:section]
2889 ) && [self visible];
2892 - (bool) isVisibleInSource:(Source *)source {
2893 return [self source] == source && [self visible];
2898 /* Section Class {{{ */
2899 @interface Section : NSObject {
2904 NSString *localized_;
2907 - (NSComparisonResult) compareByLocalized:(Section *)section;
2908 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2909 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2910 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2911 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2912 - (NSString *) name;
2919 - (void) addToCount;
2921 - (void) setCount:(size_t)count;
2922 - (NSString *) localized;
2926 @implementation Section
2930 if (localized_ != nil)
2931 [localized_ release];
2935 - (NSComparisonResult) compareByLocalized:(Section *)section {
2936 NSString *lhs(localized_);
2937 NSString *rhs([section localized]);
2939 /*if ([lhs length] != 0 && [rhs length] != 0) {
2940 unichar lhc = [lhs characterAtIndex:0];
2941 unichar rhc = [rhs characterAtIndex:0];
2943 if (isalpha(lhc) && !isalpha(rhc))
2944 return NSOrderedAscending;
2945 else if (!isalpha(lhc) && isalpha(rhc))
2946 return NSOrderedDescending;
2949 return [lhs compare:rhs options:LaxCompareOptions_];
2952 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2953 if ((self = [self initWithName:name localize:NO]) != nil) {
2954 if (localized != nil)
2955 localized_ = [localized retain];
2959 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2960 return [self initWithName:name row:0 localize:localize];
2963 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2964 if ((self = [super init]) != nil) {
2965 name_ = [name retain];
2969 localized_ = [LocalizeSection(name_) retain];
2973 /* XXX: localize the index thingees */
2974 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2975 if ((self = [super init]) != nil) {
2976 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2982 - (NSString *) name {
3002 - (void) addToCount {
3006 - (void) setCount:(size_t)count {
3010 - (NSString *) localized {
3017 static NSString *Colon_;
3018 static NSString *Elision_;
3019 static NSString *Error_;
3020 static NSString *Warning_;
3022 /* Database Implementation {{{ */
3023 @implementation Database
3025 + (Database *) sharedInstance {
3026 static Database *instance;
3027 if (instance == nil)
3028 instance = [[Database alloc] init];
3036 - (void) releasePackages {
3037 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3038 CFArrayRemoveAllValues(packages_);
3042 // XXX: actually implement this thing
3044 [self releasePackages];
3045 apr_pool_destroy(pool_);
3046 NSRecycleZone(zone_);
3050 - (void) _readCydia:(NSNumber *)fd { _pooled
3051 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3052 std::istream is(&ib);
3055 static Pcre finish_r("^finish:([^:]*)$");
3057 while (std::getline(is, line)) {
3058 const char *data(line.c_str());
3059 size_t size = line.size();
3060 lprintf("C:%s\n", data);
3062 if (finish_r(data, size)) {
3063 NSString *finish = finish_r[1];
3064 int index = [Finishes_ indexOfObject:finish];
3065 if (index != INT_MAX && index > Finish_)
3073 - (void) _readStatus:(NSNumber *)fd { _pooled
3074 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3075 std::istream is(&ib);
3078 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3079 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3081 while (std::getline(is, line)) {
3082 const char *data(line.c_str());
3083 size_t size(line.size());
3084 lprintf("S:%s\n", data);
3086 if (conffile_r(data, size)) {
3087 [delegate_ setConfigurationData:conffile_r[1]];
3088 } else if (strncmp(data, "status: ", 8) == 0) {
3089 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3090 [delegate_ setProgressTitle:string];
3091 } else if (pmstatus_r(data, size)) {
3092 std::string type([pmstatus_r[1] UTF8String]);
3093 NSString *id = pmstatus_r[2];
3095 float percent([pmstatus_r[3] floatValue]);
3096 [delegate_ setProgressPercent:(percent / 100)];
3098 NSString *string = pmstatus_r[4];
3100 if (type == "pmerror")
3101 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3102 withObject:[NSArray arrayWithObjects:string, id, nil]
3105 else if (type == "pmstatus") {
3106 [delegate_ setProgressTitle:string];
3107 } else if (type == "pmconffile")
3108 [delegate_ setConfigurationData:string];
3110 lprintf("E:unknown pmstatus\n");
3112 lprintf("E:unknown status\n");
3118 - (void) _readOutput:(NSNumber *)fd { _pooled
3119 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3120 std::istream is(&ib);
3123 while (std::getline(is, line)) {
3124 lprintf("O:%s\n", line.c_str());
3125 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3135 - (Package *) packageWithName:(NSString *)name {
3136 @synchronized (self) {
3137 if (static_cast<pkgDepCache *>(cache_) == NULL)
3139 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3140 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3144 if ((self = [super init]) != nil) {
3151 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3152 apr_pool_create(&pool_, NULL);
3154 size_t capacity(MetaFile_->active_);
3160 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3164 _assert(pipe(fds) != -1);
3167 _config->Set("APT::Keep-Fds::", cydiafd_);
3168 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3171 detachNewThreadSelector:@selector(_readCydia:)
3173 withObject:[NSNumber numberWithInt:fds[0]]
3176 _assert(pipe(fds) != -1);
3180 detachNewThreadSelector:@selector(_readStatus:)
3182 withObject:[NSNumber numberWithInt:fds[0]]
3185 _assert(pipe(fds) != -1);
3186 _assert(dup2(fds[0], 0) != -1);
3187 _assert(close(fds[0]) != -1);
3189 input_ = fdopen(fds[1], "a");
3191 _assert(pipe(fds) != -1);
3192 _assert(dup2(fds[1], 1) != -1);
3193 _assert(close(fds[1]) != -1);
3196 detachNewThreadSelector:@selector(_readOutput:)
3198 withObject:[NSNumber numberWithInt:fds[0]]
3203 - (pkgCacheFile &) cache {
3207 - (pkgDepCache::Policy *) policy {
3211 - (pkgRecords *) records {
3215 - (pkgProblemResolver *) resolver {
3219 - (pkgAcquire &) fetcher {
3223 - (pkgSourceList &) list {
3227 - (NSArray *) packages {
3228 return (NSArray *) packages_;
3231 - (NSArray *) sources {
3232 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3233 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3234 [sources addObject:i->second];
3238 - (NSArray *) issues {
3239 if (cache_->BrokenCount() == 0)
3242 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3244 for (Package *package in [self packages]) {
3245 if (![package broken])
3247 pkgCache::PkgIterator pkg([package iterator]);
3249 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3250 [entry addObject:[package name]];
3251 [issues addObject:entry];
3253 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3257 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3258 pkgCache::DepIterator start;
3259 pkgCache::DepIterator end;
3260 dep.GlobOr(start, end); // ++dep
3262 if (!cache_->IsImportantDep(end))
3264 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3267 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3268 [entry addObject:failure];
3269 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3271 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3272 if (Package *package = [self packageWithName:name])
3273 name = [package name];
3274 [failure addObject:name];
3276 pkgCache::PkgIterator target(start.TargetPkg());
3277 if (target->ProvidesList != 0)
3278 [failure addObject:@"?"];
3280 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3282 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3283 else if (!cache_[target].CandidateVerIter(cache_).end())
3284 [failure addObject:@"-"];
3285 else if (target->ProvidesList == 0)
3286 [failure addObject:@"!"];
3288 [failure addObject:@"%"];
3292 if (start.TargetVer() != 0)
3293 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3304 - (bool) popErrorWithTitle:(NSString *)title {
3306 std::string message;
3308 while (!_error->empty()) {
3310 bool warning(!_error->PopMessage(error));
3314 size_t size(error.size());
3315 if (size == 0 || error[size - 1] != '\n')
3317 error.resize(size - 1);
3319 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3321 if (!message.empty())
3326 if (fatal && !message.empty())
3327 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3332 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3333 return [self popErrorWithTitle:title] || !success;
3336 - (void) reloadData { CYPoolStart() {
3337 @synchronized (self) {
3340 [self releasePackages];
3361 apr_pool_clear(pool_);
3363 NSRecycleZone(zone_);
3364 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3366 int chk(creat("/tmp/cydia.chk", 0644));
3370 NSString *title(UCLocalize("DATABASE"));
3373 if (!cache_.Open(progress_, true)) { pop:
3375 bool warning(!_error->PopMessage(error));
3376 lprintf("cache_.Open():[%s]\n", error.c_str());
3378 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3379 [delegate_ repairWithSelector:@selector(configure)];
3380 else if (error == "The package lists or status file could not be parsed or opened.")
3381 [delegate_ repairWithSelector:@selector(update)];
3382 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3383 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3384 // else if (error == "The list of sources could not be read.")
3386 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3395 unlink("/tmp/cydia.chk");
3397 now_ = [[NSDate date] timeIntervalSince1970];
3399 policy_ = new pkgDepCache::Policy();
3400 records_ = new pkgRecords(cache_);
3401 resolver_ = new pkgProblemResolver(cache_);
3402 fetcher_ = new pkgAcquire(&status_);
3405 list_ = new pkgSourceList();
3406 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3409 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3410 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3414 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3417 if (cache_->BrokenCount() != 0) {
3418 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3421 if (cache_->BrokenCount() != 0) {
3422 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3426 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3430 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3431 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3432 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3433 // XXX: this could be more intelligent
3434 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3435 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3437 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3442 /*std::vector<Package *> packages;
3443 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3444 [packages_ release];
3449 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3450 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3451 //packages.push_back(package);
3452 CFArrayAppendValue(packages_, [package retain]);
3456 /*if (packages.empty())
3457 packages_ = [[NSArray alloc] init];
3459 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3462 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3463 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3464 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3472 /*if (!packages.empty())
3473 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3474 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3476 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3478 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3480 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3484 size_t count(CFArrayGetCount(packages_));
3485 MetaFile_->active_ = count;
3487 for (size_t index(0); index != count; ++index)
3488 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3492 } } CYPoolEnd() _trace(); }
3495 @synchronized (self) {
3497 resolver_ = new pkgProblemResolver(cache_);
3499 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3500 if (!cache_[iterator].Keep()) {
3501 cache_->MarkKeep(iterator, false);
3502 cache_->SetReInstall(iterator, false);
3507 - (void) configure {
3508 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3509 system([dpkg UTF8String]);
3513 // XXX: I don't remember this condition
3518 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3520 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3522 if ([self popErrorWithTitle:title])
3526 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3529 public pkgArchiveCleaner
3532 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3537 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3544 fetcher_->Shutdown();
3546 pkgRecords records(cache_);
3548 lock_ = new FileFd();
3549 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3551 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3553 if ([self popErrorWithTitle:title])
3557 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3560 manager_ = (_system->CreatePM(cache_));
3561 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3568 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3570 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3572 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3574 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3575 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3578 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3583 bool failed = false;
3584 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3585 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3587 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3590 std::string uri = (*item)->DescURI();
3591 std::string error = (*item)->ErrorText;
3593 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3596 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3597 withObject:[NSArray arrayWithObjects:
3598 [NSString stringWithUTF8String:error.c_str()],
3610 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3612 if (_error->PendingError()) {
3617 if (result == pkgPackageManager::Failed) {
3622 if (result != pkgPackageManager::Completed) {
3627 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3629 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3631 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3632 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3635 if (![before isEqualToArray:after])
3640 NSString *title(UCLocalize("UPGRADE"));
3641 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3647 [self updateWithStatus:status_];
3650 - (void) updateWithStatus:(Status &)status {
3651 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3652 NSString *title(UCLocalize("REFRESHING_DATA"));
3655 if (!list.ReadMainList())
3656 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3659 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3660 if ([self popErrorWithTitle:title])
3663 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3664 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3665 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3667 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3671 - (void) setDelegate:(id)delegate {
3672 delegate_ = delegate;
3673 status_.setDelegate(delegate);
3674 progress_.setDelegate(delegate);
3677 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3678 SourceMap::const_iterator i(sources_.find(file->ID));
3679 return i == sources_.end() ? nil : i->second;
3685 /* Confirmation Controller {{{ */
3686 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3687 if (!iterator.end())
3688 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3689 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3691 pkgCache::PkgIterator package(dep.TargetPkg());
3694 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3702 /* Web Scripting {{{ */
3703 @interface CydiaObject : NSObject {
3705 _transient id delegate_;
3708 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3711 @implementation CydiaObject
3714 [indirect_ release];
3718 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3719 if ((self = [super init]) != nil) {
3720 indirect_ = [indirect retain];
3724 - (void) setDelegate:(id)delegate {
3725 delegate_ = delegate;
3728 + (NSArray *) _attributeKeys {
3729 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3732 - (NSArray *) attributeKeys {
3733 return [[self class] _attributeKeys];
3736 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3737 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3740 - (NSString *) device {
3741 return [[UIDevice currentDevice] uniqueIdentifier];
3744 #if 0 // XXX: implement!
3745 - (NSString *) mac {
3746 if (![indirect_ promptForSensitive:@"Mac Address"])
3750 - (NSString *) serial {
3751 if (![indirect_ promptForSensitive:@"Serial #"])
3755 - (NSString *) firewire {
3756 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3760 - (NSString *) imei {
3761 if (![indirect_ promptForSensitive:@"IMEI"])
3766 + (NSString *) webScriptNameForSelector:(SEL)selector {
3767 if (selector == @selector(close))
3769 else if (selector == @selector(getInstalledPackages))
3770 return @"getInstalledPackages";
3771 else if (selector == @selector(getPackageById:))
3772 return @"getPackageById";
3773 else if (selector == @selector(installPackages:))
3774 return @"installPackages";
3775 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3776 return @"setButtonImage";
3777 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3778 return @"setButtonTitle";
3779 else if (selector == @selector(setPopupHook:))
3780 return @"setPopupHook";
3781 else if (selector == @selector(setSpecial:))
3782 return @"setSpecial";
3783 else if (selector == @selector(setToken:))
3785 else if (selector == @selector(setViewportWidth:))
3786 return @"setViewportWidth";
3787 else if (selector == @selector(supports:))
3789 else if (selector == @selector(stringWithFormat:arguments:))
3791 else if (selector == @selector(localizedStringForKey:value:table:))
3793 else if (selector == @selector(du:))
3795 else if (selector == @selector(statfs:))
3801 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3802 return [self webScriptNameForSelector:selector] == nil;
3805 - (BOOL) supports:(NSString *)feature {
3806 return [feature isEqualToString:@"window.open"];
3809 - (NSArray *) getInstalledPackages {
3810 NSArray *packages([[Database sharedInstance] packages]);
3811 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3812 for (Package *package in packages)
3813 if ([package installed] != nil)
3814 [installed addObject:package];
3818 - (Package *) getPackageById:(NSString *)id {
3819 Package *package([[Database sharedInstance] packageWithName:id]);
3824 - (NSArray *) statfs:(NSString *)path {
3827 if (path == nil || statfs([path UTF8String], &stat) == -1)
3830 return [NSArray arrayWithObjects:
3831 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3832 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3833 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3837 - (NSNumber *) du:(NSString *)path {
3838 NSNumber *value(nil);
3841 _assert(pipe(fds) != -1);
3843 pid_t pid(ExecFork());
3845 _assert(dup2(fds[1], 1) != -1);
3846 _assert(close(fds[0]) != -1);
3847 _assert(close(fds[1]) != -1);
3848 /* XXX: this should probably not use du */
3849 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3854 _assert(close(fds[1]) != -1);
3856 if (FILE *du = fdopen(fds[0], "r")) {
3858 while (fgets(line, sizeof(line), du) != NULL) {
3859 size_t length(strlen(line));
3860 while (length != 0 && line[length - 1] == '\n')
3861 line[--length] = '\0';
3862 if (char *tab = strchr(line, '\t')) {
3864 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3869 } else _assert(close(fds[0]));
3873 if (waitpid(pid, &status, 0) == -1)
3876 else _assert(false);
3885 - (void) installPackages:(NSArray *)packages {
3886 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3889 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3890 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3893 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3894 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3897 - (void) setSpecial:(id)function {
3898 [indirect_ setSpecial:function];
3901 - (void) setToken:(NSString *)token {
3904 Token_ = [token retain];
3906 [Metadata_ setObject:Token_ forKey:@"Token"];
3910 - (void) setPopupHook:(id)function {
3911 [indirect_ setPopupHook:function];
3914 - (void) setViewportWidth:(float)width {
3915 [indirect_ setViewportWidth:width];
3918 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3919 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3920 unsigned count([arguments count]);
3922 for (unsigned i(0); i != count; ++i)
3923 values[i] = [arguments objectAtIndex:i];
3924 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3927 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3928 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3930 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3932 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3938 /* Cydia Browser Controller {{{ */
3939 @interface CYBrowserController : BrowserController {
3940 CydiaObject *cydia_;
3945 @implementation CYBrowserController
3952 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3955 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3956 [super webView:view didClearWindowObject:window forFrame:frame];
3958 WebDataSource *source([frame dataSource]);
3959 NSURLResponse *response([source response]);
3960 NSURL *url([response URL]);
3961 NSString *scheme([url scheme]);
3963 NSHTTPURLResponse *http;
3964 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3965 http = (NSHTTPURLResponse *) response;
3969 NSDictionary *headers([http allHeaderFields]);
3970 NSString *host([url host]);
3971 [self setHeaders:headers forHost:host];
3974 [host isEqualToString:@"cydia.saurik.com"] ||
3975 [host hasSuffix:@".cydia.saurik.com"] ||
3976 [scheme isEqualToString:@"file"]
3978 [window setValue:cydia_ forKey:@"cydia"];
3981 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3982 if (System_ != NULL)
3983 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3984 if (Machine_ != NULL)
3985 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3987 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3989 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3992 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3993 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3994 [self _setMoreHeaders:copy];
3998 - (void) setDelegate:(id)delegate {
3999 [super setDelegate:delegate];
4000 [cydia_ setDelegate:delegate];
4004 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4005 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4007 WebView *webview([[webview_ _documentView] webView]);
4009 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4011 NSString *application = package == nil ? @"Cydia" : [NSString
4012 stringWithFormat:@"Cydia/%@",
4017 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4019 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4020 if (Product_ != nil)
4021 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4023 [webview setApplicationNameForUserAgent:application];
4030 /* Confirmation {{{ */
4031 @protocol ConfirmationControllerDelegate
4032 - (void) cancelAndClear:(bool)clear;
4033 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4037 @interface ConfirmationController : CYBrowserController {
4038 _transient Database *database_;
4039 UIAlertView *essential_;
4046 - (id) initWithDatabase:(Database *)database;
4050 @implementation ConfirmationController
4057 if (essential_ != nil)
4058 [essential_ release];
4062 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4063 NSString *context([alert context]);
4065 if ([context isEqualToString:@"remove"]) {
4066 if (button == [alert cancelButtonIndex]) {
4067 [self dismissModalViewControllerAnimated:YES];
4068 } else if (button == [alert firstOtherButtonIndex]) {
4071 [delegate_ confirmWithNavigationController:[self navigationController]];
4074 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4075 } else if ([context isEqualToString:@"unable"]) {
4076 [self dismissModalViewControllerAnimated:YES];
4077 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4079 [super alertView:alert clickedButtonAtIndex:button];
4083 - (void) _doContinue {
4084 [self dismissModalViewControllerAnimated:YES];
4085 [delegate_ cancelAndClear:NO];
4088 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4089 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4093 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4094 [super webView:view didClearWindowObject:window forFrame:frame];
4095 [window setValue:changes_ forKey:@"changes"];
4096 [window setValue:issues_ forKey:@"issues"];
4097 [window setValue:sizes_ forKey:@"sizes"];
4098 [window setValue:self forKey:@"queue"];
4101 - (id) initWithDatabase:(Database *)database {
4102 if ((self = [super init]) != nil) {
4103 database_ = database;
4105 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4107 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4108 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4109 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4110 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4111 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4115 pkgDepCache::Policy *policy([database_ policy]);
4117 pkgCacheFile &cache([database_ cache]);
4118 NSArray *packages = [database_ packages];
4119 for (Package *package in packages) {
4120 pkgCache::PkgIterator iterator = [package iterator];
4121 pkgDepCache::StateCache &state(cache[iterator]);
4123 NSString *name([package name]);
4125 if (state.NewInstall())
4126 [installing addObject:name];
4127 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4128 [reinstalling addObject:name];
4129 else if (state.Upgrade())
4130 [upgrading addObject:name];
4131 else if (state.Downgrade())
4132 [downgrading addObject:name];
4133 else if (state.Delete()) {
4134 if ([package essential])
4136 [removing addObject:name];
4139 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4140 substrate_ |= DepSubstrate(iterator.CurrentVer());
4145 else if (Advanced_) {
4146 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4148 essential_ = [[UIAlertView alloc]
4149 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4150 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4152 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4153 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4156 [essential_ setContext:@"remove"];
4158 essential_ = [[UIAlertView alloc]
4159 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4160 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4162 cancelButtonTitle:UCLocalize("OKAY")
4163 otherButtonTitles:nil
4166 [essential_ setContext:@"unable"];
4169 changes_ = [[NSArray alloc] initWithObjects:
4177 issues_ = [database_ issues];
4179 issues_ = [issues_ retain];
4181 sizes_ = [[NSArray alloc] initWithObjects:
4182 SizeString([database_ fetcher].FetchNeeded()),
4183 SizeString([database_ fetcher].PartialPresent()),
4186 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4188 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4189 initWithTitle:UCLocalize("CANCEL")
4190 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4191 style:UIBarButtonItemStylePlain
4193 action:@selector(cancelButtonClicked)
4198 - (void) applyRightButton {
4199 #if !AlwaysReload && !IgnoreInstall
4200 if (issues_ == nil && ![self isLoading])
4201 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4202 initWithTitle:UCLocalize("CONFIRM")
4203 style:UIBarButtonItemStylePlain
4205 action:@selector(confirmButtonClicked)
4208 [super applyRightButton];
4210 [[self navigationItem] setRightBarButtonItem:nil];
4214 - (void) cancelButtonClicked {
4215 [self dismissModalViewControllerAnimated:YES];
4216 [delegate_ cancelAndClear:YES];
4220 - (void) confirmButtonClicked {
4224 if (essential_ != nil)
4229 [delegate_ confirmWithNavigationController:[self navigationController]];
4237 /* Progress Data {{{ */
4238 @interface ProgressData : NSObject {
4240 // XXX: should these really both be _transient?
4241 _transient id target_;
4242 _transient id object_;
4245 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4252 @implementation ProgressData
4254 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4255 if ((self = [super init]) != nil) {
4256 selector_ = selector;
4276 /* Progress Controller {{{ */
4277 @interface ProgressController : CYViewController <
4278 ConfigurationDelegate,
4281 _transient Database *database_;
4282 UIProgressBar *progress_;
4283 UITextView *output_;
4284 UITextLabel *status_;
4285 UIPushButton *close_;
4287 SHA1SumValue springlist_;
4288 SHA1SumValue notifyconf_;
4292 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4294 - (void) _retachThread;
4295 - (void) _detachNewThreadData:(ProgressData *)data;
4296 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4302 @protocol ProgressControllerDelegate
4303 - (void) progressControllerIsComplete:(ProgressController *)sender;
4306 @implementation ProgressController
4309 [database_ setDelegate:nil];
4310 [progress_ release];
4319 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4320 if ((self = [super init]) != nil) {
4321 database_ = database;
4322 [database_ setDelegate:self];
4323 delegate_ = delegate;
4325 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4327 progress_ = [[UIProgressBar alloc] init];
4328 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4329 [progress_ setStyle:0];
4331 status_ = [[UITextLabel alloc] init];
4332 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4333 [status_ setColor:[UIColor whiteColor]];
4334 [status_ setBackgroundColor:[UIColor clearColor]];
4335 [status_ setCentersHorizontally:YES];
4336 //[status_ setFont:font];
4338 output_ = [[UITextView alloc] init];
4340 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4341 //[output_ setTextFont:@"Courier New"];
4342 [output_ setFont:[[output_ font] fontWithSize:12]];
4343 [output_ setTextColor:[UIColor whiteColor]];
4344 [output_ setBackgroundColor:[UIColor clearColor]];
4345 [output_ setMarginTop:0];
4346 [output_ setAllowsRubberBanding:YES];
4347 [output_ setEditable:NO];
4348 [[self view] addSubview:output_];
4350 close_ = [[UIPushButton alloc] init];
4351 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4352 [close_ setAutosizesToFit:NO];
4353 [close_ setDrawsShadow:YES];
4354 [close_ setStretchBackground:YES];
4355 [close_ setEnabled:YES];
4356 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4357 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4358 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4359 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4363 - (void) positionViews {
4364 CGRect bounds = [[self view] bounds];
4365 CGSize prgsize = [UIProgressBar defaultSize];
4368 (bounds.size.width - prgsize.width) / 2,
4369 bounds.size.height - prgsize.height - 20
4372 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4374 [progress_ setFrame:prgrect];
4375 [status_ setFrame:CGRectMake(
4377 bounds.size.height - prgsize.height - 50,
4378 bounds.size.width - 20,
4381 [output_ setFrame:CGRectMake(
4384 bounds.size.width - 20,
4385 bounds.size.height - 62
4387 [close_ setFrame:CGRectMake(
4388 (bounds.size.width - closewidth) / 2,
4389 bounds.size.height - prgsize.height - 50,
4395 - (void) viewWillAppear:(BOOL)animated {
4396 [super viewDidAppear:animated];
4397 [[self navigationItem] setHidesBackButton:YES];
4398 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4400 [self positionViews];
4403 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4404 [self positionViews];
4407 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4408 NSString *context([alert context]);
4410 if ([context isEqualToString:@"conffile"]) {
4411 FILE *input = [database_ input];
4412 if (button == [alert cancelButtonIndex])
4413 fprintf(input, "N\n");
4414 else if (button == [alert firstOtherButtonIndex])
4415 fprintf(input, "Y\n");
4420 - (void) closeButtonPushed {
4423 UpdateExternalStatus(0);
4427 [self dismissModalViewControllerAnimated:YES];
4431 [delegate_ terminateWithSuccess];
4432 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4433 [delegate_ suspendWithAnimation:YES];
4435 [delegate_ suspend];*/
4439 system("launchctl stop com.apple.SpringBoard");
4443 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4452 - (void) _retachThread {
4453 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4455 [[self view] addSubview:close_];
4456 [progress_ removeFromSuperview];
4457 [status_ removeFromSuperview];
4459 [database_ popErrorWithTitle:title_];
4460 [delegate_ progressControllerIsComplete:self];
4464 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4467 MMap mmap(file, MMap::ReadOnly);
4469 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4470 if (!(notifyconf_ == sha1.Result()))
4477 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4480 MMap mmap(file, MMap::ReadOnly);
4482 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4483 if (!(springlist_ == sha1.Result()))
4489 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4490 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4491 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4492 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4493 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4496 system("su -c /usr/bin/uicache mobile");
4498 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4500 [delegate_ setStatusBarShowsProgress:NO];
4503 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4504 [[data target] performSelector:[data selector] withObject:[data object]];
4505 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4508 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4509 UpdateExternalStatus(1);
4516 title_ = [title retain];
4518 [[self navigationItem] setTitle:title_];
4520 [status_ setText:nil];
4521 [output_ setText:@""];
4522 [progress_ setProgress:0];
4524 [close_ removeFromSuperview];
4525 [[self view] addSubview:progress_];
4526 [[self view] addSubview:status_];
4528 [delegate_ setStatusBarShowsProgress:YES];
4533 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4536 MMap mmap(file, MMap::ReadOnly);
4538 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4539 notifyconf_ = sha1.Result();
4545 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4548 MMap mmap(file, MMap::ReadOnly);
4550 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4551 springlist_ = sha1.Result();
4556 detachNewThreadSelector:@selector(_detachNewThreadData:)
4558 withObject:[[[ProgressData alloc]
4559 initWithSelector:selector
4566 - (void) repairWithSelector:(SEL)selector {
4568 detachNewThreadSelector:selector
4571 title:UCLocalize("REPAIRING")
4575 - (void) setConfigurationData:(NSString *)data {
4577 performSelectorOnMainThread:@selector(_setConfigurationData:)
4583 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4584 CYActionSheet *sheet([[[CYActionSheet alloc]
4586 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4587 defaultButtonIndex:0
4590 [sheet setMessage:error];
4591 [sheet yieldToPopupAlertAnimated:YES];
4595 - (void) setProgressTitle:(NSString *)title {
4597 performSelectorOnMainThread:@selector(_setProgressTitle:)
4603 - (void) setProgressPercent:(float)percent {
4605 performSelectorOnMainThread:@selector(_setProgressPercent:)
4606 withObject:[NSNumber numberWithFloat:percent]
4611 - (void) startProgress {
4614 - (void) addProgressOutput:(NSString *)output {
4616 performSelectorOnMainThread:@selector(_addProgressOutput:)
4622 - (bool) isCancelling:(size_t)received {
4626 - (void) _setConfigurationData:(NSString *)data {
4627 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4629 if (!conffile_r(data)) {
4630 lprintf("E:invalid conffile\n");
4634 NSString *ofile = conffile_r[1];
4635 //NSString *nfile = conffile_r[2];
4637 UIAlertView *alert = [[[UIAlertView alloc]
4638 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4639 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4641 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4642 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4643 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4647 [alert setContext:@"conffile"];
4651 - (void) _setProgressTitle:(NSString *)title {
4652 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4653 for (size_t i(0), e([words count]); i != e; ++i) {
4654 NSString *word([words objectAtIndex:i]);
4655 if (Package *package = [database_ packageWithName:word])
4656 [words replaceObjectAtIndex:i withObject:[package name]];
4659 [status_ setText:[words componentsJoinedByString:@" "]];
4662 - (void) _setProgressPercent:(NSNumber *)percent {
4663 [progress_ setProgress:[percent floatValue]];
4666 - (void) _addProgressOutput:(NSString *)output {
4667 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4668 CGSize size = [output_ contentSize];
4669 CGRect rect = {{0, size.height}, {size.width, 0}};
4670 [output_ scrollRectToVisible:rect animated:YES];
4673 - (BOOL) isRunning {
4680 /* Cell Content View {{{ */
4681 @protocol ContentDelegate
4682 - (void) drawContentRect:(CGRect)rect;
4685 @interface ContentView : UIView {
4686 _transient id<ContentDelegate> delegate_;
4691 @implementation ContentView
4693 - (id) initWithFrame:(CGRect)frame {
4694 if ((self = [super initWithFrame:frame]) != nil) {
4695 [self setNeedsDisplayOnBoundsChange:YES];
4699 - (void) setDelegate:(id<ContentDelegate>)delegate {
4700 delegate_ = delegate;
4703 - (void) drawRect:(CGRect)rect {
4704 [super drawRect:rect];
4705 [delegate_ drawContentRect:rect];
4710 /* Cydia TableView Cell {{{ */
4711 @interface CYTableViewCell : UITableViewCell {
4712 ContentView *content_;
4718 @implementation CYTableViewCell
4725 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4726 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4728 if (view == content_) {
4729 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4730 highlighted_ = highlighted;
4733 [super _updateHighlightColorsForView:view highlighted:highlighted];
4736 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4737 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4738 highlighted_ = selected;
4740 [super setSelected:selected animated:animated];
4741 [content_ setNeedsDisplay];
4746 /* Package Cell {{{ */
4747 @interface PackageCell : CYTableViewCell <
4752 NSString *description_;
4760 - (PackageCell *) init;
4761 - (void) setPackage:(Package *)package;
4763 + (int) heightForPackage:(Package *)package;
4764 - (void) drawContentRect:(CGRect)rect;
4768 @implementation PackageCell
4770 - (void) clearPackage {
4781 if (description_ != nil) {
4782 [description_ release];
4786 if (source_ != nil) {
4791 if (badge_ != nil) {
4796 if (placard_ != nil) {
4806 [self clearPackage];
4810 - (PackageCell *) init {
4811 CGRect frame(CGRectMake(0, 0, 320, 74));
4812 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4813 UIView *content([self contentView]);
4814 CGRect bounds([content bounds]);
4816 content_ = [[ContentView alloc] initWithFrame:bounds];
4817 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4818 [content addSubview:content_];
4820 [content_ setDelegate:self];
4821 [content_ setOpaque:YES];
4825 - (void) _setBackgroundColor {
4827 if (NSString *mode = [package_ mode]) {
4828 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4829 color = remove ? RemovingColor_ : InstallingColor_;
4831 color = [UIColor whiteColor];
4833 [content_ setBackgroundColor:color];
4834 [self setNeedsDisplay];
4837 - (void) setPackage:(Package *)package {
4838 [self clearPackage];
4841 Source *source = [package source];
4843 icon_ = [[package icon] retain];
4844 name_ = [[package name] retain];
4847 description_ = [package longDescription];
4848 if (description_ == nil)
4849 description_ = [package shortDescription];
4850 if (description_ != nil)
4851 description_ = [description_ retain];
4853 commercial_ = [package isCommercial];
4855 package_ = [package retain];
4857 NSString *label = nil;
4858 bool trusted = false;
4860 if (source != nil) {
4861 label = [source label];
4862 trusted = [source trusted];
4863 } else if ([[package id] isEqualToString:@"firmware"])
4864 label = UCLocalize("APPLE");
4866 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4868 NSString *from(label);
4870 NSString *section = [package simpleSection];
4871 if (section != nil && ![section isEqualToString:label]) {
4872 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4873 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4876 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4877 source_ = [from retain];
4879 if (NSString *purpose = [package primaryPurpose])
4880 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4881 badge_ = [badge_ retain];
4883 if ([package installed] != nil)
4884 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4885 placard_ = [placard_ retain];
4887 [self _setBackgroundColor];
4888 [content_ setNeedsDisplay];
4891 - (void) drawContentRect:(CGRect)rect {
4892 bool highlighted(highlighted_);
4893 float width([self bounds].size.width);
4896 CGContextRef context(UIGraphicsGetCurrentContext());
4897 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4898 CGContextFillRect(context, rect);
4903 rect.size = [icon_ size];
4905 rect.size.width /= 2;
4906 rect.size.height /= 2;
4908 rect.origin.x = 25 - rect.size.width / 2;
4909 rect.origin.y = 25 - rect.size.height / 2;
4911 [icon_ drawInRect:rect];
4914 if (badge_ != nil) {
4916 rect.size = [badge_ size];
4918 rect.size.width /= 2;
4919 rect.size.height /= 2;
4921 rect.origin.x = 36 - rect.size.width / 2;
4922 rect.origin.y = 36 - rect.size.height / 2;
4924 [badge_ drawInRect:rect];
4931 UISetColor(commercial_ ? Purple_ : Black_);
4932 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4933 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4936 UISetColor(commercial_ ? Purplish_ : Gray_);
4937 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4939 if (placard_ != nil)
4940 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4943 + (int) heightForPackage:(Package *)package {
4949 /* Section Cell {{{ */
4950 @interface SectionCell : CYTableViewCell <
4962 - (void) setSection:(Section *)section editing:(BOOL)editing;
4966 @implementation SectionCell
4968 - (void) clearSection {
4969 if (basic_ != nil) {
4974 if (section_ != nil) {
4984 if (count_ != nil) {
4991 [self clearSection];
4997 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4998 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4999 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5000 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5001 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5003 UIView *content([self contentView]);
5004 CGRect bounds([content bounds]);
5006 content_ = [[ContentView alloc] initWithFrame:bounds];
5007 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5008 [content addSubview:content_];
5009 [content_ setBackgroundColor:[UIColor whiteColor]];
5011 [content_ setDelegate:self];
5015 - (void) onSwitch:(id)sender {
5016 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5017 if (metadata == nil) {
5018 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5019 [Sections_ setObject:metadata forKey:basic_];
5022 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5026 - (void) setSection:(Section *)section editing:(BOOL)editing {
5027 if (editing != editing_) {
5029 [switch_ removeFromSuperview];
5031 [self addSubview:switch_];
5035 [self clearSection];
5037 if (section == nil) {
5038 name_ = [UCLocalize("ALL_PACKAGES") retain];
5041 basic_ = [section name];
5043 basic_ = [basic_ retain];
5045 section_ = [section localized];
5046 if (section_ != nil)
5047 section_ = [section_ retain];
5049 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5050 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5053 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5056 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5057 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5059 [content_ setNeedsDisplay];
5062 - (void) setFrame:(CGRect)frame {
5063 [super setFrame:frame];
5065 CGRect rect([switch_ frame]);
5066 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5069 - (void) drawContentRect:(CGRect)rect {
5070 bool highlighted(highlighted_);
5072 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5077 float width(rect.size.width);
5083 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5085 CGSize size = [count_ sizeWithFont:Font14_];
5089 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5095 /* File Table {{{ */
5096 @interface FileTable : CYViewController <
5097 UITableViewDataSource,
5100 _transient Database *database_;
5103 NSMutableArray *files_;
5107 - (id) initWithDatabase:(Database *)database;
5108 - (void) setPackage:(Package *)package;
5112 @implementation FileTable
5115 if (package_ != nil)
5124 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5125 return files_ == nil ? 0 : [files_ count];
5128 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5132 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5133 static NSString *reuseIdentifier = @"Cell";
5135 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5137 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5138 [cell setFont:[UIFont systemFontOfSize:16]];
5140 [cell setText:[files_ objectAtIndex:indexPath.row]];
5141 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5146 - (id) initWithDatabase:(Database *)database {
5147 if ((self = [super init]) != nil) {
5148 database_ = database;
5150 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5152 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5154 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5155 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5156 [list_ setRowHeight:24.0f];
5157 [[self view] addSubview:list_];
5159 [list_ setDataSource:self];
5160 [list_ setDelegate:self];
5164 - (void) setPackage:(Package *)package {
5165 if (package_ != nil) {
5166 [package_ autorelease];
5175 [files_ removeAllObjects];
5177 if (package != nil) {
5178 package_ = [package retain];
5179 name_ = [[package id] retain];
5181 if (NSArray *files = [package files])
5182 [files_ addObjectsFromArray:files];
5184 if ([files_ count] != 0) {
5185 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5186 [files_ removeObjectAtIndex:0];
5187 [files_ sortUsingSelector:@selector(compareByPath:)];
5189 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5190 [stack addObject:@"/"];
5192 for (int i(0), e([files_ count]); i != e; ++i) {
5193 NSString *file = [files_ objectAtIndex:i];
5194 while (![file hasPrefix:[stack lastObject]])
5195 [stack removeLastObject];
5196 NSString *directory = [stack lastObject];
5197 [stack addObject:[file stringByAppendingString:@"/"]];
5198 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5199 ([stack count] - 2) * 3, "",
5200 [file substringFromIndex:[directory length]]
5209 - (void) reloadData {
5210 [self setPackage:[database_ packageWithName:name_]];
5215 /* Package Controller {{{ */
5216 @interface PackageController : CYBrowserController <
5217 UIActionSheetDelegate
5219 _transient Database *database_;
5223 NSMutableArray *buttons_;
5224 UIBarButtonItem *button_;
5227 - (id) initWithDatabase:(Database *)database;
5228 - (void) setPackage:(Package *)package;
5232 @implementation PackageController
5235 if (package_ != nil)
5249 if ([self retainCount] == 1)
5250 [delegate_ setPackageController:self];
5254 /* XXX: this is not safe at all... localization of /fail/ */
5255 - (void) _clickButtonWithName:(NSString *)name {
5256 if ([name isEqualToString:UCLocalize("CLEAR")])
5257 [delegate_ clearPackage:package_];
5258 else if ([name isEqualToString:UCLocalize("INSTALL")])
5259 [delegate_ installPackage:package_];
5260 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5261 [delegate_ installPackage:package_];
5262 else if ([name isEqualToString:UCLocalize("REMOVE")])
5263 [delegate_ removePackage:package_];
5264 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5265 [delegate_ installPackage:package_];
5266 else _assert(false);
5269 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5270 NSString *context([sheet context]);
5272 if ([context isEqualToString:@"modify"]) {
5273 if (button != [sheet cancelButtonIndex]) {
5274 NSString *buttonName = [buttons_ objectAtIndex:button];
5275 [self _clickButtonWithName:buttonName];
5278 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5282 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5283 [super webView:view didClearWindowObject:window forFrame:frame];
5284 [window setValue:package_ forKey:@"package"];
5287 - (bool) _allowJavaScriptPanel {
5292 - (void) _customButtonClicked {
5293 int count([buttons_ count]);
5298 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5300 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5301 [buttons addObjectsFromArray:buttons_];
5303 UIActionSheet *sheet = [[[UIActionSheet alloc]
5306 cancelButtonTitle:nil
5307 destructiveButtonTitle:nil
5308 otherButtonTitles:nil
5311 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5313 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5314 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5316 [sheet setContext:@"modify"];
5318 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5322 // We don't want to allow non-commercial packages to do custom things to the install button,
5323 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5324 - (void) customButtonClicked {
5326 [super customButtonClicked];
5328 [self _customButtonClicked];
5331 - (void) reloadButtonClicked {
5332 // Don't reload a package view by clicking the button.
5335 - (void) applyLoadingTitle {
5336 // Don't show "Loading" as the title. Ever.
5339 - (UIBarButtonItem *) rightButton {
5344 - (id) initWithDatabase:(Database *)database {
5345 if ((self = [super init]) != nil) {
5346 database_ = database;
5347 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5348 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5352 - (void) setPackage:(Package *)package {
5353 if (package_ != nil) {
5354 [package_ autorelease];
5363 [buttons_ removeAllObjects];
5365 if (package != nil) {
5368 package_ = [package retain];
5369 name_ = [[package id] retain];
5370 commercial_ = [package isCommercial];
5372 if ([package_ mode] != nil)
5373 [buttons_ addObject:UCLocalize("CLEAR")];
5374 if ([package_ source] == nil);
5375 else if ([package_ upgradableAndEssential:NO])
5376 [buttons_ addObject:UCLocalize("UPGRADE")];
5377 else if ([package_ uninstalled])
5378 [buttons_ addObject:UCLocalize("INSTALL")];
5380 [buttons_ addObject:UCLocalize("REINSTALL")];
5381 if (![package_ uninstalled])
5382 [buttons_ addObject:UCLocalize("REMOVE")];
5389 switch ([buttons_ count]) {
5390 case 0: title = nil; break;
5391 case 1: title = [buttons_ objectAtIndex:0]; break;
5392 default: title = UCLocalize("MODIFY"); break;
5395 button_ = [[UIBarButtonItem alloc]
5397 style:UIBarButtonItemStylePlain
5399 action:@selector(customButtonClicked)
5405 - (bool) isLoading {
5406 return commercial_ ? [super isLoading] : false;
5409 - (void) reloadData {
5410 [self setPackage:[database_ packageWithName:name_]];
5415 /* Package Table {{{ */
5416 @interface PackageTable : UIView <
5417 UITableViewDataSource,
5420 _transient Database *database_;
5422 NSMutableArray *packages_;
5423 NSMutableArray *sections_;
5425 NSMutableArray *index_;
5426 NSMutableDictionary *indices_;
5427 // XXX: this target_ seems to be delegate_. :(
5428 _transient id target_;
5430 // XXX: why do we even have this delegate_?
5431 _transient id delegate_;
5434 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5436 - (void) setDelegate:(id)delegate;
5438 - (void) reloadData;
5439 - (void) resetCursor;
5441 - (UITableView *) list;
5443 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5445 - (void) deselectWithAnimation:(BOOL)animated;
5449 @implementation PackageTable
5452 [packages_ release];
5453 [sections_ release];
5461 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5462 NSInteger count([sections_ count]);
5463 return count == 0 ? 1 : count;
5466 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5467 if ([sections_ count] == 0)
5469 return [[sections_ objectAtIndex:section] name];
5472 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5473 if ([sections_ count] == 0)
5475 return [[sections_ objectAtIndex:section] count];
5478 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5479 @synchronized (database_) {
5480 if ([database_ era] != era_)
5483 Section *section([sections_ objectAtIndex:[path section]]);
5484 NSInteger row([path row]);
5485 Package *package([packages_ objectAtIndex:([section row] + row)]);
5486 return [[package retain] autorelease];
5489 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5490 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5492 cell = [[[PackageCell alloc] init] autorelease];
5493 [cell setPackage:[self packageAtIndexPath:path]];
5497 - (void) deselectWithAnimation:(BOOL)animated {
5498 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5501 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5502 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5505 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5506 Package *package([self packageAtIndexPath:path]);
5507 package = [database_ packageWithName:[package id]];
5508 [target_ performSelector:action_ withObject:package];
5512 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5513 return [packages_ count] > 20 ? index_ : nil;
5516 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5520 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5521 if ((self = [super initWithFrame:frame]) != nil) {
5522 database_ = database;
5527 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5528 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5530 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5531 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5533 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5534 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5535 [list_ setRowHeight:73.0f];
5536 [self addSubview:list_];
5538 [list_ setDataSource:self];
5539 [list_ setDelegate:self];
5543 - (void) setDelegate:(id)delegate {
5544 delegate_ = delegate;
5547 - (bool) hasPackage:(Package *)package {
5551 - (void) reloadData {
5552 era_ = [database_ era];
5553 NSArray *packages = [database_ packages];
5555 [packages_ removeAllObjects];
5556 [sections_ removeAllObjects];
5558 _profile(PackageTable$reloadData$Filter)
5559 for (Package *package in packages)
5560 if ([self hasPackage:package])
5561 [packages_ addObject:package];
5564 [index_ removeAllObjects];
5565 [indices_ removeAllObjects];
5567 Section *section = nil;
5569 _profile(PackageTable$reloadData$Section)
5570 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5574 _profile(PackageTable$reloadData$Section$Package)
5575 package = [packages_ objectAtIndex:offset];
5576 index = [package index];
5579 if (section == nil || [section index] != index) {
5580 _profile(PackageTable$reloadData$Section$Allocate)
5581 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5584 [index_ addObject:[section name]];
5585 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5587 _profile(PackageTable$reloadData$Section$Add)
5588 [sections_ addObject:section];
5592 [section addToCount];
5596 _profile(PackageTable$reloadData$List)
5601 - (void) resetCursor {
5602 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5605 - (UITableView *) list {
5609 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5610 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5615 /* Filtered Package Table {{{ */
5616 @interface FilteredPackageTable : PackageTable {
5622 - (void) setObject:(id)object;
5623 - (void) setObject:(id)object forFilter:(SEL)filter;
5625 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5629 @implementation FilteredPackageTable
5637 - (void) setFilter:(SEL)filter {
5640 /* XXX: this is an unsafe optimization of doomy hell */
5641 Method method(class_getInstanceMethod([Package class], filter));
5642 _assert(method != NULL);
5643 imp_ = method_getImplementation(method);
5644 _assert(imp_ != NULL);
5647 - (void) setObject:(id)object {
5653 object_ = [object retain];
5656 - (void) setObject:(id)object forFilter:(SEL)filter {
5657 [self setFilter:filter];
5658 [self setObject:object];
5661 - (bool) hasPackage:(Package *)package {
5662 _profile(FilteredPackageTable$hasPackage)
5663 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5667 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5668 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5669 [self setFilter:filter];
5670 object_ = [object retain];
5678 /* Filtered Package Controller {{{ */
5679 @interface FilteredPackageController : CYViewController {
5680 _transient Database *database_;
5681 FilteredPackageTable *packages_;
5685 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5689 @implementation FilteredPackageController
5692 [packages_ release];
5698 - (void) viewDidAppear:(BOOL)animated {
5699 [super viewDidAppear:animated];
5700 [packages_ deselectWithAnimation:animated];
5703 - (void) didSelectPackage:(Package *)package {
5704 PackageController *view([delegate_ packageController]);
5705 [view setPackage:package];
5706 [view setDelegate:delegate_];
5707 [[self navigationController] pushViewController:view animated:YES];
5710 - (NSString *) title { return title_; }
5712 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5713 if ((self = [super init]) != nil) {
5714 database_ = database;
5715 title_ = [title copy];
5716 [[self navigationItem] setTitle:title_];
5718 packages_ = [[FilteredPackageTable alloc]
5719 initWithFrame:[[self view] bounds]
5722 action:@selector(didSelectPackage:)
5727 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5728 [[self view] addSubview:packages_];
5732 - (void) reloadData {
5733 [packages_ reloadData];
5736 - (void) setDelegate:(id)delegate {
5737 [super setDelegate:delegate];
5738 [packages_ setDelegate:delegate];
5745 /* Add Source Controller {{{ */
5746 @interface AddSourceController : CYViewController {
5747 _transient Database *database_;
5750 - (id) initWithDatabase:(Database *)database;
5754 @implementation AddSourceController
5756 - (id) initWithDatabase:(Database *)database {
5757 if ((self = [super init]) != nil) {
5758 database_ = database;
5764 /* Source Cell {{{ */
5765 @interface SourceCell : CYTableViewCell <
5770 NSString *description_;
5774 - (void) setSource:(Source *)source;
5778 @implementation SourceCell
5780 - (void) clearSource {
5783 [description_ release];
5792 - (void) setSource:(Source *)source {
5796 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5798 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5799 icon_ = [icon_ retain];
5801 origin_ = [[source name] retain];
5802 label_ = [[source uri] retain];
5803 description_ = [[source description] retain];
5805 [content_ setNeedsDisplay];
5813 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5814 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5815 UIView *content([self contentView]);
5816 CGRect bounds([content bounds]);
5818 content_ = [[ContentView alloc] initWithFrame:bounds];
5819 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5820 [content_ setBackgroundColor:[UIColor whiteColor]];
5821 [content addSubview:content_];
5823 [content_ setDelegate:self];
5824 [content_ setOpaque:YES];
5828 - (void) drawContentRect:(CGRect)rect {
5829 bool highlighted(highlighted_);
5830 float width(rect.size.width);
5833 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5840 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5844 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5848 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5853 /* Source Table {{{ */
5854 @interface SourceTable : CYViewController <
5855 UITableViewDataSource,
5858 _transient Database *database_;
5860 NSMutableArray *sources_;
5864 UIProgressHUD *hud_;
5867 //NSURLConnection *installer_;
5868 NSURLConnection *trivial_;
5869 NSURLConnection *trivial_bz2_;
5870 NSURLConnection *trivial_gz_;
5871 //NSURLConnection *automatic_;
5876 - (id) initWithDatabase:(Database *)database;
5878 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5882 @implementation SourceTable
5884 - (void) _releaseConnection:(NSURLConnection *)connection {
5885 if (connection != nil) {
5886 [connection cancel];
5887 //[connection setDelegate:nil];
5888 [connection release];
5900 //[self _releaseConnection:installer_];
5901 [self _releaseConnection:trivial_];
5902 [self _releaseConnection:trivial_gz_];
5903 [self _releaseConnection:trivial_bz2_];
5904 //[self _releaseConnection:automatic_];
5911 - (void) viewDidAppear:(BOOL)animated {
5912 [super viewDidAppear:animated];
5913 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5916 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5917 return offset_ == 0 ? 1 : 2;
5920 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5921 switch (section + (offset_ == 0 ? 1 : 0)) {
5922 case 0: return UCLocalize("ENTERED_BY_USER");
5923 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5929 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5930 int count = [sources_ count];
5932 case 0: return (offset_ == 0 ? count : offset_);
5933 case 1: return count - offset_;
5939 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5941 switch (indexPath.section) {
5942 case 0: idx = indexPath.row; break;
5943 case 1: idx = indexPath.row + offset_; break;
5947 return [sources_ objectAtIndex:idx];
5950 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5951 Source *source = [self sourceAtIndexPath:indexPath];
5952 return [source description] == nil ? 56 : 73;
5955 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5956 static NSString *cellIdentifier = @"SourceCell";
5958 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5959 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5960 [cell setSource:[self sourceAtIndexPath:indexPath]];
5965 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5966 return UITableViewCellAccessoryDisclosureIndicator;
5969 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5970 Source *source = [self sourceAtIndexPath:indexPath];
5972 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5973 initWithDatabase:database_
5974 title:[source label]
5975 filter:@selector(isVisibleInSource:)
5979 [packages setDelegate:delegate_];
5981 [[self navigationController] pushViewController:packages animated:YES];
5984 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5985 Source *source = [self sourceAtIndexPath:indexPath];
5986 return [source record] != nil;
5989 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5990 Source *source = [self sourceAtIndexPath:indexPath];
5991 [Sources_ removeObjectForKey:[source key]];
5992 [delegate_ syncData];
5996 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5999 @"./", @"Distribution",
6000 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
6002 [delegate_ syncData];
6005 - (NSString *) getWarning {
6006 NSString *href(href_);
6007 NSRange colon([href rangeOfString:@"://"]);
6008 if (colon.location != NSNotFound)
6009 href = [href substringFromIndex:(colon.location + 3)];
6010 href = [href stringByAddingPercentEscapes];
6011 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
6012 href = [href stringByCachingURLWithCurrentCDN];
6014 NSURL *url([NSURL URLWithString:href]);
6016 NSStringEncoding encoding;
6017 NSError *error(nil);
6019 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
6020 return [warning length] == 0 ? nil : warning;
6024 - (void) _endConnection:(NSURLConnection *)connection {
6025 // XXX: the memory management in this method is horribly awkward
6027 NSURLConnection **field = NULL;
6028 if (connection == trivial_)
6030 else if (connection == trivial_bz2_)
6031 field = &trivial_bz2_;
6032 else if (connection == trivial_gz_)
6033 field = &trivial_gz_;
6034 _assert(field != NULL);
6035 [connection release];
6040 trivial_bz2_ == nil &&
6046 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6049 UIAlertView *alert = [[[UIAlertView alloc]
6050 initWithTitle:UCLocalize("SOURCE_WARNING")
6053 cancelButtonTitle:UCLocalize("CANCEL")
6054 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6057 [alert setContext:@"warning"];
6058 [alert setNumberOfRows:1];
6062 } else if (error_ != nil) {
6063 UIAlertView *alert = [[[UIAlertView alloc]
6064 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6065 message:[error_ localizedDescription]
6067 cancelButtonTitle:UCLocalize("OK")
6068 otherButtonTitles:nil
6071 [alert setContext:@"urlerror"];
6074 UIAlertView *alert = [[[UIAlertView alloc]
6075 initWithTitle:UCLocalize("NOT_REPOSITORY")
6076 message:UCLocalize("NOT_REPOSITORY_EX")
6078 cancelButtonTitle:UCLocalize("OK")
6079 otherButtonTitles:nil
6082 [alert setContext:@"trivial"];
6086 [delegate_ setStatusBarShowsProgress:NO];
6087 [delegate_ removeProgressHUD:hud_];
6097 if (error_ != nil) {
6104 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6105 switch ([response statusCode]) {
6111 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6112 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6114 error_ = [error retain];
6115 [self _endConnection:connection];
6118 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6119 [self _endConnection:connection];
6122 - (NSString *) title { return UCLocalize("SOURCES"); }
6124 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6125 NSMutableURLRequest *request = [NSMutableURLRequest
6126 requestWithURL:[NSURL URLWithString:href]
6127 cachePolicy:NSURLRequestUseProtocolCachePolicy
6128 timeoutInterval:120.0
6131 [request setHTTPMethod:method];
6133 if (Machine_ != NULL)
6134 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6135 if (UniqueID_ != nil)
6136 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6138 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6140 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6143 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6144 NSString *context([alert context]);
6146 if ([context isEqualToString:@"source"]) {
6149 NSString *href = [[alert textField] text];
6151 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6153 if (![href hasSuffix:@"/"])
6154 href_ = [href stringByAppendingString:@"/"];
6157 href_ = [href_ retain];
6159 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6160 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6161 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6162 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6166 // XXX: this is stupid
6167 hud_ = [[delegate_ addProgressHUD] retain];
6168 [hud_ setText:UCLocalize("VERIFYING_URL")];
6177 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6178 } else if ([context isEqualToString:@"trivial"])
6179 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6180 else if ([context isEqualToString:@"urlerror"])
6181 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6182 else if ([context isEqualToString:@"warning"]) {
6197 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6201 - (id) initWithDatabase:(Database *)database {
6202 if ((self = [super init]) != nil) {
6203 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6204 [self updateButtonsForEditingStatus:NO animated:NO];
6206 database_ = database;
6207 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6209 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6210 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6211 [[self view] addSubview:list_];
6213 [list_ setDataSource:self];
6214 [list_ setDelegate:self];
6220 - (void) reloadData {
6222 if (!list.ReadMainList())
6225 [sources_ removeAllObjects];
6226 [sources_ addObjectsFromArray:[database_ sources]];
6228 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6231 int count([sources_ count]);
6233 for (int i = 0; i != count; i++) {
6234 if ([[sources_ objectAtIndex:i] record] == nil)
6239 [list_ setEditing:NO];
6240 [self updateButtonsForEditingStatus:NO animated:NO];
6244 - (void) addButtonClicked {
6245 /*[book_ pushPage:[[[AddSourceController alloc]
6250 UIAlertView *alert = [[[UIAlertView alloc]
6251 initWithTitle:UCLocalize("ENTER_APT_URL")
6254 cancelButtonTitle:UCLocalize("CANCEL")
6255 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6258 [alert setContext:@"source"];
6259 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6261 [alert setNumberOfRows:1];
6262 [alert addTextFieldWithValue:@"http://" label:@""];
6264 UITextInputTraits *traits = [[alert textField] textInputTraits];
6265 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6266 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6267 [traits setKeyboardType:UIKeyboardTypeURL];
6268 // XXX: UIReturnKeyDone
6269 [traits setReturnKeyType:UIReturnKeyNext];
6274 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6275 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6276 initWithTitle:UCLocalize("ADD")
6277 style:UIBarButtonItemStylePlain
6279 action:@selector(addButtonClicked)
6280 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6282 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6283 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6284 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6286 action:@selector(editButtonClicked)
6287 ] autorelease] animated:animated];
6289 if (IsWildcat_ && !editing)
6290 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6291 initWithTitle:UCLocalize("SETTINGS")
6292 style:UIBarButtonItemStylePlain
6294 action:@selector(settingsButtonClicked)
6298 - (void) settingsButtonClicked {
6299 [delegate_ showSettings];
6302 - (void) editButtonClicked {
6303 [list_ setEditing:![list_ isEditing] animated:YES];
6305 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6311 /* Installed Controller {{{ */
6312 @interface InstalledController : FilteredPackageController {
6316 - (id) initWithDatabase:(Database *)database;
6318 - (void) updateRoleButton;
6319 - (void) queueStatusDidChange;
6323 @implementation InstalledController
6329 - (NSString *) title { return UCLocalize("INSTALLED"); }
6331 - (id) initWithDatabase:(Database *)database {
6332 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6333 [self updateRoleButton];
6334 [self queueStatusDidChange];
6339 - (void) queueButtonClicked {
6344 - (void) queueStatusDidChange {
6348 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6349 initWithTitle:UCLocalize("QUEUE")
6350 style:UIBarButtonItemStyleDone
6352 action:@selector(queueButtonClicked)
6355 [[self navigationItem] setLeftBarButtonItem:nil];
6361 - (void) reloadData {
6362 [packages_ reloadData];
6365 - (void) updateRoleButton {
6366 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6367 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6368 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6369 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6371 action:@selector(roleButtonClicked)
6375 - (void) roleButtonClicked {
6376 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6377 [packages_ reloadData];
6380 [self updateRoleButton];
6383 - (void) setDelegate:(id)delegate {
6384 [super setDelegate:delegate];
6385 [packages_ setDelegate:delegate];
6391 /* Home Controller {{{ */
6392 @interface HomeController : CYBrowserController {
6397 @implementation HomeController
6399 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6400 [super _setMoreHeaders:request];
6403 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6404 if (UniqueID_ != nil)
6405 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6407 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6410 - (void) aboutButtonClicked {
6411 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6413 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6414 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6415 [alert setCancelButtonIndex:0];
6418 @"Copyright (C) 2008-2010\n"
6419 "Jay Freeman (saurik)\n"
6420 "saurik@saurik.com\n"
6421 "http://www.saurik.com/"
6427 - (void) viewWillAppear:(BOOL)animated {
6428 [super viewWillAppear:animated];
6429 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6432 - (void) viewWillDisappear:(BOOL)animated {
6433 [super viewWillDisappear:animated];
6434 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6438 if ((self = [super init]) != nil) {
6439 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6440 initWithTitle:UCLocalize("ABOUT")
6441 style:UIBarButtonItemStylePlain
6443 action:@selector(aboutButtonClicked)
6450 /* Manage Controller {{{ */
6451 @interface ManageController : CYBrowserController {
6454 - (void) queueStatusDidChange;
6457 @implementation ManageController
6460 if ((self = [super init]) != nil) {
6461 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6463 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6464 initWithTitle:UCLocalize("SETTINGS")
6465 style:UIBarButtonItemStylePlain
6467 action:@selector(settingsButtonClicked)
6470 [self queueStatusDidChange];
6474 - (void) settingsButtonClicked {
6475 [delegate_ showSettings];
6479 - (void) queueButtonClicked {
6483 - (void) applyLoadingTitle {
6484 // No "Loading" title.
6487 - (void) applyRightButton {
6492 - (void) queueStatusDidChange {
6494 if (!IsWildcat_ && Queuing_) {
6495 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6496 initWithTitle:UCLocalize("QUEUE")
6497 style:UIBarButtonItemStyleDone
6499 action:@selector(queueButtonClicked)
6502 [[self navigationItem] setRightBarButtonItem:nil];
6507 - (bool) isLoading {
6514 /* Refresh Bar {{{ */
6515 @interface RefreshBar : UINavigationBar {
6516 UIProgressIndicator *indicator_;
6517 UITextLabel *prompt_;
6518 UIProgressBar *progress_;
6519 UINavigationButton *cancel_;
6524 @implementation RefreshBar
6527 [indicator_ release];
6529 [progress_ release];
6534 - (void) positionViews {
6535 CGRect frame = [cancel_ frame];
6536 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6537 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6538 [cancel_ setFrame:frame];
6540 CGSize prgsize = {75, 100};
6542 [self frame].size.width - prgsize.width - 10,
6543 ([self frame].size.height - prgsize.height) / 2
6545 [progress_ setFrame:prgrect];
6547 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6548 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6549 CGRect indrect = {{indoffset, indoffset}, indsize};
6550 [indicator_ setFrame:indrect];
6552 CGSize prmsize = {215, indsize.height + 4};
6554 indoffset * 2 + indsize.width,
6555 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6557 [prompt_ setFrame:prmrect];
6560 - (void)setFrame:(CGRect)frame {
6561 [super setFrame:frame];
6563 [self positionViews];
6566 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6567 if ((self = [super initWithFrame:frame])) {
6568 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6570 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6571 [self setBarStyle:UIBarStyleBlack];
6573 UIBarStyle barstyle([self _barStyle:NO]);
6574 bool ugly(barstyle == UIBarStyleDefault);
6576 UIProgressIndicatorStyle style = ugly ?
6577 UIProgressIndicatorStyleMediumBrown :
6578 UIProgressIndicatorStyleMediumWhite;
6580 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6581 [indicator_ setStyle:style];
6582 [indicator_ startAnimation];
6583 [self addSubview:indicator_];
6585 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6586 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6587 [prompt_ setBackgroundColor:[UIColor clearColor]];
6588 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6589 [self addSubview:prompt_];
6591 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6592 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6593 [progress_ setStyle:0];
6594 [self addSubview:progress_];
6596 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6597 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6598 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6599 [cancel_ setBarStyle:barstyle];
6601 [self positionViews];
6606 [cancel_ removeFromSuperview];
6610 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6611 [progress_ setProgress:0];
6612 [self addSubview:cancel_];
6616 [cancel_ removeFromSuperview];
6619 - (void) setPrompt:(NSString *)prompt {
6620 [prompt_ setText:prompt];
6623 - (void) setProgress:(float)progress {
6624 [progress_ setProgress:progress];
6630 @class CYNavigationController;
6632 /* Cydia Tab Bar Controller {{{ */
6633 @interface CYTabBarController : UITabBarController <
6636 _transient Database *database_;
6637 RefreshBar *refreshbar_;
6641 // XXX: ok, "updatedelegate_"?...
6642 _transient NSObject<CydiaDelegate> *updatedelegate_;
6647 - (void) dropBar:(BOOL)animated;
6648 - (void) beginUpdate;
6649 - (void) raiseBar:(BOOL)animated;
6654 @implementation CYTabBarController
6656 /* XXX: some logic should probably go here related to
6657 freeing the view controllers on tab change */
6659 - (void) reloadData {
6660 size_t count([[self viewControllers] count]);
6661 for (size_t i(0); i != count; ++i) {
6662 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6667 - (id) initWithDatabase:(Database *)database {
6668 if ((self = [super init]) != nil) {
6669 database_ = database;
6671 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6672 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6674 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6678 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6679 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
6682 - (void) setUpdate:(NSDate *)date {
6686 - (void) beginUpdate {
6688 [refreshbar_ start];
6693 detachNewThreadSelector:@selector(performUpdate)
6699 - (void) performUpdate { _pooled
6701 status.setDelegate(self);
6702 [database_ updateWithStatus:status];
6705 performSelectorOnMainThread:@selector(completeUpdate)
6711 - (void) completeUpdate {
6716 [self raiseBar:YES];
6718 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6721 - (void) cancelUpdate {
6723 [self raiseBar:YES];
6725 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
6728 - (void) cancelPressed {
6729 [self cancelUpdate];
6736 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6737 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6740 - (void) startProgress {
6743 - (void) setProgressTitle:(NSString *)title {
6745 performSelectorOnMainThread:@selector(_setProgressTitle:)
6751 - (bool) isCancelling:(size_t)received {
6755 - (void) setProgressPercent:(float)percent {
6757 performSelectorOnMainThread:@selector(_setProgressPercent:)
6758 withObject:[NSNumber numberWithFloat:percent]
6763 - (void) addProgressOutput:(NSString *)output {
6765 performSelectorOnMainThread:@selector(_addProgressOutput:)
6771 - (void) _setProgressTitle:(NSString *)title {
6772 [refreshbar_ setPrompt:title];
6775 - (void) _setProgressPercent:(NSNumber *)percent {
6776 [refreshbar_ setProgress:[percent floatValue]];
6779 - (void) _addProgressOutput:(NSString *)output {
6782 - (void) setUpdateDelegate:(id)delegate {
6783 updatedelegate_ = delegate;
6786 - (CGFloat) statusBarHeight {
6787 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6788 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6790 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6794 - (UIView *) transitionView {
6795 if ([self respondsToSelector:@selector(_transitionView)])
6796 return [self _transitionView];
6798 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6801 - (void) dropBar:(BOOL)animated {
6806 UIView *transition([self transitionView]);
6807 [[self view] addSubview:refreshbar_];
6809 CGRect barframe([refreshbar_ frame]);
6811 if (false) // XXX: _UIApplicationLinkedOnOrAfter(4)
6812 barframe.origin.y = [self statusBarHeight];
6814 barframe.origin.y = 0;
6816 [refreshbar_ setFrame:barframe];
6819 [UIView beginAnimations:nil context:NULL];
6821 CGRect viewframe = [transition frame];
6822 viewframe.origin.y += barframe.size.height;
6823 viewframe.size.height -= barframe.size.height;
6824 [transition setFrame:viewframe];
6827 [UIView commitAnimations];
6829 // Ensure bar has the proper width for our view, it might have changed
6830 barframe.size.width = viewframe.size.width;
6831 [refreshbar_ setFrame:barframe];
6833 // XXX: fix Apple's layout bug
6834 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6837 - (void) raiseBar:(BOOL)animated {
6842 UIView *transition([self transitionView]);
6843 [refreshbar_ removeFromSuperview];
6845 CGRect barframe([refreshbar_ frame]);
6848 [UIView beginAnimations:nil context:NULL];
6850 CGRect viewframe = [transition frame];
6851 viewframe.origin.y -= barframe.size.height;
6852 viewframe.size.height += barframe.size.height;
6853 [transition setFrame:viewframe];
6856 [UIView commitAnimations];
6858 // XXX: fix Apple's layout bug
6859 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6863 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6864 // XXX: fix Apple's layout bug
6865 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6869 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6870 bool dropped(dropped_);
6875 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6880 // XXX: fix Apple's layout bug
6881 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6884 - (void) statusBarFrameChanged:(NSNotification *)notification {
6892 [refreshbar_ release];
6893 [[NSNotificationCenter defaultCenter] removeObserver:self];
6900 /* Cydia Navigation Controller {{{ */
6901 @interface CYNavigationController : UINavigationController {
6902 _transient Database *database_;
6903 _transient id<UINavigationControllerDelegate> delegate_;
6906 - (id) initWithDatabase:(Database *)database;
6907 - (void) reloadData;
6912 @implementation CYNavigationController
6914 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6915 // Inherit autorotation settings for modal parents.
6916 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6917 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6919 return [super shouldAutorotateToInterfaceOrientation:orientation];
6927 - (void) reloadData {
6928 size_t count([[self viewControllers] count]);
6929 for (size_t i(0); i != count; ++i) {
6930 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6935 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6936 delegate_ = delegate;
6939 - (id) initWithDatabase:(Database *)database {
6940 if ((self = [super init]) != nil) {
6941 database_ = database;
6947 /* Cydia:// Protocol {{{ */
6948 @interface CydiaURLProtocol : NSURLProtocol {
6953 @implementation CydiaURLProtocol
6955 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6956 NSURL *url([request URL]);
6959 NSString *scheme([[url scheme] lowercaseString]);
6960 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6965 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6969 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6970 id<NSURLProtocolClient> client([self client]);
6972 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6974 NSData *data(UIImagePNGRepresentation(icon));
6976 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6977 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6978 [client URLProtocol:self didLoadData:data];
6979 [client URLProtocolDidFinishLoading:self];
6983 - (void) startLoading {
6984 id<NSURLProtocolClient> client([self client]);
6985 NSURLRequest *request([self request]);
6987 NSURL *url([request URL]);
6988 NSString *href([url absoluteString]);
6990 NSString *path([href substringFromIndex:8]);
6991 NSRange slash([path rangeOfString:@"/"]);
6994 if (slash.location == NSNotFound) {
6998 command = [path substringToIndex:slash.location];
6999 path = [path substringFromIndex:(slash.location + 1)];
7002 Database *database([Database sharedInstance]);
7004 if ([command isEqualToString:@"package-icon"]) {
7007 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7008 Package *package([database packageWithName:path]);
7011 UIImage *icon([package icon]);
7012 [self _returnPNGWithImage:icon forRequest:request];
7013 } else if ([command isEqualToString:@"source-icon"]) {
7016 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7017 NSString *source(Simplify(path));
7018 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7020 icon = [UIImage applicationImageNamed:@"unknown.png"];
7021 [self _returnPNGWithImage:icon forRequest:request];
7022 } else if ([command isEqualToString:@"uikit-image"]) {
7025 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7026 UIImage *icon(_UIImageWithName(path));
7027 [self _returnPNGWithImage:icon forRequest:request];
7028 } else if ([command isEqualToString:@"section-icon"]) {
7031 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7032 NSString *section(Simplify(path));
7033 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7035 icon = [UIImage applicationImageNamed:@"unknown.png"];
7036 [self _returnPNGWithImage:icon forRequest:request];
7038 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7042 - (void) stopLoading {
7048 /* Sections Controller {{{ */
7049 @interface SectionsController : CYViewController <
7050 UITableViewDataSource,
7053 _transient Database *database_;
7054 NSMutableArray *sections_;
7055 NSMutableArray *filtered_;
7061 - (id) initWithDatabase:(Database *)database;
7062 - (void) reloadData;
7065 - (void) editButtonClicked;
7069 @implementation SectionsController
7072 [list_ setDataSource:nil];
7073 [list_ setDelegate:nil];
7075 [sections_ release];
7076 [filtered_ release];
7078 [accessory_ release];
7082 - (void) viewDidAppear:(BOOL)animated {
7083 [super viewDidAppear:animated];
7084 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7087 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7088 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7092 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7093 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7096 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7100 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7101 static NSString *reuseIdentifier = @"SectionCell";
7103 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7105 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7107 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7112 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7116 Section *section = [self sectionAtIndexPath:indexPath];
7117 NSString *name = [section name];
7120 if ([indexPath row] == 0) {
7123 title = UCLocalize("ALL_PACKAGES");
7126 name = [NSString stringWithString:name];
7127 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7130 title = UCLocalize("NO_SECTION");
7134 FilteredPackageController *table = [[[FilteredPackageController alloc]
7135 initWithDatabase:database_
7137 filter:@selector(isVisibleInSection:)
7141 [table setDelegate:delegate_];
7143 [[self navigationController] pushViewController:table animated:YES];
7146 - (NSString *) title { return UCLocalize("SECTIONS"); }
7148 - (id) initWithDatabase:(Database *)database {
7149 if ((self = [super init]) != nil) {
7150 database_ = database;
7152 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7154 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7155 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7157 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7158 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7159 [list_ setRowHeight:45.0f];
7160 [[self view] addSubview:list_];
7162 [list_ setDataSource:self];
7163 [list_ setDelegate:self];
7169 - (void) reloadData {
7170 NSArray *packages = [database_ packages];
7172 [sections_ removeAllObjects];
7173 [filtered_ removeAllObjects];
7175 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7178 for (Package *package in packages) {
7179 NSString *name([package section]);
7180 NSString *key(name == nil ? @"" : name);
7184 _profile(SectionsView$reloadData$Section)
7185 section = [sections objectForKey:key];
7186 if (section == nil) {
7187 _profile(SectionsView$reloadData$Section$Allocate)
7188 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
7189 [sections setObject:section forKey:key];
7194 [section addToCount];
7196 _profile(SectionsView$reloadData$Filter)
7197 if (![package valid] || ![package visible])
7205 [sections_ addObjectsFromArray:[sections allValues]];
7207 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7209 for (Section *section in sections_) {
7210 size_t count([section row]);
7214 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7215 [section setCount:count];
7216 [filtered_ addObject:section];
7219 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7220 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
7221 style:UIBarButtonItemStylePlain
7223 action:@selector(editButtonClicked)
7224 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7230 - (void) resetView {
7232 [self editButtonClicked];
7235 - (void) editButtonClicked {
7236 if ((editing_ = !editing_))
7239 [delegate_ updateData];
7241 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7242 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
7243 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
7246 - (UIView *) accessoryView {
7252 /* Changes Controller {{{ */
7253 @interface ChangesController : CYViewController <
7254 UITableViewDataSource,
7257 _transient Database *database_;
7259 CFMutableArrayRef packages_;
7260 NSMutableArray *sections_;
7263 BOOL hasSentFirstLoad_;
7266 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
7267 - (void) reloadData;
7271 @implementation ChangesController
7274 [list_ setDelegate:nil];
7275 [list_ setDataSource:nil];
7277 CFRelease(packages_);
7279 [sections_ release];
7284 - (void) viewDidAppear:(BOOL)animated {
7285 [super viewDidAppear:animated];
7286 if (!hasSentFirstLoad_) {
7287 hasSentFirstLoad_ = YES;
7288 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7290 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7294 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7295 NSInteger count([sections_ count]);
7296 return count == 0 ? 1 : count;
7299 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7300 if ([sections_ count] == 0)
7302 return [[sections_ objectAtIndex:section] name];
7305 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7306 if ([sections_ count] == 0)
7308 return [[sections_ objectAtIndex:section] count];
7311 - (Package *) packageAtIndex:(NSUInteger)index {
7312 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7315 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7316 @synchronized (database_) {
7317 if ([database_ era] != era_)
7320 Section *section([sections_ objectAtIndex:[path section]]);
7321 NSInteger row([path row]);
7322 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7325 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7326 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7328 cell = [[[PackageCell alloc] init] autorelease];
7329 [cell setPackage:[self packageAtIndexPath:path]];
7333 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7334 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7337 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7338 Package *package([self packageAtIndexPath:path]);
7339 PackageController *view([delegate_ packageController]);
7340 [view setDelegate:delegate_];
7341 [view setPackage:package];
7342 [[self navigationController] pushViewController:view animated:YES];
7346 - (void) refreshButtonClicked {
7347 [delegate_ beginUpdate];
7348 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7351 - (void) upgradeButtonClicked {
7352 [delegate_ distUpgrade];
7355 - (NSString *) title { return UCLocalize("CHANGES"); }
7357 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7358 if ((self = [super init]) != nil) {
7359 database_ = database;
7360 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7362 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7364 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7366 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7367 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7368 [list_ setRowHeight:73.0f];
7369 [[self view] addSubview:list_];
7371 [list_ setDataSource:self];
7372 [list_ setDelegate:self];
7374 delegate_ = delegate;
7378 - (void) _reloadPackages:(NSArray *)packages {
7380 for (Package *package in packages)
7381 if ([package upgradableAndEssential:YES] || [package visible])
7382 CFArrayAppendValue(packages_, package);
7385 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7389 - (void) reloadData {
7390 era_ = [database_ era];
7391 NSArray *packages = [database_ packages];
7393 CFArrayRemoveAllValues(packages_);
7395 [sections_ removeAllObjects];
7398 UIProgressHUD *hud([delegate_ addProgressHUD]);
7399 [hud setText:UCLocalize("LOADING")];
7400 //NSLog(@"HUD:%@::%@", delegate_, hud);
7401 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7402 [delegate_ removeProgressHUD:hud];
7404 [self _reloadPackages:packages];
7407 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7408 Section *ignored = nil;
7409 Section *section = nil;
7413 bool unseens = false;
7415 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7417 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7418 Package *package = [self packageAtIndex:offset];
7420 BOOL uae = [package upgradableAndEssential:YES];
7424 time_t seen([package seen]);
7426 if (section == nil || last != seen) {
7430 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7433 _profile(ChangesController$reloadData$Allocate)
7434 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7435 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7436 [sections_ addObject:section];
7440 [section addToCount];
7441 } else if ([package ignored]) {
7442 if (ignored == nil) {
7443 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7445 [ignored addToCount];
7448 [upgradable addToCount];
7453 CFRelease(formatter);
7456 Section *last = [sections_ lastObject];
7457 size_t count = [last count];
7458 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7459 [sections_ removeLastObject];
7462 if ([ignored count] != 0)
7463 [sections_ insertObject:ignored atIndex:0];
7465 [sections_ insertObject:upgradable atIndex:0];
7470 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7471 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7472 style:UIBarButtonItemStylePlain
7474 action:@selector(upgradeButtonClicked)
7477 if (![delegate_ updating])
7478 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7479 initWithTitle:UCLocalize("REFRESH")
7480 style:UIBarButtonItemStylePlain
7482 action:@selector(refreshButtonClicked)
7488 /* Search Controller {{{ */
7489 @interface SearchController : FilteredPackageController <
7492 UISearchBar *search_;
7495 - (id) initWithDatabase:(Database *)database;
7496 - (void) reloadData;
7500 @implementation SearchController
7507 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7508 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7509 [search_ resignFirstResponder];
7513 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7514 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7518 - (NSString *) title { return nil; }
7520 - (id) initWithDatabase:(Database *)database {
7521 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7524 - (void)viewDidAppear:(BOOL)animated {
7525 [super viewDidAppear:animated];
7527 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7528 [search_ layoutSubviews];
7529 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7531 UITextField *textField;
7532 if ([search_ respondsToSelector:@selector(searchField)])
7533 textField = [search_ searchField];
7535 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7537 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7538 [search_ setDelegate:self];
7539 [textField setEnablesReturnKeyAutomatically:NO];
7540 [[self navigationItem] setTitleView:textField];
7544 - (void) _reloadData {
7547 - (void) reloadData {
7548 _profile(SearchController$reloadData)
7549 [packages_ reloadData];
7552 [packages_ resetCursor];
7555 - (void) didSelectPackage:(Package *)package {
7556 [search_ resignFirstResponder];
7557 [super didSelectPackage:package];
7562 /* Settings Controller {{{ */
7563 @interface SettingsController : CYViewController <
7564 UITableViewDataSource,
7567 _transient Database *database_;
7570 UITableView *table_;
7571 UISwitch *subscribedSwitch_;
7572 UISwitch *ignoredSwitch_;
7573 UITableViewCell *subscribedCell_;
7574 UITableViewCell *ignoredCell_;
7577 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7581 @implementation SettingsController
7585 if (package_ != nil)
7588 [subscribedSwitch_ release];
7589 [ignoredSwitch_ release];
7590 [subscribedCell_ release];
7591 [ignoredCell_ release];
7596 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7597 if (package_ == nil)
7603 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7604 if (package_ == nil)
7610 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7611 return UCLocalize("SHOW_ALL_CHANGES_EX");
7614 - (void) onSubscribed:(id)control {
7615 bool value([control isOn]);
7616 if (package_ == nil)
7618 if ([package_ setSubscribed:value])
7619 [delegate_ updateData];
7622 - (void) onIgnored:(id)control {
7623 // TODO: set Held state - possibly call out to dpkg, etc.
7626 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7627 if (package_ == nil)
7630 switch ([indexPath row]) {
7631 case 0: return subscribedCell_;
7632 case 1: return ignoredCell_;
7640 - (NSString *) title { return UCLocalize("SETTINGS"); }
7642 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7643 if ((self = [super init])) {
7644 database_ = database;
7645 name_ = [package retain];
7647 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7649 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7650 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7651 [[self view] addSubview:table_];
7653 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7654 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7655 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7657 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7658 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7659 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7661 subscribedCell_ = [[UITableViewCell alloc] init];
7662 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7663 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7664 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7666 ignoredCell_ = [[UITableViewCell alloc] init];
7667 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7668 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7669 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7671 [table_ setDataSource:self];
7672 [table_ setDelegate:self];
7677 - (void) reloadData {
7678 if (package_ != nil)
7679 [package_ autorelease];
7680 package_ = [database_ packageWithName:name_];
7681 if (package_ != nil) {
7683 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7684 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7687 [table_ reloadData];
7692 /* Signature Controller {{{ */
7693 @interface SignatureController : CYBrowserController {
7694 _transient Database *database_;
7698 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7702 @implementation SignatureController
7709 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7711 [super webView:view didClearWindowObject:window forFrame:frame];
7714 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7715 if ((self = [super init]) != nil) {
7716 database_ = database;
7717 package_ = [package retain];
7722 - (void) reloadData {
7723 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7729 /* Role Controller {{{ */
7730 @interface RoleController : CYViewController <
7731 UITableViewDataSource,
7734 _transient Database *database_;
7735 // XXX: ok, "roledelegate_"?...
7736 _transient id roledelegate_;
7737 UITableView *table_;
7738 UISegmentedControl *segment_;
7742 - (void) showDoneButton;
7743 - (void) resizeSegmentedControl;
7747 @implementation RoleController
7751 [container_ release];
7756 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7757 if ((self = [super init])) {
7758 database_ = database;
7759 roledelegate_ = delegate;
7761 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7763 NSArray *items = [NSArray arrayWithObjects:
7765 UCLocalize("HACKER"),
7766 UCLocalize("DEVELOPER"),
7768 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7769 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7770 [container_ addSubview:segment_];
7773 if ([Role_ isEqualToString:@"User"]) index = 0;
7774 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7775 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7777 [segment_ setSelectedSegmentIndex:index];
7778 [self showDoneButton];
7781 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7782 [self resizeSegmentedControl];
7784 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7785 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7786 [table_ setDelegate:self];
7787 [table_ setDataSource:self];
7788 [[self view] addSubview:table_];
7789 [table_ reloadData];
7793 - (void) resizeSegmentedControl {
7794 CGFloat width = [[self view] frame].size.width;
7795 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7798 - (void) viewWillAppear:(BOOL)animated {
7799 [super viewWillAppear:animated];
7801 [self resizeSegmentedControl];
7804 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7805 [self resizeSegmentedControl];
7808 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7809 [self resizeSegmentedControl];
7813 NSString *role(nil);
7815 switch ([segment_ selectedSegmentIndex]) {
7816 case 0: role = @"User"; break;
7817 case 1: role = @"Hacker"; break;
7818 case 2: role = @"Developer"; break;
7823 if (![role isEqualToString:Role_]) {
7824 bool rolling(Role_ == nil);
7827 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7831 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7835 [roledelegate_ loadData];
7837 [roledelegate_ updateData];
7841 - (void) segmentChanged:(UISegmentedControl *)control {
7842 [self showDoneButton];
7845 - (void) saveAndClose {
7848 [[self navigationItem] setRightBarButtonItem:nil];
7849 [[self navigationController] dismissModalViewControllerAnimated:YES];
7852 - (void) doneButtonClicked {
7853 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7854 [spinner startAnimating];
7855 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7856 [[self navigationItem] setRightBarButtonItem:spinItem];
7858 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7861 - (void) showDoneButton {
7862 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7863 initWithTitle:UCLocalize("DONE")
7864 style:UIBarButtonItemStyleDone
7866 action:@selector(doneButtonClicked)
7867 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7870 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7871 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7875 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7879 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7880 return nil; // This method is required by the protocol.
7883 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7885 return UCLocalize("ROLE_EX");
7887 return [NSString stringWithFormat:
7888 @"%@: %@\n%@: %@\n%@: %@",
7889 UCLocalize("USER"), UCLocalize("USER_EX"),
7890 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7891 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7896 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7897 return section == 3 ? 44.0f : 0;
7900 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7901 return section == 3 ? container_ : nil;
7906 /* Stash Controller {{{ */
7907 @interface CYStashController : CYViewController {
7908 // XXX: just delete these things
7909 _transient UIActivityIndicatorView *spinner_;
7910 _transient UILabel *status_;
7911 _transient UILabel *caption_;
7915 @implementation CYStashController
7917 if ((self = [super init])) {
7918 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7920 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7921 CGRect spinrect = [spinner_ frame];
7922 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7923 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7924 [spinner_ setFrame:spinrect];
7925 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7926 [[self view] addSubview:spinner_];
7927 [spinner_ startAnimating];
7930 captrect.size.width = [[self view] frame].size.width;
7931 captrect.size.height = 40.0f;
7932 captrect.origin.x = 0;
7933 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7934 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7935 [caption_ setText:@"Initializing Filesystem"];
7936 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7937 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7938 [caption_ setTextColor:[UIColor whiteColor]];
7939 [caption_ setBackgroundColor:[UIColor clearColor]];
7940 [caption_ setShadowColor:[UIColor blackColor]];
7941 [caption_ setTextAlignment:UITextAlignmentCenter];
7942 [[self view] addSubview:caption_];
7945 statusrect.size.width = [[self view] frame].size.width;
7946 statusrect.size.height = 30.0f;
7947 statusrect.origin.x = 0;
7948 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7949 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7950 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7951 [status_ setText:@"(Cydia will exit when complete.)"];
7952 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7953 [status_ setTextColor:[UIColor whiteColor]];
7954 [status_ setBackgroundColor:[UIColor clearColor]];
7955 [status_ setShadowColor:[UIColor blackColor]];
7956 [status_ setTextAlignment:UITextAlignmentCenter];
7957 [[self view] addSubview:status_];
7961 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7962 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7977 @interface Cydia : UIApplication <
7978 ConfirmationControllerDelegate,
7979 ProgressControllerDelegate,
7981 UINavigationControllerDelegate,
7982 UITabBarControllerDelegate
7984 // XXX: evaluate all fields for _transient
7987 CYTabBarController *tabbar_;
7989 NSMutableArray *essential_;
7990 NSMutableArray *broken_;
7992 Database *database_;
7998 SectionsController *sections_;
7999 ChangesController *changes_;
8000 ManageController *manage_;
8001 SearchController *search_;
8002 SourceTable *sources_;
8003 InstalledController *installed_;
8006 CYStashController *stash_;
8011 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
8012 - (void) setPage:(CYViewController *)page;
8015 // XXX: I hate prototypes
8016 - (id) queueBadgeController;
8020 static _finline void _setHomePage(Cydia *self) {
8021 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
8024 @implementation Cydia
8026 - (void) beginUpdate {
8027 [tabbar_ beginUpdate];
8031 return [tabbar_ updating];
8034 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8039 if ([broken_ count] != 0) {
8040 int count = [broken_ count];
8042 UIAlertView *alert = [[[UIAlertView alloc]
8043 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8044 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8046 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8047 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8050 [alert setContext:@"fixhalf"];
8052 } else if (!Ignored_ && [essential_ count] != 0) {
8053 int count = [essential_ count];
8055 UIAlertView *alert = [[[UIAlertView alloc]
8056 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8057 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8059 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8060 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8063 [alert setContext:@"upgrade"];
8068 - (void) _saveConfig {
8074 NSString *error(nil);
8076 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8078 NSError *error(nil);
8079 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8080 NSLog(@"failure to save metadata data: %@", error);
8085 NSLog(@"failure to serialize metadata: %@", error);
8090 - (void) _updateData {
8093 /* XXX: this is just stupid */
8094 if (tag_ != 1 && sections_ != nil)
8095 [sections_ reloadData];
8096 if (tag_ != 2 && changes_ != nil)
8097 [changes_ reloadData];
8098 if (tag_ != 4 && search_ != nil)
8099 [search_ reloadData];
8101 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8103 [queueDelegate_ queueStatusDidChange];
8104 [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8107 - (int)indexOfTabWithTag:(int)tag {
8109 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8110 if ([[controller tabBarItem] tag] == tag)
8118 - (void) _refreshIfPossible {
8119 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8121 bool recently = false;
8122 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8123 if (update != nil) {
8124 NSTimeInterval interval([update timeIntervalSinceNow]);
8125 if (interval <= 0 && interval > -(15*60))
8129 // Don't automatic refresh if:
8130 // - We already refreshed recently.
8131 // - We already auto-refreshed this launch.
8132 // - Auto-refresh is disabled.
8133 if (recently || loaded_ || ManualRefresh) {
8134 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8136 // If we are cancelling due to ManualRefresh or a recent refresh
8137 // we need to make sure it knows it's already loaded.
8141 // We are going to load, so remember that.
8145 SCNetworkReachabilityFlags flags; {
8146 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8147 SCNetworkReachabilityGetFlags(reachability, &flags);
8148 CFRelease(reachability);
8151 // XXX: this elaborate mess is what Apple is using to determine this? :(
8152 // XXX: do we care if the user has to intervene? maybe that's ok?
8154 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8155 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8156 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8157 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8158 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8159 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8163 // If we can reach the server, auto-refresh!
8165 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8170 - (void) refreshIfPossible {
8171 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8174 - (void) _reloadData {
8175 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8176 [hud setText:UCLocalize("RELOADING_DATA")];
8178 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8181 [self removeProgressHUD:hud];
8185 [essential_ removeAllObjects];
8186 [broken_ removeAllObjects];
8188 NSArray *packages([database_ packages]);
8189 for (Package *package in packages) {
8191 [broken_ addObject:package];
8192 if ([package upgradableAndEssential:NO]) {
8193 if ([package essential])
8194 [essential_ addObject:package];
8199 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8201 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8202 [changesItem setBadgeValue:badge];
8203 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8205 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8206 [self setApplicationBadge:badge];
8208 [self setApplicationBadgeString:badge];
8210 [changesItem setBadgeValue:nil];
8211 [changesItem setAnimatedBadge:NO];
8213 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8214 [self removeApplicationBadge];
8215 else // XXX: maybe use setApplicationBadgeString also?
8216 [self setApplicationIconBadgeNumber:0];
8221 [self refreshIfPossible];
8224 - (void) updateData {
8233 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8234 _assert(file != NULL);
8236 for (NSString *key in [Sources_ allKeys]) {
8237 NSDictionary *source([Sources_ objectForKey:key]);
8239 fprintf(file, "%s %s %s\n",
8240 [[source objectForKey:@"Type"] UTF8String],
8241 [[source objectForKey:@"URI"] UTF8String],
8242 [[source objectForKey:@"Distribution"] UTF8String]
8250 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8251 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8253 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8254 [tabbar_ presentModalViewController:navigation animated:YES];
8257 detachNewThreadSelector:@selector(update_)
8260 title:UCLocalize("UPDATING_SOURCES")
8264 - (void) reloadData {
8265 @synchronized (self) {
8271 pkgProblemResolver *resolver = [database_ resolver];
8273 resolver->InstallProtect();
8274 if (!resolver->Resolve(true))
8278 - (CGRect) popUpBounds {
8279 return [[tabbar_ view] bounds];
8283 if (![database_ prepare])
8286 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8287 [page setDelegate:self];
8288 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8289 [confirm_ setDelegate:self];
8292 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8293 [tabbar_ presentModalViewController:confirm_ animated:YES];
8299 @synchronized (self) {
8304 - (void) clearPackage:(Package *)package {
8305 @synchronized (self) {
8312 - (void) installPackages:(NSArray *)packages {
8313 @synchronized (self) {
8314 for (Package *package in packages)
8321 - (void) installPackage:(Package *)package {
8322 @synchronized (self) {
8329 - (void) removePackage:(Package *)package {
8330 @synchronized (self) {
8337 - (void) distUpgrade {
8338 @synchronized (self) {
8339 if (![database_ upgrade])
8346 @synchronized (self) {
8351 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8354 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8356 if (navigation != nil) {
8357 [navigation pushViewController:progress animated:YES];
8359 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8361 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8362 [tabbar_ presentModalViewController:navigation animated:YES];
8366 detachNewThreadSelector:@selector(perform)
8369 title:UCLocalize("RUNNING")
8375 - (void) progressControllerIsComplete:(ProgressController *)progress {
8380 - (void) setPage:(CYViewController *)page {
8381 [page setDelegate:self];
8383 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8384 [navController setViewControllers:[NSArray arrayWithObject:page]];
8385 for (CYNavigationController *page in [tabbar_ viewControllers])
8386 if (page != navController)
8387 [page setViewControllers:nil];
8390 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8391 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8392 [browser loadURL:url];
8396 - (SectionsController *) sectionsController {
8397 if (sections_ == nil)
8398 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8402 - (ChangesController *) changesController {
8403 if (changes_ == nil)
8404 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8408 - (ManageController *) manageController {
8409 if (manage_ == nil) {
8410 manage_ = (ManageController *) [[self
8411 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8412 withClass:[ManageController class]
8415 queueDelegate_ = manage_;
8420 - (SearchController *) searchController {
8422 search_ = [[SearchController alloc] initWithDatabase:database_];
8426 - (SourceTable *) sourcesController {
8427 if (sources_ == nil)
8428 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8432 - (InstalledController *) installedController {
8433 if (installed_ == nil) {
8434 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8436 queueDelegate_ = installed_;
8441 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8442 int tag = [[viewController tabBarItem] tag];
8444 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8446 } else if (tag_ == 1) {
8447 [[self sectionsController] resetView];
8451 case kCydiaTag: _setHomePage(self); break;
8453 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8454 case kChangesTag: [self setPage:[self changesController]]; break;
8455 case kManageTag: [self setPage:[self manageController]]; break;
8456 case kInstalledTag: [self setPage:[self installedController]]; break;
8457 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8458 case kSearchTag: [self setPage:[self searchController]]; break;
8466 - (void) showSettings {
8467 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8468 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8470 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8471 [tabbar_ presentModalViewController:nav animated:YES];
8474 - (void) setPackageController:(PackageController *)view {
8476 [view setPackage:nil];
8480 - (PackageController *) _packageController {
8481 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8484 - (PackageController *) packageController {
8485 return [self _packageController];
8488 // Returns the navigation controller for the queuing badge.
8489 - (id) queueBadgeController {
8490 int index = [self indexOfTabWithTag:kManageTag];
8492 index = [self indexOfTabWithTag:kInstalledTag];
8494 return [[tabbar_ viewControllers] objectAtIndex:index];
8497 - (void) cancelAndClear:(bool)clear {
8498 @synchronized (self) {
8510 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8511 NSString *context([alert context]);
8513 if ([context isEqualToString:@"fixhalf"]) {
8514 if (button == [alert firstOtherButtonIndex]) {
8515 @synchronized (self) {
8516 for (Package *broken in broken_) {
8519 NSString *id = [broken id];
8520 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8521 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8522 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8523 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8529 } else if (button == [alert cancelButtonIndex]) {
8530 [broken_ removeAllObjects];
8534 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8535 } else if ([context isEqualToString:@"upgrade"]) {
8536 if (button == [alert firstOtherButtonIndex]) {
8537 @synchronized (self) {
8538 for (Package *essential in essential_)
8539 [essential install];
8544 } else if (button == [alert firstOtherButtonIndex] + 1) {
8546 } else if (button == [alert cancelButtonIndex]) {
8550 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8554 - (void) system:(NSString *)command { _pooled
8555 system([command UTF8String]);
8558 - (void) applicationWillSuspend {
8560 [super applicationWillSuspend];
8563 - (BOOL) isSafeToSuspend {
8564 // Use external process status API internally.
8565 // This is probably a really bad idea.
8566 // XXX: what is the point of this? does this solve anything at all?
8567 uint64_t status = 0;
8569 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8570 notify_get_state(notify_token, &status);
8571 notify_cancel(notify_token);
8574 return locked_ == 0 && status == 0;
8577 - (void) applicationSuspend:(__GSEvent *)event {
8578 if ([self isSafeToSuspend])
8579 [super applicationSuspend:event];
8582 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8583 if ([self isSafeToSuspend])
8584 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8587 - (void) _setSuspended:(BOOL)value {
8588 if ([self isSafeToSuspend])
8589 [super _setSuspended:value];
8592 - (UIProgressHUD *) addProgressHUD {
8593 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8594 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8596 [window_ setUserInteractionEnabled:NO];
8599 UIViewController *target = tabbar_;
8600 while ([target modalViewController] != nil) target = [target modalViewController];
8601 [[target view] addSubview:hud];
8607 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8609 [hud removeFromSuperview];
8610 [window_ setUserInteractionEnabled:YES];
8614 - (CYViewController *) pageForPackage:(NSString *)name {
8615 if (Package *package = [database_ packageWithName:name]) {
8616 PackageController *view([self packageController]);
8617 [view setPackage:package];
8620 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8621 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8622 return [self _pageForURL:url withClass:[CYBrowserController class]];
8626 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8630 NSString *href([url absoluteString]);
8631 if ([href hasPrefix:@"apptapp://package/"])
8632 return [self pageForPackage:[href substringFromIndex:18]];
8634 NSString *scheme([[url scheme] lowercaseString]);
8635 if (![scheme isEqualToString:@"cydia"])
8637 NSString *path([url absoluteString]);
8638 if ([path length] < 8)
8640 path = [path substringFromIndex:8];
8641 if (![path hasPrefix:@"/"])
8642 path = [@"/" stringByAppendingString:path];
8644 if ([path isEqualToString:@"/add-source"])
8645 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8646 else if ([path isEqualToString:@"/storage"])
8647 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8648 else if ([path isEqualToString:@"/sources"])
8649 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8650 else if ([path isEqualToString:@"/packages"])
8651 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8652 else if ([path hasPrefix:@"/url/"])
8653 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8654 else if ([path hasPrefix:@"/launch/"])
8655 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8656 else if ([path hasPrefix:@"/package-settings/"])
8657 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8658 else if ([path hasPrefix:@"/package-signature/"])
8659 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8660 else if ([path hasPrefix:@"/package/"])
8661 return [self pageForPackage:[path substringFromIndex:9]];
8662 else if ([path hasPrefix:@"/files/"]) {
8663 NSString *name = [path substringFromIndex:7];
8665 if (Package *package = [database_ packageWithName:name]) {
8666 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8667 [files setPackage:package];
8675 - (BOOL) openCydiaURL:(NSURL *)url {
8676 CYViewController *page = nil;
8679 NSLog(@"open url: %@", url);
8681 if ((page = [self pageForURL:url hasTag:&tag])) {
8682 [self setPage:page];
8684 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8690 - (void) applicationOpenURL:(NSURL *)url {
8691 [super applicationOpenURL:url];
8692 NSLog(@"first: %@", url);
8693 if (!loaded_) starturl_ = [url retain];
8694 else [self openCydiaURL:url];
8697 - (void) applicationWillResignActive:(UIApplication *)application {
8698 // Stop refreshing if you get a phone call or lock the device.
8699 if ([tabbar_ updating])
8700 [tabbar_ cancelUpdate];
8702 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8703 [super applicationWillResignActive:application];
8706 - (void) addStashController {
8708 stash_ = [[CYStashController alloc] init];
8709 [window_ addSubview:[stash_ view]];
8712 - (void) removeStashController {
8713 [[stash_ view] removeFromSuperview];
8719 [self setIdleTimerDisabled:YES];
8721 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8722 [self setStatusBarShowsProgress:YES];
8723 UpdateExternalStatus(1);
8725 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8727 UpdateExternalStatus(0);
8728 [self setStatusBarShowsProgress:NO];
8730 [self removeStashController];
8732 if (ExecFork() == 0) {
8733 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8734 perror("launchctl stop");
8738 - (void) setupTabBarController {
8739 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8740 [tabbar_ setDelegate:self];
8742 NSMutableArray *items([NSMutableArray arrayWithObjects:
8743 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8744 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8745 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8746 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8750 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8751 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8753 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8756 NSMutableArray *controllers([NSMutableArray array]);
8758 for (UITabBarItem *item in items) {
8759 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8760 [controller setTabBarItem:item];
8761 [controllers addObject:controller];
8764 [tabbar_ setViewControllers:controllers];
8767 - (void) applicationDidFinishLaunching:(id)unused {
8769 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
8770 initWithMemoryCapacity:524288
8771 diskCapacity:10485760
8772 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
8775 [CYBrowserController _initialize];
8777 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8779 Font12_ = [[UIFont systemFontOfSize:12] retain];
8780 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8781 Font14_ = [[UIFont systemFontOfSize:14] retain];
8782 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8783 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8787 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8788 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8790 UIScreen *screen([UIScreen mainScreen]);
8792 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8793 [window_ orderFront:self];
8794 [window_ makeKey:self];
8795 [window_ setHidden:NO];
8798 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8799 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8800 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8801 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8802 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8803 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8804 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8805 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8806 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8809 [self addStashController];
8810 // XXX: this would be much cleaner as a yieldToSelector:
8811 // that way the removeStashController could happen right here inline
8812 // we also could no longer require the useless stash_ field anymore
8813 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8817 database_ = [Database sharedInstance];
8819 [self setupTabBarController];
8820 [tabbar_ setUpdateDelegate:self];
8821 [window_ addSubview:[tabbar_ view]];
8823 // Show pinstripes while loading data.
8824 [[tabbar_ view] setBackgroundColor:[UIColor pinStripeColor]];
8826 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8833 [self showSettings];
8837 [window_ setUserInteractionEnabled:NO];
8839 UIView *container = [[[UIView alloc] init] autorelease];
8840 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8842 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8843 [spinner startAnimating];
8844 [container addSubview:spinner];
8846 UILabel *label = [[[UILabel alloc] init] autorelease];
8847 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8848 [label setBackgroundColor:[UIColor clearColor]];
8849 [label setTextColor:[UIColor blackColor]];
8850 [label setShadowColor:[UIColor whiteColor]];
8851 [label setShadowOffset:CGSizeMake(0, 1)];
8852 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8853 [container addSubview:label];
8855 CGSize viewsize = [[tabbar_ view] frame].size;
8856 CGSize spinnersize = [spinner bounds].size;
8857 CGSize textsize = [[label text] sizeWithFont:[label font]];
8858 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8860 CGRect containrect = {
8861 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8862 CGSizeMake(bothwidth, spinnersize.height)
8865 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8873 [container setFrame:containrect];
8874 [spinner setFrame:spinrect];
8875 [label setFrame:textrect];
8876 [[tabbar_ view] addSubview:container];
8881 // Show the initial page
8882 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
8883 [tabbar_ setSelectedIndex:0];
8887 [starturl_ release];
8890 [window_ setUserInteractionEnabled:YES];
8892 // XXX: does this actually slow anything down?
8893 [[tabbar_ view] setBackgroundColor:[UIColor clearColor]];
8894 [container removeFromSuperview];
8897 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8898 if (item != nil && IsWildcat_) {
8899 [sheet showFromBarButtonItem:item animated:YES];
8901 [sheet showInView:window_];
8908 id Alloc_(id self, SEL selector) {
8909 id object = alloc_(self, selector);
8910 lprintf("[%s]A-%p\n", self->isa->name, object);
8915 id Dealloc_(id self, SEL selector) {
8916 id object = dealloc_(self, selector);
8917 lprintf("[%s]D-%p\n", self->isa->name, object);
8921 Class $WebDefaultUIKitDelegate;
8923 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8924 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8925 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8926 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8929 static NSNumber *shouldPlayKeyboardSounds;
8933 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8935 case 1104: // Keyboard Button Clicked
8936 case 1105: // Keyboard Delete Repeated
8937 if (shouldPlayKeyboardSounds == nil) {
8938 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8939 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8942 if (![shouldPlayKeyboardSounds boolValue])
8946 _UIHardware$_playSystemSound$(self, _cmd, sound);
8950 int main(int argc, char *argv[]) { _pooled
8953 if (Class $UIDevice = objc_getClass("UIDevice")) {
8954 UIDevice *device([$UIDevice currentDevice]);
8955 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8959 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8961 /* Library Hacks {{{ */
8962 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8964 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8965 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8966 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8967 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8968 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8971 $UIHardware = objc_getClass("UIHardware");
8972 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8973 if (UIHardware$_playSystemSound$ != NULL) {
8974 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8975 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8978 /* Set Locale {{{ */
8979 Locale_ = CFLocaleCopyCurrent();
8980 Languages_ = [NSLocale preferredLanguages];
8981 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8982 //NSLog(@"%@", [Languages_ description]);
8985 if (Languages_ == nil || [Languages_ count] == 0)
8986 // XXX: consider just setting to C and then falling through?
8989 lang = [[Languages_ objectAtIndex:0] UTF8String];
8990 setenv("LANG", lang, true);
8993 //std::setlocale(LC_ALL, lang);
8994 NSLog(@"Setting Language: %s", lang);
8997 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8999 /* Parse Arguments {{{ */
9000 bool substrate(false);
9006 for (int argi(1); argi != argc; ++argi)
9007 if (strcmp(argv[argi], "--") == 0) {
9009 argv[argi] = argv[0];
9015 for (int argi(1); argi != arge; ++argi)
9016 if (strcmp(args[argi], "--substrate") == 0)
9019 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9023 App_ = [[NSBundle mainBundle] bundlePath];
9024 Home_ = NSHomeDirectory();
9030 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9031 alloc_ = alloc->method_imp;
9032 alloc->method_imp = (IMP) &Alloc_;*/
9034 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9035 dealloc_ = dealloc->method_imp;
9036 dealloc->method_imp = (IMP) &Dealloc_;*/
9038 /* System Information {{{ */
9042 size = sizeof(maxproc);
9043 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9044 perror("sysctlbyname(\"kern.maxproc\", ?)");
9045 else if (maxproc < 64) {
9047 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9048 perror("sysctlbyname(\"kern.maxproc\", #)");
9051 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9052 char *osversion = new char[size];
9053 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9054 perror("sysctlbyname(\"kern.osversion\", ?)");
9056 System_ = [NSString stringWithUTF8String:osversion];
9058 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9059 char *machine = new char[size];
9060 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9061 perror("sysctlbyname(\"hw.machine\", ?)");
9065 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9066 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9067 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9068 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9072 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9073 NSData *data((NSData *) ecid);
9074 size_t length([data length]);
9075 uint8_t bytes[length];
9076 [data getBytes:bytes];
9077 char string[length * 2 + 1];
9078 for (size_t i(0); i != length; ++i)
9079 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9080 ChipID_ = [NSString stringWithUTF8String:string];
9084 IOObjectRelease(service);
9088 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9090 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9091 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9092 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9094 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9095 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9096 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9098 if (mcc != NULL && mnc != NULL)
9099 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9106 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9107 Build_ = [system objectForKey:@"ProductBuildVersion"];
9108 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9109 Product_ = [info objectForKey:@"SafariProductVersion"];
9110 Safari_ = [info objectForKey:@"CFBundleVersion"];
9113 /* Load Database {{{ */
9115 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9117 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9119 if (Metadata_ == NULL)
9120 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9122 Settings_ = [Metadata_ objectForKey:@"Settings"];
9124 Packages_ = [Metadata_ objectForKey:@"Packages"];
9125 Sections_ = [Metadata_ objectForKey:@"Sections"];
9126 Sources_ = [Metadata_ objectForKey:@"Sources"];
9128 Token_ = [Metadata_ objectForKey:@"Token"];
9131 if (Settings_ != nil)
9132 Role_ = [Settings_ objectForKey:@"Role"];
9134 if (Sections_ == nil) {
9135 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9136 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9139 if (Sources_ == nil) {
9140 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9141 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9146 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9149 if (Packages_ != nil) {
9150 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9152 [Metadata_ removeObjectForKey:@"Packages"];
9157 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9159 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9160 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9161 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9162 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9163 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9164 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9166 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9168 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9169 unlink("/tmp/.cydia.fw");
9171 } else if (access("/User", F_OK) != 0 || version < 2) {
9174 system("/usr/libexec/cydia/firmware.sh");
9178 _assert([[NSFileManager defaultManager]
9179 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9180 withIntermediateDirectories:YES
9185 if (access("/tmp/cydia.chk", F_OK) == 0) {
9186 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9187 _assert(errno == ENOENT);
9188 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9189 _assert(errno == ENOENT);
9192 /* APT Initialization {{{ */
9193 _assert(pkgInitConfig(*_config));
9194 _assert(pkgInitSystem(*_config, _system));
9197 _config->Set("APT::Acquire::Translation", lang);
9199 // XXX: this timeout might be important :(
9200 //_config->Set("Acquire::http::Timeout", 15);
9202 _config->Set("Acquire::http::MaxParallel", 3);
9204 /* Color Choices {{{ */
9205 space_ = CGColorSpaceCreateDeviceRGB();
9207 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9208 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9209 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9210 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9211 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9212 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9213 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9214 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9215 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9217 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9218 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9220 /* UIKit Configuration {{{ */
9221 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9222 if ($GSFontSetUseLegacyFontMetrics != NULL)
9223 $GSFontSetUseLegacyFontMetrics(YES);
9225 // XXX: I have a feeling this was important
9226 //UIKeyboardDisableAutomaticAppearance();
9229 Colon_ = UCLocalize("COLON_DELIMITED");
9230 Elision_ = UCLocalize("ELISION");
9231 Error_ = UCLocalize("ERROR");
9232 Warning_ = UCLocalize("WARNING");
9235 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9237 CGColorSpaceRelease(space_);