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;
1016 static NSArray *Finishes_;
1018 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1019 #define NotifyConfig_ "/etc/notify.conf"
1021 static bool Queuing_;
1023 static CYColor Blue_;
1024 static CYColor Blueish_;
1025 static CYColor Black_;
1026 static CYColor Off_;
1027 static CYColor White_;
1028 static CYColor Gray_;
1029 static CYColor Green_;
1030 static CYColor Purple_;
1031 static CYColor Purplish_;
1033 static UIColor *InstallingColor_;
1034 static UIColor *RemovingColor_;
1036 static NSString *App_;
1037 static NSString *Home_;
1039 static BOOL Advanced_;
1040 static BOOL Ignored_;
1042 static UIFont *Font12_;
1043 static UIFont *Font12Bold_;
1044 static UIFont *Font14_;
1045 static UIFont *Font18Bold_;
1046 static UIFont *Font22Bold_;
1048 static const char *Machine_ = NULL;
1049 static NSString *System_ = nil;
1050 static NSString *SerialNumber_ = nil;
1051 static NSString *ChipID_ = nil;
1052 static NSString *Token_ = nil;
1053 static NSString *UniqueID_ = nil;
1054 static NSString *PLMN_ = nil;
1055 static NSString *Build_ = nil;
1056 static NSString *Product_ = nil;
1057 static NSString *Safari_ = nil;
1059 static CFLocaleRef Locale_;
1060 static NSArray *Languages_;
1061 static CGColorSpaceRef space_;
1063 static NSDictionary *SectionMap_;
1064 static NSMutableDictionary *Metadata_;
1065 static _transient NSMutableDictionary *Settings_;
1066 static _transient NSString *Role_;
1067 static _transient NSMutableDictionary *Packages_;
1068 static _transient NSMutableDictionary *Sections_;
1069 static _transient NSMutableDictionary *Sources_;
1070 static bool Changed_;
1073 static bool IsWildcat_;
1076 /* Display Helpers {{{ */
1077 inline float Interpolate(float begin, float end, float fraction) {
1078 return (end - begin) * fraction + begin;
1081 /* XXX: localize this! */
1082 NSString *SizeString(double size) {
1083 bool negative = size < 0;
1088 while (size > 1024) {
1093 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1095 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1098 static _finline const char *StripVersion_(const char *version) {
1099 const char *colon(strchr(version, ':'));
1100 return colon == NULL ? version : colon + 1;
1103 NSString *LocalizeSection(NSString *section) {
1104 static Pcre title_r("^(.*?) \\((.*)\\)$");
1105 if (title_r(section)) {
1106 NSString *parent(title_r[1]);
1107 NSString *child(title_r[2]);
1109 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1110 LocalizeSection(parent),
1111 LocalizeSection(child)
1115 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1118 NSString *Simplify(NSString *title) {
1119 const char *data = [title UTF8String];
1120 size_t size = [title length];
1122 static Pcre square_r("^\\[(.*)\\]$");
1123 if (square_r(data, size))
1124 return Simplify(square_r[1]);
1126 static Pcre paren_r("^\\((.*)\\)$");
1127 if (paren_r(data, size))
1128 return Simplify(paren_r[1]);
1130 static Pcre title_r("^(.*?) \\((.*)\\)$");
1131 if (title_r(data, size))
1132 return Simplify(title_r[1]);
1138 NSString *GetLastUpdate() {
1139 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1142 return UCLocalize("NEVER_OR_UNKNOWN");
1144 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1145 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1147 CFRelease(formatter);
1149 return [(NSString *) formatted autorelease];
1152 bool isSectionVisible(NSString *section) {
1153 NSDictionary *metadata([Sections_ objectForKey:section]);
1154 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1155 return hidden == nil || ![hidden boolValue];
1160 /* Delegate Prototypes {{{ */
1164 @interface NSObject (ProgressDelegate)
1167 @protocol ProgressDelegate
1168 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1169 - (void) setProgressTitle:(NSString *)title;
1170 - (void) setProgressPercent:(float)percent;
1171 - (void) startProgress;
1172 - (void) addProgressOutput:(NSString *)output;
1173 - (bool) isCancelling:(size_t)received;
1176 @protocol ConfigurationDelegate
1177 - (void) repairWithSelector:(SEL)selector;
1178 - (void) setConfigurationData:(NSString *)data;
1181 @class PackageController;
1183 @protocol CydiaDelegate
1184 - (void) retainNetworkActivityIndicator;
1185 - (void) releaseNetworkActivityIndicator;
1186 - (void) setPackageController:(PackageController *)view;
1187 - (void) clearPackage:(Package *)package;
1188 - (void) installPackage:(Package *)package;
1189 - (void) installPackages:(NSArray *)packages;
1190 - (void) removePackage:(Package *)package;
1191 - (void) beginUpdate;
1193 - (void) distUpgrade;
1195 - (void) updateData;
1197 - (void) showSettings;
1198 - (UIProgressHUD *) addProgressHUD;
1199 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1200 - (CYViewController *) pageForPackage:(NSString *)name;
1201 - (PackageController *) packageController;
1202 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1205 static id<CydiaDelegate> CydiaApp;
1208 /* Status Delegation {{{ */
1210 public pkgAcquireStatus
1213 _transient NSObject<ProgressDelegate> *delegate_;
1221 void setDelegate(id delegate) {
1222 delegate_ = delegate;
1225 NSObject<ProgressDelegate> *getDelegate() const {
1229 virtual bool MediaChange(std::string media, std::string drive) {
1233 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1236 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1237 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1238 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1241 virtual void Done(pkgAcquire::ItemDesc &item) {
1244 virtual void Fail(pkgAcquire::ItemDesc &item) {
1246 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1247 item.Owner->Status == pkgAcquire::Item::StatDone
1251 std::string &error(item.Owner->ErrorText);
1255 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1256 NSArray *fields([description componentsSeparatedByString:@" "]);
1257 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1259 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1260 withObject:[NSArray arrayWithObjects:
1261 [NSString stringWithUTF8String:error.c_str()],
1268 virtual bool Pulse(pkgAcquire *Owner) {
1269 bool value = pkgAcquireStatus::Pulse(Owner);
1272 double(CurrentBytes + CurrentItems) /
1273 double(TotalBytes + TotalItems)
1276 [delegate_ setProgressPercent:percent];
1277 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1280 virtual void Start() {
1281 [delegate_ startProgress];
1284 virtual void Stop() {
1288 /* Progress Delegation {{{ */
1293 _transient id<ProgressDelegate> delegate_;
1297 virtual void Update() {
1298 /*if (abs(Percent - percent_) > 2)
1299 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1303 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1304 [delegate_ setProgressPercent:(Percent / 100)];*/
1314 void setDelegate(id delegate) {
1315 delegate_ = delegate;
1318 id getDelegate() const {
1322 virtual void Done() {
1324 //[delegate_ setProgressPercent:1];
1329 /* Database Interface {{{ */
1330 typedef std::map< unsigned long, _H<Source> > SourceMap;
1332 @interface Database : NSObject {
1338 pkgCacheFile cache_;
1339 pkgDepCache::Policy *policy_;
1340 pkgRecords *records_;
1341 pkgProblemResolver *resolver_;
1342 pkgAcquire *fetcher_;
1344 SPtr<pkgPackageManager> manager_;
1345 pkgSourceList *list_;
1348 CFMutableArrayRef packages_;
1350 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1359 + (Database *) sharedInstance;
1362 - (void) _readCydia:(NSNumber *)fd;
1363 - (void) _readStatus:(NSNumber *)fd;
1364 - (void) _readOutput:(NSNumber *)fd;
1368 - (Package *) packageWithName:(NSString *)name;
1370 - (pkgCacheFile &) cache;
1371 - (pkgDepCache::Policy *) policy;
1372 - (pkgRecords *) records;
1373 - (pkgProblemResolver *) resolver;
1374 - (pkgAcquire &) fetcher;
1375 - (pkgSourceList &) list;
1376 - (NSArray *) packages;
1377 - (NSArray *) sources;
1378 - (void) reloadData;
1386 - (void) updateWithStatus:(Status &)status;
1388 - (void) setDelegate:(id)delegate;
1389 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1392 /* Delegate Helpers {{{ */
1393 @implementation NSObject (ProgressDelegate)
1395 - (void) _setProgressErrorPackage:(NSArray *)args {
1396 [self performSelector:@selector(setProgressError:forPackage:)
1397 withObject:[args objectAtIndex:0]
1398 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1402 - (void) _setProgressErrorTitle:(NSArray *)args {
1403 [self performSelector:@selector(setProgressError:withTitle:)
1404 withObject:[args objectAtIndex:0]
1405 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1409 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1410 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1411 withObject:[NSArray arrayWithObjects:error, title, nil]
1416 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1417 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1419 [self performSelector:@selector(setProgressError:withTitle:)
1421 withObject:(package == nil ? id : [package name])
1428 // Cytore Definitions {{{
1429 struct PackageValue :
1432 Cytore::Offset<PackageValue> next_;
1434 uint32_t index_ : 23;
1435 uint32_t subscribed_ : 1;
1452 Cytore::Offset<PackageValue> packages_[1 << 16];
1455 static Cytore::File<MetaValue> MetaFile_;
1457 // Cytore Helper Functions {{{
1458 static PackageValue *PackageFind(const char *name, size_t length) {
1459 SplitHash nhash = { hashlittle(name, length) };
1461 PackageValue *metadata;
1463 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1464 offset: if (offset->IsNull()) {
1465 *offset = MetaFile_.New<PackageValue>(length + 1);
1466 metadata = &MetaFile_.Get(*offset);
1468 memcpy(metadata->name_, name, length + 1);
1469 metadata->nhash_ = nhash.u16[1];
1471 metadata = &MetaFile_.Get(*offset);
1473 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1474 offset = &metadata->next_;
1482 static void PackageImport(const void *key, const void *value, void *context) {
1484 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1485 NSLog(@"failed to import package %@", key);
1489 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1490 NSDictionary *package((NSDictionary *) value);
1492 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1493 if ([subscribed boolValue])
1494 metadata->subscribed_ = true;
1496 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1497 time_t time([date timeIntervalSince1970]);
1498 if (metadata->first_ > time || metadata->first_ == 0)
1499 metadata->first_ = time;
1502 bool versioned(false);
1504 if (NSDate *date = [package objectForKey:@"LastSeen"]) {
1505 time_t time([date timeIntervalSince1970]);
1506 if (metadata->last_ < time || metadata->last_ == 0) {
1507 metadata->last_ = time;
1510 } else if (metadata->last_ == 0) {
1511 metadata->last_ = metadata->first_;
1512 if (metadata->version_[0] == '\0')
1517 if (NSString *version = [package objectForKey:@"LastVersion"])
1518 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1519 size_t length(strlen(buffer));
1520 uint16_t vhash(hashlittle(buffer, length));
1522 size_t capped(std::min<size_t>(8, length));
1523 char *latest(buffer + length - capped);
1525 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1526 metadata->vhash_ = vhash;
1531 /* Source Class {{{ */
1532 @interface Source : NSObject {
1533 CYString depiction_;
1534 CYString description_;
1540 CYString distribution_;
1545 NSString *authority_;
1547 CYString defaultIcon_;
1549 NSDictionary *record_;
1553 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1555 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1557 - (NSString *) depictionForPackage:(NSString *)package;
1558 - (NSString *) supportForPackage:(NSString *)package;
1560 - (NSDictionary *) record;
1564 - (NSString *) distribution;
1565 - (NSString *) type;
1567 - (NSString *) host;
1569 - (NSString *) name;
1570 - (NSString *) description;
1571 - (NSString *) label;
1572 - (NSString *) origin;
1573 - (NSString *) version;
1575 - (NSString *) defaultIcon;
1579 @implementation Source
1583 distribution_.clear();
1586 description_.clear();
1592 defaultIcon_.clear();
1594 if (record_ != nil) {
1604 if (authority_ != nil) {
1605 [authority_ release];
1611 // XXX: this is a very inefficient way to call these deconstructors
1616 + (NSArray *) _attributeKeys {
1617 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1620 - (NSArray *) attributeKeys {
1621 return [[self class] _attributeKeys];
1624 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1625 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1628 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1631 trusted_ = index->IsTrusted();
1633 uri_.set(pool, index->GetURI());
1634 distribution_.set(pool, index->GetDist());
1635 type_.set(pool, index->GetType());
1637 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1638 if (dindex != NULL) {
1640 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1643 pkgTagFile tags(&fd);
1645 pkgTagSection section;
1652 {"default-icon", &defaultIcon_},
1653 {"depiction", &depiction_},
1654 {"description", &description_},
1656 {"origin", &origin_},
1657 {"support", &support_},
1658 {"version", &version_},
1661 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1662 const char *start, *end;
1664 if (section.Find(names[i].name_, start, end)) {
1665 CYString &value(*names[i].value_);
1666 value.set(pool, start, end - start);
1672 record_ = [Sources_ objectForKey:[self key]];
1674 record_ = [record_ retain];
1676 NSURL *url([NSURL URLWithString:uri_]);
1680 host_ = [[host_ lowercaseString] retain];
1685 authority_ = [url path];
1687 if (authority_ != nil)
1688 authority_ = [authority_ retain];
1691 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1692 if ((self = [super init]) != nil) {
1693 [self setMetaIndex:index inPool:pool];
1697 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1698 NSDictionary *lhr = [self record];
1699 NSDictionary *rhr = [source record];
1702 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1704 NSString *lhs = [self name];
1705 NSString *rhs = [source name];
1707 if ([lhs length] != 0 && [rhs length] != 0) {
1708 unichar lhc = [lhs characterAtIndex:0];
1709 unichar rhc = [rhs characterAtIndex:0];
1711 if (isalpha(lhc) && !isalpha(rhc))
1712 return NSOrderedAscending;
1713 else if (!isalpha(lhc) && isalpha(rhc))
1714 return NSOrderedDescending;
1717 return [lhs compare:rhs options:LaxCompareOptions_];
1720 - (NSString *) depictionForPackage:(NSString *)package {
1721 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1724 - (NSString *) supportForPackage:(NSString *)package {
1725 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1728 - (NSDictionary *) record {
1736 - (NSString *) uri {
1740 - (NSString *) distribution {
1741 return distribution_;
1744 - (NSString *) type {
1748 - (NSString *) key {
1749 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1752 - (NSString *) host {
1756 - (NSString *) name {
1757 return origin_.empty() ? authority_ : origin_;
1760 - (NSString *) description {
1761 return description_;
1764 - (NSString *) label {
1765 return label_.empty() ? authority_ : label_;
1768 - (NSString *) origin {
1772 - (NSString *) version {
1776 - (NSString *) defaultIcon {
1777 return defaultIcon_;
1782 /* Relationship Class {{{ */
1783 @interface Relationship : NSObject {
1788 - (NSString *) type;
1790 - (NSString *) name;
1794 @implementation Relationship
1802 - (NSString *) type {
1810 - (NSString *) name {
1817 /* Package Class {{{ */
1818 struct ParsedPackage {
1823 CYString depiction_;
1833 @interface Package : NSObject {
1835 uint32_t essential_ : 1;
1836 uint32_t obsolete_ : 1;
1837 uint32_t ignored_ : 1;
1841 _transient Database *database_;
1843 pkgCache::VerIterator version_;
1844 pkgCache::PkgIterator iterator_;
1845 pkgCache::VerFileIterator file_;
1851 CYString installed_;
1854 _transient NSString *section$_;
1858 PackageValue *metadata_;
1859 ParsedPackage *parsed_;
1861 NSMutableArray *tags_;
1865 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1866 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1868 - (pkgCache::PkgIterator) iterator;
1871 - (NSString *) section;
1872 - (NSString *) simpleSection;
1874 - (NSString *) longSection;
1875 - (NSString *) shortSection;
1879 - (Address *) maintainer;
1881 - (NSString *) longDescription;
1882 - (NSString *) shortDescription;
1885 - (PackageValue *) metadata;
1888 - (bool) subscribed;
1889 - (bool) setSubscribed:(bool)subscribed;
1893 - (NSString *) latest;
1894 - (NSString *) installed;
1895 - (BOOL) uninstalled;
1898 - (BOOL) upgradableAndEssential:(BOOL)essential;
1901 - (BOOL) unfiltered;
1905 - (BOOL) halfConfigured;
1906 - (BOOL) halfInstalled;
1908 - (NSString *) mode;
1911 - (NSString *) name;
1913 - (NSString *) homepage;
1914 - (NSString *) depiction;
1915 - (Address *) author;
1917 - (NSString *) support;
1919 - (NSArray *) files;
1920 - (NSArray *) warnings;
1921 - (NSArray *) applications;
1923 - (Source *) source;
1924 - (NSString *) role;
1926 - (BOOL) matches:(NSString *)text;
1928 - (bool) hasSupportingRole;
1929 - (BOOL) hasTag:(NSString *)tag;
1930 - (NSString *) primaryPurpose;
1931 - (NSArray *) purposes;
1932 - (bool) isCommercial;
1934 - (void) setIndex:(size_t)index;
1936 - (CYString &) cyname;
1938 - (uint32_t) compareBySection:(NSArray *)sections;
1943 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1944 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1945 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1946 - (bool) isVisibleInSection:(NSString *)section;
1947 - (bool) isVisibleInSource:(Source *)source;
1951 uint32_t PackageChangesRadix(Package *self, void *) {
1956 uint32_t timestamp : 30;
1957 uint32_t ignored : 1;
1958 uint32_t upgradable : 1;
1962 bool upgradable([self upgradableAndEssential:YES]);
1963 value.bits.upgradable = upgradable ? 1 : 0;
1966 value.bits.timestamp = 0;
1967 value.bits.ignored = [self ignored] ? 0 : 1;
1968 value.bits.upgradable = 1;
1970 value.bits.timestamp = [self seen] >> 2;
1971 value.bits.ignored = 0;
1972 value.bits.upgradable = 0;
1975 return _not(uint32_t) - value.key;
1978 uint32_t PackagePrefixRadix(Package *self, void *context) {
1979 size_t offset(reinterpret_cast<size_t>(context));
1980 CYString &name([self cyname]);
1982 size_t size(name.size());
1985 char *text(name.data());
1988 if (!isdigit(text[0]))
1992 while (size != digits && isdigit(text[digits]))
2000 if (offset == 0 && zeros != 0) {
2001 memset(data, '0', zeros);
2002 memcpy(data + zeros, text, 4 - zeros);
2004 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2005 if (size <= offset - zeros)
2008 text += offset - zeros;
2009 size -= offset - zeros;
2012 memcpy(data, text, 4);
2014 memcpy(data, text, size);
2015 memset(data + size, 0, 4 - size);
2018 for (size_t i(0); i != 4; ++i)
2019 if (isalpha(data[i]))
2027 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2029 /* XXX: ntohl may be more honest */
2030 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2033 CYString &(*PackageName)(Package *self, SEL sel);
2035 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2036 _profile(PackageNameCompare)
2037 CYString &lhi(PackageName(lhs, @selector(cyname)));
2038 CYString &rhi(PackageName(rhs, @selector(cyname)));
2039 CFStringRef lhn(lhi), rhn(rhi);
2042 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2043 else if (rhn == NULL)
2044 return NSOrderedDescending;
2046 _profile(PackageNameCompare$NumbersLast)
2047 if (!lhi.empty() && !rhi.empty()) {
2048 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2049 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2050 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2051 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2052 return lha ? NSOrderedAscending : NSOrderedDescending;
2056 CFIndex length = CFStringGetLength(lhn);
2058 _profile(PackageNameCompare$Compare)
2059 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2064 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2065 return PackageNameCompare(*lhs, *rhs, context);
2068 struct PackageNameOrdering :
2069 std::binary_function<Package *, Package *, bool>
2071 _finline bool operator ()(Package *lhs, Package *rhs) const {
2072 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2076 @implementation Package
2078 - (NSString *) description {
2079 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2083 if (parsed_ != NULL)
2097 + (NSString *) webScriptNameForSelector:(SEL)selector {
2098 if (selector == @selector(hasTag:))
2104 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2105 return [self webScriptNameForSelector:selector] == nil;
2108 + (NSArray *) _attributeKeys {
2109 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];
2112 - (NSArray *) attributeKeys {
2113 return [[self class] _attributeKeys];
2116 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2117 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2121 if (parsed_ != NULL)
2123 @synchronized (database_) {
2124 if ([database_ era] != era_ || file_.end())
2127 ParsedPackage *parsed(new ParsedPackage);
2130 _profile(Package$parse)
2131 pkgRecords::Parser *parser;
2133 _profile(Package$parse$Lookup)
2134 parser = &[database_ records]->Lookup(file_);
2139 _profile(Package$parse$Find)
2144 {"icon", &parsed->icon_},
2145 {"depiction", &parsed->depiction_},
2146 {"homepage", &parsed->homepage_},
2147 {"website", &website},
2148 {"bugs", &parsed->bugs_},
2149 {"support", &parsed->support_},
2150 {"sponsor", &parsed->sponsor_},
2151 {"author", &parsed->author_},
2154 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2155 const char *start, *end;
2157 if (parser->Find(names[i].name_, start, end)) {
2158 CYString &value(*names[i].value_);
2159 _profile(Package$parse$Value)
2160 value.set(pool_, start, end - start);
2166 _profile(Package$parse$Tagline)
2167 const char *start, *end;
2168 if (parser->ShortDesc(start, end)) {
2169 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2172 while (stop != start && stop[-1] == '\r')
2174 parsed->tagline_.set(pool_, start, stop - start);
2178 _profile(Package$parse$Retain)
2179 if (parsed->homepage_.empty())
2180 parsed->homepage_ = website;
2181 if (parsed->homepage_ == parsed->depiction_)
2182 parsed->homepage_.clear();
2187 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2188 if ((self = [super init]) != nil) {
2189 _profile(Package$initWithVersion)
2192 database_ = database;
2193 era_ = [database era];
2197 pkgCache::PkgIterator iterator(version.ParentPkg());
2198 iterator_ = iterator;
2200 _profile(Package$initWithVersion$Version)
2201 if (!version_.end())
2202 file_ = version_.FileList();
2204 pkgCache &cache([database_ cache]);
2205 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2209 _profile(Package$initWithVersion$Cache)
2210 name_.set(NULL, iterator.Display());
2212 latest_.set(NULL, StripVersion_(version_.VerStr()));
2214 pkgCache::VerIterator current(iterator.CurrentVer());
2216 installed_.set(NULL, StripVersion_(current.VerStr()));
2219 _profile(Package$initWithVersion$Tags)
2220 pkgCache::TagIterator tag(iterator.TagList());
2222 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2224 const char *name(tag.Name());
2225 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2227 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2228 role_ = (NSString *) CYStringCreate(name + 6);
2230 if (strncmp(name, "cydia::", 7) == 0) {
2231 if (strcmp(name + 7, "essential") == 0)
2233 else if (strcmp(name + 7, "obsolete") == 0)
2238 } while (!tag.end());
2242 _profile(Package$initWithVersion$Metadata)
2243 const char *mixed(iterator.Name());
2244 size_t size(strlen(mixed));
2245 char lower[size + 1];
2247 for (size_t i(0); i != size; ++i)
2248 lower[i] = mixed[i] | 0x20;
2251 PackageValue *metadata(PackageFind(lower, size));
2252 metadata_ = metadata;
2254 id_.set(NULL, metadata->name_, size);
2256 const char *latest(version_.VerStr());
2257 size_t length(strlen(latest));
2259 uint16_t vhash(hashlittle(latest, length));
2261 size_t capped(std::min<size_t>(8, length));
2262 latest = latest + length - capped;
2264 if (metadata->first_ == 0)
2265 metadata->first_ = now_;
2267 if (metadata->last_ == 0)
2268 metadata->last_ = metadata->first_;
2270 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2271 if (metadata->version_[0] != '\0')
2272 metadata->last_ = now_;
2273 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2274 metadata->vhash_ = vhash;
2278 _profile(Package$initWithVersion$Section)
2279 section_.set(NULL, iterator.Section());
2282 _profile(Package$initWithVersion$Flags)
2283 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2284 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2289 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2290 pkgCache::VerIterator version;
2292 _profile(Package$packageWithIterator$GetCandidateVer)
2293 version = [database policy]->GetCandidateVer(iterator);
2301 _profile(Package$packageWithIterator$Allocate)
2302 package = [Package allocWithZone:zone];
2305 _profile(Package$packageWithIterator$Initialize)
2307 initWithVersion:version
2314 _profile(Package$packageWithIterator$Autorelease)
2315 package = [package autorelease];
2321 - (pkgCache::PkgIterator) iterator {
2325 - (NSString *) section {
2326 if (section$_ == nil) {
2327 if (section_.empty())
2330 _profile(Package$section)
2331 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2332 NSString *name(section_);
2333 section$_ = [SectionMap_ objectForKey:name] ?: name;
2338 - (NSString *) simpleSection {
2339 if (NSString *section = [self section])
2340 return Simplify(section);
2345 - (NSString *) longSection {
2346 return LocalizeSection([self section]);
2349 - (NSString *) shortSection {
2350 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2353 - (NSString *) uri {
2356 pkgIndexFile *index;
2357 pkgCache::PkgFileIterator file(file_.File());
2358 if (![database_ list].FindIndex(file, index))
2360 return [NSString stringWithUTF8String:iterator_->Path];
2361 //return [NSString stringWithUTF8String:file.Site()];
2362 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2366 - (Address *) maintainer {
2367 @synchronized (database_) {
2368 if ([database_ era] != era_ || file_.end())
2371 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2372 const std::string &maintainer(parser->Maintainer());
2373 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2377 @synchronized (database_) {
2378 if ([database_ era] != era_ || version_.end())
2381 return version_->InstalledSize;
2384 - (NSString *) longDescription {
2385 @synchronized (database_) {
2386 if ([database_ era] != era_ || file_.end())
2389 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2390 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2392 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2393 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2394 if ([lines count] < 2)
2397 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2398 for (size_t i(1), e([lines count]); i != e; ++i) {
2399 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2400 [trimmed addObject:trim];
2403 return [trimmed componentsJoinedByString:@"\n"];
2406 - (NSString *) shortDescription {
2407 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2411 _profile(Package$index)
2412 CFStringRef name((CFStringRef) [self name]);
2413 if (CFStringGetLength(name) == 0)
2415 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2416 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2418 return toupper(character);
2422 - (PackageValue *) metadata {
2427 PackageValue *metadata([self metadata]);
2428 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2431 - (bool) subscribed {
2432 return [self metadata]->subscribed_;
2435 - (bool) setSubscribed:(bool)subscribed {
2436 PackageValue *metadata([self metadata]);
2437 if (metadata->subscribed_ == subscribed)
2439 metadata->subscribed_ = subscribed;
2447 - (NSString *) latest {
2451 - (NSString *) installed {
2455 - (BOOL) uninstalled {
2456 return installed_.empty();
2460 return !version_.end();
2463 - (BOOL) upgradableAndEssential:(BOOL)essential {
2464 _profile(Package$upgradableAndEssential)
2465 pkgCache::VerIterator current(iterator_.CurrentVer());
2467 return essential && essential_;
2469 return !version_.end() && version_ != current;
2473 - (BOOL) essential {
2478 return [database_ cache][iterator_].InstBroken();
2481 - (BOOL) unfiltered {
2482 _profile(Package$unfiltered$obsolete)
2487 _profile(Package$unfiltered$hasSupportingRole)
2488 if (![self hasSupportingRole])
2496 if (![self unfiltered])
2499 NSString *section([self section]);
2501 _profile(Package$visible$isSectionVisible)
2502 if (section != nil && !isSectionVisible(section))
2510 unsigned char current(iterator_->CurrentState);
2511 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2514 - (BOOL) halfConfigured {
2515 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2518 - (BOOL) halfInstalled {
2519 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2523 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2524 return state.Mode != pkgDepCache::ModeKeep;
2527 - (NSString *) mode {
2528 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2530 switch (state.Mode) {
2531 case pkgDepCache::ModeDelete:
2532 if ((state.iFlags & pkgDepCache::Purge) != 0)
2536 case pkgDepCache::ModeKeep:
2537 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2538 return @"REINSTALL";
2539 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2543 case pkgDepCache::ModeInstall:
2544 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2545 return @"REINSTALL";
2546 else*/ switch (state.Status) {
2548 return @"DOWNGRADE";
2554 return @"NEW_INSTALL";
2565 - (NSString *) name {
2566 return name_.empty() ? id_ : name_;
2569 - (UIImage *) icon {
2570 NSString *section = [self simpleSection];
2573 if (parsed_ != NULL)
2574 if (NSString *href = parsed_->icon_)
2575 if ([href hasPrefix:@"file:///"])
2576 // XXX: correct escaping
2577 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2578 if (icon == nil) if (section != nil)
2579 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2580 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2581 if ([dicon hasPrefix:@"file:///"])
2582 // XXX: correct escaping
2583 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2585 icon = [UIImage applicationImageNamed:@"unknown.png"];
2589 - (NSString *) homepage {
2590 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2593 - (NSString *) depiction {
2594 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2597 - (Address *) sponsor {
2598 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2601 - (Address *) author {
2602 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2605 - (NSString *) support {
2606 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2609 - (NSArray *) files {
2610 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2611 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2614 fin.open([path UTF8String]);
2619 while (std::getline(fin, line))
2620 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2625 - (NSArray *) warnings {
2626 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2627 const char *name(iterator_.Name());
2629 size_t length(strlen(name));
2630 if (length < 2) invalid:
2631 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2632 else for (size_t i(0); i != length; ++i)
2634 /* XXX: technically this is not allowed */
2635 (name[i] < 'A' || name[i] > 'Z') &&
2636 (name[i] < 'a' || name[i] > 'z') &&
2637 (name[i] < '0' || name[i] > '9') &&
2638 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2641 if (strcmp(name, "cydia") != 0) {
2644 bool _private = false;
2647 bool repository = [[self section] isEqualToString:@"Repositories"];
2649 if (NSArray *files = [self files])
2650 for (NSString *file in files)
2651 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2653 else if (!user && [file isEqualToString:@"/User"])
2655 else if (!_private && [file isEqualToString:@"/private"])
2657 else if (!stash && [file isEqualToString:@"/var/stash"])
2660 /* XXX: this is not sensitive enough. only some folders are valid. */
2661 if (cydia && !repository)
2662 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2664 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2666 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2668 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2671 return [warnings count] == 0 ? nil : warnings;
2674 - (NSArray *) applications {
2675 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2677 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2679 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2680 if (NSArray *files = [self files])
2681 for (NSString *file in files)
2682 if (application_r(file)) {
2683 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2684 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2685 if ([id isEqualToString:me])
2688 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2690 display = application_r[1];
2692 NSString *bundle([file stringByDeletingLastPathComponent]);
2693 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2694 if (icon == nil || [icon length] == 0)
2696 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2698 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2699 [applications addObject:application];
2701 [application addObject:id];
2702 [application addObject:display];
2703 [application addObject:url];
2706 return [applications count] == 0 ? nil : applications;
2709 - (Source *) source {
2710 if (source_ == nil) {
2711 @synchronized (database_) {
2712 if ([database_ era] != era_ || file_.end())
2713 source_ = (Source *) [NSNull null];
2715 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2719 return source_ == (Source *) [NSNull null] ? nil : source_;
2722 - (NSString *) role {
2726 - (BOOL) matches:(NSString *)text {
2732 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2733 if (range.location != NSNotFound)
2736 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2737 if (range.location != NSNotFound)
2740 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2741 if (range.location != NSNotFound)
2747 - (bool) hasSupportingRole {
2750 if ([role_ isEqualToString:@"enduser"])
2752 if ([Role_ isEqualToString:@"User"])
2754 if ([role_ isEqualToString:@"hacker"])
2756 if ([Role_ isEqualToString:@"Hacker"])
2758 if ([role_ isEqualToString:@"developer"])
2760 if ([Role_ isEqualToString:@"Developer"])
2765 - (BOOL) hasTag:(NSString *)tag {
2766 return tags_ == nil ? NO : [tags_ containsObject:tag];
2769 - (NSString *) primaryPurpose {
2770 for (NSString *tag in tags_)
2771 if ([tag hasPrefix:@"purpose::"])
2772 return [tag substringFromIndex:9];
2776 - (NSArray *) purposes {
2777 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2778 for (NSString *tag in tags_)
2779 if ([tag hasPrefix:@"purpose::"])
2780 [purposes addObject:[tag substringFromIndex:9]];
2781 return [purposes count] == 0 ? nil : purposes;
2784 - (bool) isCommercial {
2785 return [self hasTag:@"cydia::commercial"];
2788 - (void) setIndex:(size_t)index {
2789 if (metadata_->index_ != index)
2790 metadata_->index_ = index;
2793 - (CYString &) cyname {
2794 return name_.empty() ? id_ : name_;
2797 - (uint32_t) compareBySection:(NSArray *)sections {
2798 NSString *section([self section]);
2799 for (size_t i(0), e([sections count]); i != e; ++i) {
2800 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2804 return _not(uint32_t);
2808 @synchronized (database_) {
2809 pkgProblemResolver *resolver = [database_ resolver];
2810 resolver->Clear(iterator_);
2812 pkgCacheFile &cache([database_ cache]);
2813 cache->SetReInstall(iterator_, false);
2814 cache->MarkKeep(iterator_, false);
2818 @synchronized (database_) {
2819 pkgProblemResolver *resolver = [database_ resolver];
2820 resolver->Clear(iterator_);
2821 resolver->Protect(iterator_);
2823 pkgCacheFile &cache([database_ cache]);
2824 cache->SetReInstall(iterator_, false);
2825 cache->MarkInstall(iterator_, false);
2827 pkgDepCache::StateCache &state((*cache)[iterator_]);
2828 if (!state.Install())
2829 cache->SetReInstall(iterator_, true);
2833 @synchronized (database_) {
2834 pkgProblemResolver *resolver = [database_ resolver];
2835 resolver->Clear(iterator_);
2836 resolver->Remove(iterator_);
2837 resolver->Protect(iterator_);
2839 pkgCacheFile &cache([database_ cache]);
2840 cache->SetReInstall(iterator_, false);
2841 cache->MarkDelete(iterator_, true);
2844 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2845 _profile(Package$isUnfilteredAndSearchedForBy)
2848 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2849 value &= [self unfiltered];
2852 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2853 value &= [self matches:search];
2860 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2861 if ([search length] == 0)
2864 _profile(Package$isUnfilteredAndSelectedForBy)
2867 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2868 value &= [self unfiltered];
2871 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2872 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2879 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2880 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2883 - (bool) isVisibleInSection:(NSString *)name {
2884 NSString *section([self section]);
2888 section == nil && [name length] == 0 ||
2889 [name isEqualToString:section]
2890 ) && [self visible];
2893 - (bool) isVisibleInSource:(Source *)source {
2894 return [self source] == source && [self visible];
2899 /* Section Class {{{ */
2900 @interface Section : NSObject {
2905 NSString *localized_;
2908 - (NSComparisonResult) compareByLocalized:(Section *)section;
2909 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2910 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2911 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2912 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2913 - (NSString *) name;
2920 - (void) addToCount;
2922 - (void) setCount:(size_t)count;
2923 - (NSString *) localized;
2927 @implementation Section
2931 if (localized_ != nil)
2932 [localized_ release];
2936 - (NSComparisonResult) compareByLocalized:(Section *)section {
2937 NSString *lhs(localized_);
2938 NSString *rhs([section localized]);
2940 /*if ([lhs length] != 0 && [rhs length] != 0) {
2941 unichar lhc = [lhs characterAtIndex:0];
2942 unichar rhc = [rhs characterAtIndex:0];
2944 if (isalpha(lhc) && !isalpha(rhc))
2945 return NSOrderedAscending;
2946 else if (!isalpha(lhc) && isalpha(rhc))
2947 return NSOrderedDescending;
2950 return [lhs compare:rhs options:LaxCompareOptions_];
2953 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2954 if ((self = [self initWithName:name localize:NO]) != nil) {
2955 if (localized != nil)
2956 localized_ = [localized retain];
2960 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2961 return [self initWithName:name row:0 localize:localize];
2964 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2965 if ((self = [super init]) != nil) {
2966 name_ = [name retain];
2970 localized_ = [LocalizeSection(name_) retain];
2974 /* XXX: localize the index thingees */
2975 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2976 if ((self = [super init]) != nil) {
2977 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2983 - (NSString *) name {
3003 - (void) addToCount {
3007 - (void) setCount:(size_t)count {
3011 - (NSString *) localized {
3018 static NSString *Colon_;
3019 static NSString *Elision_;
3020 static NSString *Error_;
3021 static NSString *Warning_;
3023 /* Database Implementation {{{ */
3024 @implementation Database
3026 + (Database *) sharedInstance {
3027 static Database *instance;
3028 if (instance == nil)
3029 instance = [[Database alloc] init];
3037 - (void) releasePackages {
3038 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3039 CFArrayRemoveAllValues(packages_);
3043 // XXX: actually implement this thing
3045 [self releasePackages];
3046 apr_pool_destroy(pool_);
3047 NSRecycleZone(zone_);
3051 - (void) _readCydia:(NSNumber *)fd { _pooled
3052 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3053 std::istream is(&ib);
3056 static Pcre finish_r("^finish:([^:]*)$");
3058 while (std::getline(is, line)) {
3059 const char *data(line.c_str());
3060 size_t size = line.size();
3061 lprintf("C:%s\n", data);
3063 if (finish_r(data, size)) {
3064 NSString *finish = finish_r[1];
3065 int index = [Finishes_ indexOfObject:finish];
3066 if (index != INT_MAX && index > Finish_)
3074 - (void) _readStatus:(NSNumber *)fd { _pooled
3075 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3076 std::istream is(&ib);
3079 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3080 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3082 while (std::getline(is, line)) {
3083 const char *data(line.c_str());
3084 size_t size(line.size());
3085 lprintf("S:%s\n", data);
3087 if (conffile_r(data, size)) {
3088 [delegate_ setConfigurationData:conffile_r[1]];
3089 } else if (strncmp(data, "status: ", 8) == 0) {
3090 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3091 [delegate_ setProgressTitle:string];
3092 } else if (pmstatus_r(data, size)) {
3093 std::string type([pmstatus_r[1] UTF8String]);
3094 NSString *id = pmstatus_r[2];
3096 float percent([pmstatus_r[3] floatValue]);
3097 [delegate_ setProgressPercent:(percent / 100)];
3099 NSString *string = pmstatus_r[4];
3101 if (type == "pmerror")
3102 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3103 withObject:[NSArray arrayWithObjects:string, id, nil]
3106 else if (type == "pmstatus") {
3107 [delegate_ setProgressTitle:string];
3108 } else if (type == "pmconffile")
3109 [delegate_ setConfigurationData:string];
3111 lprintf("E:unknown pmstatus\n");
3113 lprintf("E:unknown status\n");
3119 - (void) _readOutput:(NSNumber *)fd { _pooled
3120 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3121 std::istream is(&ib);
3124 while (std::getline(is, line)) {
3125 lprintf("O:%s\n", line.c_str());
3126 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3136 - (Package *) packageWithName:(NSString *)name {
3137 @synchronized (self) {
3138 if (static_cast<pkgDepCache *>(cache_) == NULL)
3140 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3141 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3145 if ((self = [super init]) != nil) {
3152 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3153 apr_pool_create(&pool_, NULL);
3155 size_t capacity(MetaFile_->active_);
3161 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3165 _assert(pipe(fds) != -1);
3168 _config->Set("APT::Keep-Fds::", cydiafd_);
3169 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3172 detachNewThreadSelector:@selector(_readCydia:)
3174 withObject:[NSNumber numberWithInt:fds[0]]
3177 _assert(pipe(fds) != -1);
3181 detachNewThreadSelector:@selector(_readStatus:)
3183 withObject:[NSNumber numberWithInt:fds[0]]
3186 _assert(pipe(fds) != -1);
3187 _assert(dup2(fds[0], 0) != -1);
3188 _assert(close(fds[0]) != -1);
3190 input_ = fdopen(fds[1], "a");
3192 _assert(pipe(fds) != -1);
3193 _assert(dup2(fds[1], 1) != -1);
3194 _assert(close(fds[1]) != -1);
3197 detachNewThreadSelector:@selector(_readOutput:)
3199 withObject:[NSNumber numberWithInt:fds[0]]
3204 - (pkgCacheFile &) cache {
3208 - (pkgDepCache::Policy *) policy {
3212 - (pkgRecords *) records {
3216 - (pkgProblemResolver *) resolver {
3220 - (pkgAcquire &) fetcher {
3224 - (pkgSourceList &) list {
3228 - (NSArray *) packages {
3229 return (NSArray *) packages_;
3232 - (NSArray *) sources {
3233 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3234 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3235 [sources addObject:i->second];
3239 - (NSArray *) issues {
3240 if (cache_->BrokenCount() == 0)
3243 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3245 for (Package *package in [self packages]) {
3246 if (![package broken])
3248 pkgCache::PkgIterator pkg([package iterator]);
3250 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3251 [entry addObject:[package name]];
3252 [issues addObject:entry];
3254 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3258 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3259 pkgCache::DepIterator start;
3260 pkgCache::DepIterator end;
3261 dep.GlobOr(start, end); // ++dep
3263 if (!cache_->IsImportantDep(end))
3265 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3268 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3269 [entry addObject:failure];
3270 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3272 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3273 if (Package *package = [self packageWithName:name])
3274 name = [package name];
3275 [failure addObject:name];
3277 pkgCache::PkgIterator target(start.TargetPkg());
3278 if (target->ProvidesList != 0)
3279 [failure addObject:@"?"];
3281 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3283 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3284 else if (!cache_[target].CandidateVerIter(cache_).end())
3285 [failure addObject:@"-"];
3286 else if (target->ProvidesList == 0)
3287 [failure addObject:@"!"];
3289 [failure addObject:@"%"];
3293 if (start.TargetVer() != 0)
3294 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3305 - (bool) popErrorWithTitle:(NSString *)title {
3307 std::string message;
3309 while (!_error->empty()) {
3311 bool warning(!_error->PopMessage(error));
3315 size_t size(error.size());
3316 if (size == 0 || error[size - 1] != '\n')
3318 error.resize(size - 1);
3320 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3322 if (!message.empty())
3327 if (fatal && !message.empty())
3328 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3333 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3334 return [self popErrorWithTitle:title] || !success;
3337 - (void) reloadData { CYPoolStart() {
3338 @synchronized (self) {
3341 [self releasePackages];
3362 apr_pool_clear(pool_);
3364 NSRecycleZone(zone_);
3365 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3367 int chk(creat("/tmp/cydia.chk", 0644));
3371 NSString *title(UCLocalize("DATABASE"));
3374 if (!cache_.Open(progress_, true)) { pop:
3376 bool warning(!_error->PopMessage(error));
3377 lprintf("cache_.Open():[%s]\n", error.c_str());
3379 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3380 [delegate_ repairWithSelector:@selector(configure)];
3381 else if (error == "The package lists or status file could not be parsed or opened.")
3382 [delegate_ repairWithSelector:@selector(update)];
3383 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3384 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3385 // else if (error == "The list of sources could not be read.")
3387 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3396 unlink("/tmp/cydia.chk");
3398 now_ = [[NSDate date] timeIntervalSince1970];
3400 policy_ = new pkgDepCache::Policy();
3401 records_ = new pkgRecords(cache_);
3402 resolver_ = new pkgProblemResolver(cache_);
3403 fetcher_ = new pkgAcquire(&status_);
3406 list_ = new pkgSourceList();
3407 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3410 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3411 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3415 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3418 if (cache_->BrokenCount() != 0) {
3419 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3422 if (cache_->BrokenCount() != 0) {
3423 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3427 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3431 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3432 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3433 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3434 // XXX: this could be more intelligent
3435 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3436 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3438 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3443 /*std::vector<Package *> packages;
3444 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3445 [packages_ release];
3450 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3451 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3452 //packages.push_back(package);
3453 CFArrayAppendValue(packages_, [package retain]);
3457 /*if (packages.empty())
3458 packages_ = [[NSArray alloc] init];
3460 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3463 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3464 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3465 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3473 /*if (!packages.empty())
3474 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3475 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3477 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3479 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3481 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3485 size_t count(CFArrayGetCount(packages_));
3486 MetaFile_->active_ = count;
3488 for (size_t index(0); index != count; ++index)
3489 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3493 } } CYPoolEnd() _trace(); }
3496 @synchronized (self) {
3498 resolver_ = new pkgProblemResolver(cache_);
3500 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3501 if (!cache_[iterator].Keep()) {
3502 cache_->MarkKeep(iterator, false);
3503 cache_->SetReInstall(iterator, false);
3508 - (void) configure {
3509 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3510 system([dpkg UTF8String]);
3514 // XXX: I don't remember this condition
3519 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3521 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3523 if ([self popErrorWithTitle:title])
3527 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3530 public pkgArchiveCleaner
3533 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3538 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3545 fetcher_->Shutdown();
3547 pkgRecords records(cache_);
3549 lock_ = new FileFd();
3550 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3552 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3554 if ([self popErrorWithTitle:title])
3558 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3561 manager_ = (_system->CreatePM(cache_));
3562 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3569 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3571 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3573 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3575 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3576 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3579 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3584 [CydiaApp retainNetworkActivityIndicator];
3586 bool failed = false;
3587 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3588 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3590 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3593 std::string uri = (*item)->DescURI();
3594 std::string error = (*item)->ErrorText;
3596 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3599 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3600 withObject:[NSArray arrayWithObjects:
3601 [NSString stringWithUTF8String:error.c_str()],
3607 [CydiaApp releaseNetworkActivityIndicator];
3615 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3617 if (_error->PendingError()) {
3622 if (result == pkgPackageManager::Failed) {
3627 if (result != pkgPackageManager::Completed) {
3632 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3634 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3636 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3637 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3640 if (![before isEqualToArray:after])
3645 NSString *title(UCLocalize("UPGRADE"));
3646 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3652 [self updateWithStatus:status_];
3655 - (void) updateWithStatus:(Status &)status {
3656 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3657 NSString *title(UCLocalize("REFRESHING_DATA"));
3660 if (!list.ReadMainList())
3661 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3664 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3665 if ([self popErrorWithTitle:title])
3668 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3669 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3670 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3672 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3676 - (void) setDelegate:(id)delegate {
3677 delegate_ = delegate;
3678 status_.setDelegate(delegate);
3679 progress_.setDelegate(delegate);
3682 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3683 SourceMap::const_iterator i(sources_.find(file->ID));
3684 return i == sources_.end() ? nil : i->second;
3690 /* Confirmation Controller {{{ */
3691 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3692 if (!iterator.end())
3693 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3694 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3696 pkgCache::PkgIterator package(dep.TargetPkg());
3699 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3707 /* Web Scripting {{{ */
3708 @interface CydiaObject : NSObject {
3710 _transient id delegate_;
3713 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3716 @implementation CydiaObject
3719 [indirect_ release];
3723 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3724 if ((self = [super init]) != nil) {
3725 indirect_ = [indirect retain];
3729 - (void) setDelegate:(id)delegate {
3730 delegate_ = delegate;
3733 + (NSArray *) _attributeKeys {
3734 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3737 - (NSArray *) attributeKeys {
3738 return [[self class] _attributeKeys];
3741 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3742 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3745 - (NSString *) device {
3746 return [[UIDevice currentDevice] uniqueIdentifier];
3749 #if 0 // XXX: implement!
3750 - (NSString *) mac {
3751 if (![indirect_ promptForSensitive:@"Mac Address"])
3755 - (NSString *) serial {
3756 if (![indirect_ promptForSensitive:@"Serial #"])
3760 - (NSString *) firewire {
3761 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3765 - (NSString *) imei {
3766 if (![indirect_ promptForSensitive:@"IMEI"])
3771 + (NSString *) webScriptNameForSelector:(SEL)selector {
3772 if (selector == @selector(close))
3774 else if (selector == @selector(getInstalledPackages))
3775 return @"getInstalledPackages";
3776 else if (selector == @selector(getPackageById:))
3777 return @"getPackageById";
3778 else if (selector == @selector(installPackages:))
3779 return @"installPackages";
3780 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3781 return @"setButtonImage";
3782 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3783 return @"setButtonTitle";
3784 else if (selector == @selector(setPopupHook:))
3785 return @"setPopupHook";
3786 else if (selector == @selector(setSpecial:))
3787 return @"setSpecial";
3788 else if (selector == @selector(setToken:))
3790 else if (selector == @selector(setViewportWidth:))
3791 return @"setViewportWidth";
3792 else if (selector == @selector(supports:))
3794 else if (selector == @selector(stringWithFormat:arguments:))
3796 else if (selector == @selector(localizedStringForKey:value:table:))
3798 else if (selector == @selector(du:))
3800 else if (selector == @selector(statfs:))
3806 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3807 return [self webScriptNameForSelector:selector] == nil;
3810 - (BOOL) supports:(NSString *)feature {
3811 return [feature isEqualToString:@"window.open"];
3814 - (NSArray *) getInstalledPackages {
3815 NSArray *packages([[Database sharedInstance] packages]);
3816 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3817 for (Package *package in packages)
3818 if ([package installed] != nil)
3819 [installed addObject:package];
3823 - (Package *) getPackageById:(NSString *)id {
3824 Package *package([[Database sharedInstance] packageWithName:id]);
3829 - (NSArray *) statfs:(NSString *)path {
3832 if (path == nil || statfs([path UTF8String], &stat) == -1)
3835 return [NSArray arrayWithObjects:
3836 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3837 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3838 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3842 - (NSNumber *) du:(NSString *)path {
3843 NSNumber *value(nil);
3846 _assert(pipe(fds) != -1);
3848 pid_t pid(ExecFork());
3850 _assert(dup2(fds[1], 1) != -1);
3851 _assert(close(fds[0]) != -1);
3852 _assert(close(fds[1]) != -1);
3853 /* XXX: this should probably not use du */
3854 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3859 _assert(close(fds[1]) != -1);
3861 if (FILE *du = fdopen(fds[0], "r")) {
3863 while (fgets(line, sizeof(line), du) != NULL) {
3864 size_t length(strlen(line));
3865 while (length != 0 && line[length - 1] == '\n')
3866 line[--length] = '\0';
3867 if (char *tab = strchr(line, '\t')) {
3869 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3874 } else _assert(close(fds[0]));
3878 if (waitpid(pid, &status, 0) == -1)
3881 else _assert(false);
3890 - (void) installPackages:(NSArray *)packages {
3891 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3894 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3895 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3898 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3899 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3902 - (void) setSpecial:(id)function {
3903 [indirect_ setSpecial:function];
3906 - (void) setToken:(NSString *)token {
3909 Token_ = [token retain];
3911 [Metadata_ setObject:Token_ forKey:@"Token"];
3915 - (void) setPopupHook:(id)function {
3916 [indirect_ setPopupHook:function];
3919 - (void) setViewportWidth:(float)width {
3920 [indirect_ setViewportWidth:width];
3923 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3924 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3925 unsigned count([arguments count]);
3927 for (unsigned i(0); i != count; ++i)
3928 values[i] = [arguments objectAtIndex:i];
3929 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3932 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3933 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3935 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3937 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3943 /* Cydia Browser Controller {{{ */
3944 @interface CYBrowserController : BrowserController {
3945 CydiaObject *cydia_;
3950 @implementation CYBrowserController
3957 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3960 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3961 [super webView:view didClearWindowObject:window forFrame:frame];
3963 WebDataSource *source([frame dataSource]);
3964 NSURLResponse *response([source response]);
3965 NSURL *url([response URL]);
3966 NSString *scheme([url scheme]);
3968 NSHTTPURLResponse *http;
3969 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3970 http = (NSHTTPURLResponse *) response;
3974 NSDictionary *headers([http allHeaderFields]);
3975 NSString *host([url host]);
3976 [self setHeaders:headers forHost:host];
3979 [host isEqualToString:@"cydia.saurik.com"] ||
3980 [host hasSuffix:@".cydia.saurik.com"] ||
3981 [scheme isEqualToString:@"file"]
3983 [window setValue:cydia_ forKey:@"cydia"];
3986 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3987 if (System_ != NULL)
3988 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3989 if (Machine_ != NULL)
3990 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3992 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3994 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3997 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3998 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3999 [self _setMoreHeaders:copy];
4003 - (void) setDelegate:(id)delegate {
4004 [super setDelegate:delegate];
4005 [cydia_ setDelegate:delegate];
4009 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4010 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4012 WebView *webview([[webview_ _documentView] webView]);
4014 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4016 NSString *application = package == nil ? @"Cydia" : [NSString
4017 stringWithFormat:@"Cydia/%@",
4022 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4024 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4025 if (Product_ != nil)
4026 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4028 [webview setApplicationNameForUserAgent:application];
4035 /* Confirmation {{{ */
4036 @protocol ConfirmationControllerDelegate
4037 - (void) cancelAndClear:(bool)clear;
4038 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4042 @interface ConfirmationController : CYBrowserController {
4043 _transient Database *database_;
4044 UIAlertView *essential_;
4051 - (id) initWithDatabase:(Database *)database;
4055 @implementation ConfirmationController
4062 if (essential_ != nil)
4063 [essential_ release];
4067 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4068 NSString *context([alert context]);
4070 if ([context isEqualToString:@"remove"]) {
4071 if (button == [alert cancelButtonIndex]) {
4072 [self dismissModalViewControllerAnimated:YES];
4073 } else if (button == [alert firstOtherButtonIndex]) {
4076 [delegate_ confirmWithNavigationController:[self navigationController]];
4079 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4080 } else if ([context isEqualToString:@"unable"]) {
4081 [self dismissModalViewControllerAnimated:YES];
4082 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4084 [super alertView:alert clickedButtonAtIndex:button];
4088 - (void) _doContinue {
4089 [self dismissModalViewControllerAnimated:YES];
4090 [delegate_ cancelAndClear:NO];
4093 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4094 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4098 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4099 [super webView:view didClearWindowObject:window forFrame:frame];
4100 [window setValue:changes_ forKey:@"changes"];
4101 [window setValue:issues_ forKey:@"issues"];
4102 [window setValue:sizes_ forKey:@"sizes"];
4103 [window setValue:self forKey:@"queue"];
4106 - (id) initWithDatabase:(Database *)database {
4107 if ((self = [super init]) != nil) {
4108 database_ = database;
4110 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4112 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4113 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4114 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4115 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4116 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4120 pkgDepCache::Policy *policy([database_ policy]);
4122 pkgCacheFile &cache([database_ cache]);
4123 NSArray *packages = [database_ packages];
4124 for (Package *package in packages) {
4125 pkgCache::PkgIterator iterator = [package iterator];
4126 pkgDepCache::StateCache &state(cache[iterator]);
4128 NSString *name([package name]);
4130 if (state.NewInstall())
4131 [installing addObject:name];
4132 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4133 [reinstalling addObject:name];
4134 else if (state.Upgrade())
4135 [upgrading addObject:name];
4136 else if (state.Downgrade())
4137 [downgrading addObject:name];
4138 else if (state.Delete()) {
4139 if ([package essential])
4141 [removing addObject:name];
4144 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4145 substrate_ |= DepSubstrate(iterator.CurrentVer());
4150 else if (Advanced_) {
4151 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4153 essential_ = [[UIAlertView alloc]
4154 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4155 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4157 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4158 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4161 [essential_ setContext:@"remove"];
4163 essential_ = [[UIAlertView alloc]
4164 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4165 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4167 cancelButtonTitle:UCLocalize("OKAY")
4168 otherButtonTitles:nil
4171 [essential_ setContext:@"unable"];
4174 changes_ = [[NSArray alloc] initWithObjects:
4182 issues_ = [database_ issues];
4184 issues_ = [issues_ retain];
4186 sizes_ = [[NSArray alloc] initWithObjects:
4187 SizeString([database_ fetcher].FetchNeeded()),
4188 SizeString([database_ fetcher].PartialPresent()),
4191 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4193 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4194 initWithTitle:UCLocalize("CANCEL")
4195 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4196 style:UIBarButtonItemStylePlain
4198 action:@selector(cancelButtonClicked)
4203 - (void) applyRightButton {
4204 #if !AlwaysReload && !IgnoreInstall
4205 if (issues_ == nil && ![self isLoading])
4206 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4207 initWithTitle:UCLocalize("CONFIRM")
4208 style:UIBarButtonItemStylePlain
4210 action:@selector(confirmButtonClicked)
4213 [super applyRightButton];
4215 [[self navigationItem] setRightBarButtonItem:nil];
4219 - (void) cancelButtonClicked {
4220 [self dismissModalViewControllerAnimated:YES];
4221 [delegate_ cancelAndClear:YES];
4225 - (void) confirmButtonClicked {
4229 if (essential_ != nil)
4234 [delegate_ confirmWithNavigationController:[self navigationController]];
4242 /* Progress Data {{{ */
4243 @interface ProgressData : NSObject {
4245 // XXX: should these really both be _transient?
4246 _transient id target_;
4247 _transient id object_;
4250 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4257 @implementation ProgressData
4259 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4260 if ((self = [super init]) != nil) {
4261 selector_ = selector;
4281 /* Progress Controller {{{ */
4282 @interface ProgressController : CYViewController <
4283 ConfigurationDelegate,
4286 _transient Database *database_;
4287 UIProgressBar *progress_;
4288 UITextView *output_;
4289 UITextLabel *status_;
4290 UIPushButton *close_;
4292 SHA1SumValue springlist_;
4293 SHA1SumValue notifyconf_;
4297 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4299 - (void) _retachThread;
4300 - (void) _detachNewThreadData:(ProgressData *)data;
4301 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4307 @protocol ProgressControllerDelegate
4308 - (void) progressControllerIsComplete:(ProgressController *)sender;
4311 @implementation ProgressController
4314 [database_ setDelegate:nil];
4315 [progress_ release];
4324 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4325 if ((self = [super init]) != nil) {
4326 database_ = database;
4327 [database_ setDelegate:self];
4328 delegate_ = delegate;
4330 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4332 progress_ = [[UIProgressBar alloc] init];
4333 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4334 [progress_ setStyle:0];
4336 status_ = [[UITextLabel alloc] init];
4337 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4338 [status_ setColor:[UIColor whiteColor]];
4339 [status_ setBackgroundColor:[UIColor clearColor]];
4340 [status_ setCentersHorizontally:YES];
4341 //[status_ setFont:font];
4343 output_ = [[UITextView alloc] init];
4345 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4346 //[output_ setTextFont:@"Courier New"];
4347 [output_ setFont:[[output_ font] fontWithSize:12]];
4348 [output_ setTextColor:[UIColor whiteColor]];
4349 [output_ setBackgroundColor:[UIColor clearColor]];
4350 [output_ setMarginTop:0];
4351 [output_ setAllowsRubberBanding:YES];
4352 [output_ setEditable:NO];
4353 [[self view] addSubview:output_];
4355 close_ = [[UIPushButton alloc] init];
4356 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4357 [close_ setAutosizesToFit:NO];
4358 [close_ setDrawsShadow:YES];
4359 [close_ setStretchBackground:YES];
4360 [close_ setEnabled:YES];
4361 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4362 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4363 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4364 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4368 - (void) positionViews {
4369 CGRect bounds = [[self view] bounds];
4370 CGSize prgsize = [UIProgressBar defaultSize];
4373 (bounds.size.width - prgsize.width) / 2,
4374 bounds.size.height - prgsize.height - 20
4377 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4379 [progress_ setFrame:prgrect];
4380 [status_ setFrame:CGRectMake(
4382 bounds.size.height - prgsize.height - 50,
4383 bounds.size.width - 20,
4386 [output_ setFrame:CGRectMake(
4389 bounds.size.width - 20,
4390 bounds.size.height - 62
4392 [close_ setFrame:CGRectMake(
4393 (bounds.size.width - closewidth) / 2,
4394 bounds.size.height - prgsize.height - 50,
4400 - (void) viewWillAppear:(BOOL)animated {
4401 [super viewDidAppear:animated];
4402 [[self navigationItem] setHidesBackButton:YES];
4403 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4405 [self positionViews];
4408 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4409 [self positionViews];
4412 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4413 NSString *context([alert context]);
4415 if ([context isEqualToString:@"conffile"]) {
4416 FILE *input = [database_ input];
4417 if (button == [alert cancelButtonIndex])
4418 fprintf(input, "N\n");
4419 else if (button == [alert firstOtherButtonIndex])
4420 fprintf(input, "Y\n");
4425 - (void) closeButtonPushed {
4428 UpdateExternalStatus(0);
4432 [self dismissModalViewControllerAnimated:YES];
4436 [delegate_ terminateWithSuccess];
4437 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4438 [delegate_ suspendWithAnimation:YES];
4440 [delegate_ suspend];*/
4444 system("launchctl stop com.apple.SpringBoard");
4448 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4457 - (void) _retachThread {
4458 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4460 [[self view] addSubview:close_];
4461 [progress_ removeFromSuperview];
4462 [status_ removeFromSuperview];
4464 [database_ popErrorWithTitle:title_];
4465 [delegate_ progressControllerIsComplete:self];
4469 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4472 MMap mmap(file, MMap::ReadOnly);
4474 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4475 if (!(notifyconf_ == sha1.Result()))
4482 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4485 MMap mmap(file, MMap::ReadOnly);
4487 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4488 if (!(springlist_ == sha1.Result()))
4494 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4495 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4496 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4497 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4498 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4501 system("su -c /usr/bin/uicache mobile");
4503 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4505 [delegate_ setStatusBarShowsProgress:NO];
4508 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4509 [[data target] performSelector:[data selector] withObject:[data object]];
4510 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4513 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4514 UpdateExternalStatus(1);
4521 title_ = [title retain];
4523 [[self navigationItem] setTitle:title_];
4525 [status_ setText:nil];
4526 [output_ setText:@""];
4527 [progress_ setProgress:0];
4529 [close_ removeFromSuperview];
4530 [[self view] addSubview:progress_];
4531 [[self view] addSubview:status_];
4533 [delegate_ setStatusBarShowsProgress:YES];
4538 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4541 MMap mmap(file, MMap::ReadOnly);
4543 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4544 notifyconf_ = sha1.Result();
4550 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4553 MMap mmap(file, MMap::ReadOnly);
4555 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4556 springlist_ = sha1.Result();
4561 detachNewThreadSelector:@selector(_detachNewThreadData:)
4563 withObject:[[[ProgressData alloc]
4564 initWithSelector:selector
4571 - (void) repairWithSelector:(SEL)selector {
4573 detachNewThreadSelector:selector
4576 title:UCLocalize("REPAIRING")
4580 - (void) setConfigurationData:(NSString *)data {
4582 performSelectorOnMainThread:@selector(_setConfigurationData:)
4588 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4589 CYActionSheet *sheet([[[CYActionSheet alloc]
4591 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4592 defaultButtonIndex:0
4595 [sheet setMessage:error];
4596 [sheet yieldToPopupAlertAnimated:YES];
4600 - (void) setProgressTitle:(NSString *)title {
4602 performSelectorOnMainThread:@selector(_setProgressTitle:)
4608 - (void) setProgressPercent:(float)percent {
4610 performSelectorOnMainThread:@selector(_setProgressPercent:)
4611 withObject:[NSNumber numberWithFloat:percent]
4616 - (void) startProgress {
4619 - (void) addProgressOutput:(NSString *)output {
4621 performSelectorOnMainThread:@selector(_addProgressOutput:)
4627 - (bool) isCancelling:(size_t)received {
4631 - (void) _setConfigurationData:(NSString *)data {
4632 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4634 if (!conffile_r(data)) {
4635 lprintf("E:invalid conffile\n");
4639 NSString *ofile = conffile_r[1];
4640 //NSString *nfile = conffile_r[2];
4642 UIAlertView *alert = [[[UIAlertView alloc]
4643 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4644 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4646 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4647 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4648 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4652 [alert setContext:@"conffile"];
4656 - (void) _setProgressTitle:(NSString *)title {
4657 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4658 for (size_t i(0), e([words count]); i != e; ++i) {
4659 NSString *word([words objectAtIndex:i]);
4660 if (Package *package = [database_ packageWithName:word])
4661 [words replaceObjectAtIndex:i withObject:[package name]];
4664 [status_ setText:[words componentsJoinedByString:@" "]];
4667 - (void) _setProgressPercent:(NSNumber *)percent {
4668 [progress_ setProgress:[percent floatValue]];
4671 - (void) _addProgressOutput:(NSString *)output {
4672 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4673 CGSize size = [output_ contentSize];
4674 CGPoint offset = [output_ contentOffset];
4675 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4676 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4677 [output_ scrollRectToVisible:rect animated:YES];
4681 - (BOOL) isRunning {
4688 /* Cell Content View {{{ */
4689 @protocol ContentDelegate
4690 - (void) drawContentRect:(CGRect)rect;
4693 @interface ContentView : UIView {
4694 _transient id<ContentDelegate> delegate_;
4699 @implementation ContentView
4701 - (id) initWithFrame:(CGRect)frame {
4702 if ((self = [super initWithFrame:frame]) != nil) {
4703 [self setNeedsDisplayOnBoundsChange:YES];
4707 - (void) setDelegate:(id<ContentDelegate>)delegate {
4708 delegate_ = delegate;
4711 - (void) drawRect:(CGRect)rect {
4712 [super drawRect:rect];
4713 [delegate_ drawContentRect:rect];
4718 /* Cydia TableView Cell {{{ */
4719 @interface CYTableViewCell : UITableViewCell {
4720 ContentView *content_;
4726 @implementation CYTableViewCell
4733 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4734 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4736 if (view == content_) {
4737 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4738 highlighted_ = highlighted;
4741 [super _updateHighlightColorsForView:view highlighted:highlighted];
4744 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4745 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4746 highlighted_ = selected;
4748 [super setSelected:selected animated:animated];
4749 [content_ setNeedsDisplay];
4754 /* Package Cell {{{ */
4755 @interface PackageCell : CYTableViewCell <
4760 NSString *description_;
4768 - (PackageCell *) init;
4769 - (void) setPackage:(Package *)package;
4771 + (int) heightForPackage:(Package *)package;
4772 - (void) drawContentRect:(CGRect)rect;
4776 @implementation PackageCell
4778 - (void) clearPackage {
4789 if (description_ != nil) {
4790 [description_ release];
4794 if (source_ != nil) {
4799 if (badge_ != nil) {
4804 if (placard_ != nil) {
4814 [self clearPackage];
4818 - (PackageCell *) init {
4819 CGRect frame(CGRectMake(0, 0, 320, 74));
4820 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4821 UIView *content([self contentView]);
4822 CGRect bounds([content bounds]);
4824 content_ = [[ContentView alloc] initWithFrame:bounds];
4825 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4826 [content addSubview:content_];
4828 [content_ setDelegate:self];
4829 [content_ setOpaque:YES];
4833 - (void) _setBackgroundColor {
4835 if (NSString *mode = [package_ mode]) {
4836 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4837 color = remove ? RemovingColor_ : InstallingColor_;
4839 color = [UIColor whiteColor];
4841 [content_ setBackgroundColor:color];
4842 [self setNeedsDisplay];
4845 - (void) setPackage:(Package *)package {
4846 [self clearPackage];
4849 Source *source = [package source];
4851 icon_ = [[package icon] retain];
4852 name_ = [[package name] retain];
4855 description_ = [package longDescription];
4856 if (description_ == nil)
4857 description_ = [package shortDescription];
4858 if (description_ != nil)
4859 description_ = [description_ retain];
4861 commercial_ = [package isCommercial];
4863 package_ = [package retain];
4865 NSString *label = nil;
4866 bool trusted = false;
4868 if (source != nil) {
4869 label = [source label];
4870 trusted = [source trusted];
4871 } else if ([[package id] isEqualToString:@"firmware"])
4872 label = UCLocalize("APPLE");
4874 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4876 NSString *from(label);
4878 NSString *section = [package simpleSection];
4879 if (section != nil && ![section isEqualToString:label]) {
4880 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4881 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4884 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4885 source_ = [from retain];
4887 if (NSString *purpose = [package primaryPurpose])
4888 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4889 badge_ = [badge_ retain];
4891 if ([package installed] != nil)
4892 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4893 placard_ = [placard_ retain];
4895 [self _setBackgroundColor];
4896 [content_ setNeedsDisplay];
4899 - (void) drawContentRect:(CGRect)rect {
4900 bool highlighted(highlighted_);
4901 float width([self bounds].size.width);
4904 CGContextRef context(UIGraphicsGetCurrentContext());
4905 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4906 CGContextFillRect(context, rect);
4911 rect.size = [icon_ size];
4913 rect.size.width /= 2;
4914 rect.size.height /= 2;
4916 rect.origin.x = 25 - rect.size.width / 2;
4917 rect.origin.y = 25 - rect.size.height / 2;
4919 [icon_ drawInRect:rect];
4922 if (badge_ != nil) {
4924 rect.size = [badge_ size];
4926 rect.size.width /= 2;
4927 rect.size.height /= 2;
4929 rect.origin.x = 36 - rect.size.width / 2;
4930 rect.origin.y = 36 - rect.size.height / 2;
4932 [badge_ drawInRect:rect];
4939 UISetColor(commercial_ ? Purple_ : Black_);
4940 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4941 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4944 UISetColor(commercial_ ? Purplish_ : Gray_);
4945 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4947 if (placard_ != nil)
4948 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4951 + (int) heightForPackage:(Package *)package {
4957 /* Section Cell {{{ */
4958 @interface SectionCell : CYTableViewCell <
4970 - (void) setSection:(Section *)section editing:(BOOL)editing;
4974 @implementation SectionCell
4976 - (void) clearSection {
4977 if (basic_ != nil) {
4982 if (section_ != nil) {
4992 if (count_ != nil) {
4999 [self clearSection];
5005 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5006 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5007 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5008 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5009 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5011 UIView *content([self contentView]);
5012 CGRect bounds([content bounds]);
5014 content_ = [[ContentView alloc] initWithFrame:bounds];
5015 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5016 [content addSubview:content_];
5017 [content_ setBackgroundColor:[UIColor whiteColor]];
5019 [content_ setDelegate:self];
5023 - (void) onSwitch:(id)sender {
5024 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5025 if (metadata == nil) {
5026 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5027 [Sections_ setObject:metadata forKey:basic_];
5030 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5034 - (void) setSection:(Section *)section editing:(BOOL)editing {
5035 if (editing != editing_) {
5037 [switch_ removeFromSuperview];
5039 [self addSubview:switch_];
5043 [self clearSection];
5045 if (section == nil) {
5046 name_ = [UCLocalize("ALL_PACKAGES") retain];
5049 basic_ = [section name];
5051 basic_ = [basic_ retain];
5053 section_ = [section localized];
5054 if (section_ != nil)
5055 section_ = [section_ retain];
5057 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5058 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5061 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5064 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5065 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5067 [content_ setNeedsDisplay];
5070 - (void) setFrame:(CGRect)frame {
5071 [super setFrame:frame];
5073 CGRect rect([switch_ frame]);
5074 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5077 - (void) drawContentRect:(CGRect)rect {
5078 bool highlighted(highlighted_);
5080 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5085 float width(rect.size.width);
5091 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5093 CGSize size = [count_ sizeWithFont:Font14_];
5097 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5103 /* File Table {{{ */
5104 @interface FileTable : CYViewController <
5105 UITableViewDataSource,
5108 _transient Database *database_;
5111 NSMutableArray *files_;
5115 - (id) initWithDatabase:(Database *)database;
5116 - (void) setPackage:(Package *)package;
5120 @implementation FileTable
5123 if (package_ != nil)
5132 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5133 return files_ == nil ? 0 : [files_ count];
5136 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5140 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5141 static NSString *reuseIdentifier = @"Cell";
5143 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5145 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5146 [cell setFont:[UIFont systemFontOfSize:16]];
5148 [cell setText:[files_ objectAtIndex:indexPath.row]];
5149 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5154 - (id) initWithDatabase:(Database *)database {
5155 if ((self = [super init]) != nil) {
5156 database_ = database;
5158 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5160 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5162 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5163 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5164 [list_ setRowHeight:24.0f];
5165 [[self view] addSubview:list_];
5167 [list_ setDataSource:self];
5168 [list_ setDelegate:self];
5172 - (void) setPackage:(Package *)package {
5173 if (package_ != nil) {
5174 [package_ autorelease];
5183 [files_ removeAllObjects];
5185 if (package != nil) {
5186 package_ = [package retain];
5187 name_ = [[package id] retain];
5189 if (NSArray *files = [package files])
5190 [files_ addObjectsFromArray:files];
5192 if ([files_ count] != 0) {
5193 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5194 [files_ removeObjectAtIndex:0];
5195 [files_ sortUsingSelector:@selector(compareByPath:)];
5197 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5198 [stack addObject:@"/"];
5200 for (int i(0), e([files_ count]); i != e; ++i) {
5201 NSString *file = [files_ objectAtIndex:i];
5202 while (![file hasPrefix:[stack lastObject]])
5203 [stack removeLastObject];
5204 NSString *directory = [stack lastObject];
5205 [stack addObject:[file stringByAppendingString:@"/"]];
5206 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5207 ([stack count] - 2) * 3, "",
5208 [file substringFromIndex:[directory length]]
5217 - (void) reloadData {
5218 [self setPackage:[database_ packageWithName:name_]];
5223 /* Package Controller {{{ */
5224 @interface PackageController : CYBrowserController <
5225 UIActionSheetDelegate
5227 _transient Database *database_;
5231 NSMutableArray *buttons_;
5232 UIBarButtonItem *button_;
5235 - (id) initWithDatabase:(Database *)database;
5236 - (void) setPackage:(Package *)package;
5240 @implementation PackageController
5243 if (package_ != nil)
5257 if ([self retainCount] == 1)
5258 [delegate_ setPackageController:self];
5262 /* XXX: this is not safe at all... localization of /fail/ */
5263 - (void) _clickButtonWithName:(NSString *)name {
5264 if ([name isEqualToString:UCLocalize("CLEAR")])
5265 [delegate_ clearPackage:package_];
5266 else if ([name isEqualToString:UCLocalize("INSTALL")])
5267 [delegate_ installPackage:package_];
5268 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5269 [delegate_ installPackage:package_];
5270 else if ([name isEqualToString:UCLocalize("REMOVE")])
5271 [delegate_ removePackage:package_];
5272 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5273 [delegate_ installPackage:package_];
5274 else _assert(false);
5277 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5278 NSString *context([sheet context]);
5280 if ([context isEqualToString:@"modify"]) {
5281 if (button != [sheet cancelButtonIndex]) {
5282 NSString *buttonName = [buttons_ objectAtIndex:button];
5283 [self _clickButtonWithName:buttonName];
5286 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5290 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5291 [super webView:view didClearWindowObject:window forFrame:frame];
5292 [window setValue:package_ forKey:@"package"];
5295 - (bool) _allowJavaScriptPanel {
5300 - (void) _customButtonClicked {
5301 int count([buttons_ count]);
5306 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5308 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5309 [buttons addObjectsFromArray:buttons_];
5311 UIActionSheet *sheet = [[[UIActionSheet alloc]
5314 cancelButtonTitle:nil
5315 destructiveButtonTitle:nil
5316 otherButtonTitles:nil
5319 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5321 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5322 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5324 [sheet setContext:@"modify"];
5326 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5330 // We don't want to allow non-commercial packages to do custom things to the install button,
5331 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5332 - (void) customButtonClicked {
5334 [super customButtonClicked];
5336 [self _customButtonClicked];
5339 - (void) reloadButtonClicked {
5340 // Don't reload a package view by clicking the button.
5343 - (void) applyLoadingTitle {
5344 // Don't show "Loading" as the title. Ever.
5347 - (UIBarButtonItem *) rightButton {
5352 - (id) initWithDatabase:(Database *)database {
5353 if ((self = [super init]) != nil) {
5354 database_ = database;
5355 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5356 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5360 - (void) setPackage:(Package *)package {
5361 if (package_ != nil) {
5362 [package_ autorelease];
5371 [buttons_ removeAllObjects];
5373 if (package != nil) {
5376 package_ = [package retain];
5377 name_ = [[package id] retain];
5378 commercial_ = [package isCommercial];
5380 if ([package_ mode] != nil)
5381 [buttons_ addObject:UCLocalize("CLEAR")];
5382 if ([package_ source] == nil);
5383 else if ([package_ upgradableAndEssential:NO])
5384 [buttons_ addObject:UCLocalize("UPGRADE")];
5385 else if ([package_ uninstalled])
5386 [buttons_ addObject:UCLocalize("INSTALL")];
5388 [buttons_ addObject:UCLocalize("REINSTALL")];
5389 if (![package_ uninstalled])
5390 [buttons_ addObject:UCLocalize("REMOVE")];
5397 switch ([buttons_ count]) {
5398 case 0: title = nil; break;
5399 case 1: title = [buttons_ objectAtIndex:0]; break;
5400 default: title = UCLocalize("MODIFY"); break;
5403 button_ = [[UIBarButtonItem alloc]
5405 style:UIBarButtonItemStylePlain
5407 action:@selector(customButtonClicked)
5413 - (bool) isLoading {
5414 return commercial_ ? [super isLoading] : false;
5417 - (void) reloadData {
5418 [self setPackage:[database_ packageWithName:name_]];
5423 /* Package Table {{{ */
5424 @interface PackageTable : UIView <
5425 UITableViewDataSource,
5428 _transient Database *database_;
5430 NSMutableArray *packages_;
5431 NSMutableArray *sections_;
5433 NSMutableArray *index_;
5434 NSMutableDictionary *indices_;
5435 // XXX: this target_ seems to be delegate_. :(
5436 _transient id target_;
5438 // XXX: why do we even have this delegate_?
5439 _transient id delegate_;
5442 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5444 - (void) setDelegate:(id)delegate;
5446 - (void) reloadData;
5447 - (void) resetCursor;
5449 - (UITableView *) list;
5451 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5453 - (void) deselectWithAnimation:(BOOL)animated;
5457 @implementation PackageTable
5460 [packages_ release];
5461 [sections_ release];
5469 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5470 NSInteger count([sections_ count]);
5471 return count == 0 ? 1 : count;
5474 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5475 if ([sections_ count] == 0)
5477 return [[sections_ objectAtIndex:section] name];
5480 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5481 if ([sections_ count] == 0)
5483 return [[sections_ objectAtIndex:section] count];
5486 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5487 @synchronized (database_) {
5488 if ([database_ era] != era_)
5491 Section *section([sections_ objectAtIndex:[path section]]);
5492 NSInteger row([path row]);
5493 Package *package([packages_ objectAtIndex:([section row] + row)]);
5494 return [[package retain] autorelease];
5497 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5498 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5500 cell = [[[PackageCell alloc] init] autorelease];
5501 [cell setPackage:[self packageAtIndexPath:path]];
5505 - (void) deselectWithAnimation:(BOOL)animated {
5506 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5509 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5510 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5513 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5514 Package *package([self packageAtIndexPath:path]);
5515 package = [database_ packageWithName:[package id]];
5516 [target_ performSelector:action_ withObject:package];
5520 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5521 return [packages_ count] > 20 ? index_ : nil;
5524 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5528 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5529 if ((self = [super initWithFrame:frame]) != nil) {
5530 database_ = database;
5535 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5536 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5538 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5539 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5541 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5542 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5543 [list_ setRowHeight:73.0f];
5544 [self addSubview:list_];
5546 [list_ setDataSource:self];
5547 [list_ setDelegate:self];
5551 - (void) setDelegate:(id)delegate {
5552 delegate_ = delegate;
5555 - (bool) hasPackage:(Package *)package {
5559 - (void) reloadData {
5560 era_ = [database_ era];
5561 NSArray *packages = [database_ packages];
5563 [packages_ removeAllObjects];
5564 [sections_ removeAllObjects];
5566 _profile(PackageTable$reloadData$Filter)
5567 for (Package *package in packages)
5568 if ([self hasPackage:package])
5569 [packages_ addObject:package];
5572 [index_ removeAllObjects];
5573 [indices_ removeAllObjects];
5575 Section *section = nil;
5577 _profile(PackageTable$reloadData$Section)
5578 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5582 _profile(PackageTable$reloadData$Section$Package)
5583 package = [packages_ objectAtIndex:offset];
5584 index = [package index];
5587 if (section == nil || [section index] != index) {
5588 _profile(PackageTable$reloadData$Section$Allocate)
5589 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5592 [index_ addObject:[section name]];
5593 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5595 _profile(PackageTable$reloadData$Section$Add)
5596 [sections_ addObject:section];
5600 [section addToCount];
5604 _profile(PackageTable$reloadData$List)
5609 - (void) resetCursor {
5610 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5613 - (UITableView *) list {
5617 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5618 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5623 /* Filtered Package Table {{{ */
5624 @interface FilteredPackageTable : PackageTable {
5630 - (void) setObject:(id)object;
5631 - (void) setObject:(id)object forFilter:(SEL)filter;
5633 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5637 @implementation FilteredPackageTable
5645 - (void) setFilter:(SEL)filter {
5648 /* XXX: this is an unsafe optimization of doomy hell */
5649 Method method(class_getInstanceMethod([Package class], filter));
5650 _assert(method != NULL);
5651 imp_ = method_getImplementation(method);
5652 _assert(imp_ != NULL);
5655 - (void) setObject:(id)object {
5661 object_ = [object retain];
5664 - (void) setObject:(id)object forFilter:(SEL)filter {
5665 [self setFilter:filter];
5666 [self setObject:object];
5669 - (bool) hasPackage:(Package *)package {
5670 _profile(FilteredPackageTable$hasPackage)
5671 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5675 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5676 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5677 [self setFilter:filter];
5678 object_ = [object retain];
5686 /* Filtered Package Controller {{{ */
5687 @interface FilteredPackageController : CYViewController {
5688 _transient Database *database_;
5689 FilteredPackageTable *packages_;
5693 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5697 @implementation FilteredPackageController
5700 [packages_ release];
5706 - (void) viewDidAppear:(BOOL)animated {
5707 [super viewDidAppear:animated];
5708 [packages_ deselectWithAnimation:animated];
5711 - (void) didSelectPackage:(Package *)package {
5712 PackageController *view([delegate_ packageController]);
5713 [view setPackage:package];
5714 [view setDelegate:delegate_];
5715 [[self navigationController] pushViewController:view animated:YES];
5718 - (NSString *) title { return title_; }
5720 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5721 if ((self = [super init]) != nil) {
5722 database_ = database;
5723 title_ = [title copy];
5724 [[self navigationItem] setTitle:title_];
5726 packages_ = [[FilteredPackageTable alloc]
5727 initWithFrame:[[self view] bounds]
5730 action:@selector(didSelectPackage:)
5735 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5736 [[self view] addSubview:packages_];
5740 - (void) reloadData {
5741 [packages_ reloadData];
5744 - (void) setDelegate:(id)delegate {
5745 [super setDelegate:delegate];
5746 [packages_ setDelegate:delegate];
5753 /* Add Source Controller {{{ */
5754 @interface AddSourceController : CYViewController {
5755 _transient Database *database_;
5758 - (id) initWithDatabase:(Database *)database;
5762 @implementation AddSourceController
5764 - (id) initWithDatabase:(Database *)database {
5765 if ((self = [super init]) != nil) {
5766 database_ = database;
5772 /* Source Cell {{{ */
5773 @interface SourceCell : CYTableViewCell <
5778 NSString *description_;
5782 - (void) setSource:(Source *)source;
5786 @implementation SourceCell
5788 - (void) clearSource {
5791 [description_ release];
5800 - (void) setSource:(Source *)source {
5804 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5806 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5807 icon_ = [icon_ retain];
5809 origin_ = [[source name] retain];
5810 label_ = [[source uri] retain];
5811 description_ = [[source description] retain];
5813 [content_ setNeedsDisplay];
5821 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5822 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5823 UIView *content([self contentView]);
5824 CGRect bounds([content bounds]);
5826 content_ = [[ContentView alloc] initWithFrame:bounds];
5827 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5828 [content_ setBackgroundColor:[UIColor whiteColor]];
5829 [content addSubview:content_];
5831 [content_ setDelegate:self];
5832 [content_ setOpaque:YES];
5836 - (void) drawContentRect:(CGRect)rect {
5837 bool highlighted(highlighted_);
5838 float width(rect.size.width);
5841 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5848 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5852 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5856 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5861 /* Source Table {{{ */
5862 @interface SourceTable : CYViewController <
5863 UITableViewDataSource,
5866 _transient Database *database_;
5868 NSMutableArray *sources_;
5872 UIProgressHUD *hud_;
5875 //NSURLConnection *installer_;
5876 NSURLConnection *trivial_;
5877 NSURLConnection *trivial_bz2_;
5878 NSURLConnection *trivial_gz_;
5879 //NSURLConnection *automatic_;
5884 - (id) initWithDatabase:(Database *)database;
5886 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5890 @implementation SourceTable
5892 - (void) _releaseConnection:(NSURLConnection *)connection {
5893 if (connection != nil) {
5894 [connection cancel];
5895 //[connection setDelegate:nil];
5896 [connection release];
5908 //[self _releaseConnection:installer_];
5909 [self _releaseConnection:trivial_];
5910 [self _releaseConnection:trivial_gz_];
5911 [self _releaseConnection:trivial_bz2_];
5912 //[self _releaseConnection:automatic_];
5919 - (void) viewDidAppear:(BOOL)animated {
5920 [super viewDidAppear:animated];
5921 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5924 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5925 return offset_ == 0 ? 1 : 2;
5928 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5929 switch (section + (offset_ == 0 ? 1 : 0)) {
5930 case 0: return UCLocalize("ENTERED_BY_USER");
5931 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5937 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5938 int count = [sources_ count];
5940 case 0: return (offset_ == 0 ? count : offset_);
5941 case 1: return count - offset_;
5947 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5949 switch (indexPath.section) {
5950 case 0: idx = indexPath.row; break;
5951 case 1: idx = indexPath.row + offset_; break;
5955 return [sources_ objectAtIndex:idx];
5958 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5959 Source *source = [self sourceAtIndexPath:indexPath];
5960 return [source description] == nil ? 56 : 73;
5963 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5964 static NSString *cellIdentifier = @"SourceCell";
5966 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5967 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5968 [cell setSource:[self sourceAtIndexPath:indexPath]];
5973 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5974 return UITableViewCellAccessoryDisclosureIndicator;
5977 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5978 Source *source = [self sourceAtIndexPath:indexPath];
5980 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5981 initWithDatabase:database_
5982 title:[source label]
5983 filter:@selector(isVisibleInSource:)
5987 [packages setDelegate:delegate_];
5989 [[self navigationController] pushViewController:packages animated:YES];
5992 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5993 Source *source = [self sourceAtIndexPath:indexPath];
5994 return [source record] != nil;
5997 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5998 Source *source = [self sourceAtIndexPath:indexPath];
5999 [Sources_ removeObjectForKey:[source key]];
6000 [delegate_ syncData];
6004 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
6007 @"./", @"Distribution",
6008 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
6010 [delegate_ syncData];
6013 - (NSString *) getWarning {
6014 NSString *href(href_);
6015 NSRange colon([href rangeOfString:@"://"]);
6016 if (colon.location != NSNotFound)
6017 href = [href substringFromIndex:(colon.location + 3)];
6018 href = [href stringByAddingPercentEscapes];
6019 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
6020 href = [href stringByCachingURLWithCurrentCDN];
6022 NSURL *url([NSURL URLWithString:href]);
6024 NSStringEncoding encoding;
6025 NSError *error(nil);
6027 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
6028 return [warning length] == 0 ? nil : warning;
6032 - (void) _endConnection:(NSURLConnection *)connection {
6033 // XXX: the memory management in this method is horribly awkward
6035 NSURLConnection **field = NULL;
6036 if (connection == trivial_)
6038 else if (connection == trivial_bz2_)
6039 field = &trivial_bz2_;
6040 else if (connection == trivial_gz_)
6041 field = &trivial_gz_;
6042 _assert(field != NULL);
6043 [connection release];
6048 trivial_bz2_ == nil &&
6054 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6057 UIAlertView *alert = [[[UIAlertView alloc]
6058 initWithTitle:UCLocalize("SOURCE_WARNING")
6061 cancelButtonTitle:UCLocalize("CANCEL")
6062 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6065 [alert setContext:@"warning"];
6066 [alert setNumberOfRows:1];
6070 } else if (error_ != nil) {
6071 UIAlertView *alert = [[[UIAlertView alloc]
6072 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6073 message:[error_ localizedDescription]
6075 cancelButtonTitle:UCLocalize("OK")
6076 otherButtonTitles:nil
6079 [alert setContext:@"urlerror"];
6082 UIAlertView *alert = [[[UIAlertView alloc]
6083 initWithTitle:UCLocalize("NOT_REPOSITORY")
6084 message:UCLocalize("NOT_REPOSITORY_EX")
6086 cancelButtonTitle:UCLocalize("OK")
6087 otherButtonTitles:nil
6090 [alert setContext:@"trivial"];
6094 [delegate_ setStatusBarShowsProgress:NO];
6095 [delegate_ removeProgressHUD:hud_];
6105 if (error_ != nil) {
6112 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6113 switch ([response statusCode]) {
6119 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6120 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6122 error_ = [error retain];
6123 [self _endConnection:connection];
6126 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6127 [self _endConnection:connection];
6130 - (NSString *) title { return UCLocalize("SOURCES"); }
6132 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6133 NSMutableURLRequest *request = [NSMutableURLRequest
6134 requestWithURL:[NSURL URLWithString:href]
6135 cachePolicy:NSURLRequestUseProtocolCachePolicy
6136 timeoutInterval:120.0
6139 [request setHTTPMethod:method];
6141 if (Machine_ != NULL)
6142 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6143 if (UniqueID_ != nil)
6144 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6146 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6148 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6151 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6152 NSString *context([alert context]);
6154 if ([context isEqualToString:@"source"]) {
6157 NSString *href = [[alert textField] text];
6159 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6161 if (![href hasSuffix:@"/"])
6162 href_ = [href stringByAppendingString:@"/"];
6165 href_ = [href_ retain];
6167 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6168 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6169 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6170 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6174 // XXX: this is stupid
6175 hud_ = [[delegate_ addProgressHUD] retain];
6176 [hud_ setText:UCLocalize("VERIFYING_URL")];
6185 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6186 } else if ([context isEqualToString:@"trivial"])
6187 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6188 else if ([context isEqualToString:@"urlerror"])
6189 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6190 else if ([context isEqualToString:@"warning"]) {
6205 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6209 - (id) initWithDatabase:(Database *)database {
6210 if ((self = [super init]) != nil) {
6211 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6212 [self updateButtonsForEditingStatus:NO animated:NO];
6214 database_ = database;
6215 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6217 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6218 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6219 [[self view] addSubview:list_];
6221 [list_ setDataSource:self];
6222 [list_ setDelegate:self];
6228 - (void) reloadData {
6230 if (!list.ReadMainList())
6233 [sources_ removeAllObjects];
6234 [sources_ addObjectsFromArray:[database_ sources]];
6236 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6239 int count([sources_ count]);
6241 for (int i = 0; i != count; i++) {
6242 if ([[sources_ objectAtIndex:i] record] == nil)
6247 [list_ setEditing:NO];
6248 [self updateButtonsForEditingStatus:NO animated:NO];
6252 - (void) addButtonClicked {
6253 /*[book_ pushPage:[[[AddSourceController alloc]
6258 UIAlertView *alert = [[[UIAlertView alloc]
6259 initWithTitle:UCLocalize("ENTER_APT_URL")
6262 cancelButtonTitle:UCLocalize("CANCEL")
6263 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6266 [alert setContext:@"source"];
6267 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6269 [alert setNumberOfRows:1];
6270 [alert addTextFieldWithValue:@"http://" label:@""];
6272 UITextInputTraits *traits = [[alert textField] textInputTraits];
6273 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6274 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6275 [traits setKeyboardType:UIKeyboardTypeURL];
6276 // XXX: UIReturnKeyDone
6277 [traits setReturnKeyType:UIReturnKeyNext];
6282 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6283 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6284 initWithTitle:UCLocalize("ADD")
6285 style:UIBarButtonItemStylePlain
6287 action:@selector(addButtonClicked)
6288 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6290 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6291 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6292 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6294 action:@selector(editButtonClicked)
6295 ] autorelease] animated:animated];
6297 if (IsWildcat_ && !editing)
6298 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6299 initWithTitle:UCLocalize("SETTINGS")
6300 style:UIBarButtonItemStylePlain
6302 action:@selector(settingsButtonClicked)
6306 - (void) settingsButtonClicked {
6307 [delegate_ showSettings];
6310 - (void) editButtonClicked {
6311 [list_ setEditing:![list_ isEditing] animated:YES];
6313 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6319 /* Installed Controller {{{ */
6320 @interface InstalledController : FilteredPackageController {
6324 - (id) initWithDatabase:(Database *)database;
6326 - (void) updateRoleButton;
6327 - (void) queueStatusDidChange;
6331 @implementation InstalledController
6337 - (NSString *) title { return UCLocalize("INSTALLED"); }
6339 - (id) initWithDatabase:(Database *)database {
6340 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6341 [self updateRoleButton];
6342 [self queueStatusDidChange];
6347 - (void) queueButtonClicked {
6352 - (void) queueStatusDidChange {
6356 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6357 initWithTitle:UCLocalize("QUEUE")
6358 style:UIBarButtonItemStyleDone
6360 action:@selector(queueButtonClicked)
6363 [[self navigationItem] setLeftBarButtonItem:nil];
6369 - (void) reloadData {
6370 [packages_ reloadData];
6373 - (void) updateRoleButton {
6374 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6375 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6376 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6377 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6379 action:@selector(roleButtonClicked)
6383 - (void) roleButtonClicked {
6384 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6385 [packages_ reloadData];
6388 [self updateRoleButton];
6391 - (void) setDelegate:(id)delegate {
6392 [super setDelegate:delegate];
6393 [packages_ setDelegate:delegate];
6399 /* Home Controller {{{ */
6400 @interface HomeController : CYBrowserController {
6405 @implementation HomeController
6407 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6408 [super _setMoreHeaders:request];
6411 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6412 if (UniqueID_ != nil)
6413 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6415 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6418 - (void) aboutButtonClicked {
6419 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6421 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6422 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6423 [alert setCancelButtonIndex:0];
6426 @"Copyright (C) 2008-2010\n"
6427 "Jay Freeman (saurik)\n"
6428 "saurik@saurik.com\n"
6429 "http://www.saurik.com/"
6435 - (void) viewWillAppear:(BOOL)animated {
6436 [super viewWillAppear:animated];
6437 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6440 - (void) viewWillDisappear:(BOOL)animated {
6441 [super viewWillDisappear:animated];
6442 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6446 if ((self = [super init]) != nil) {
6447 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6448 initWithTitle:UCLocalize("ABOUT")
6449 style:UIBarButtonItemStylePlain
6451 action:@selector(aboutButtonClicked)
6458 /* Manage Controller {{{ */
6459 @interface ManageController : CYBrowserController {
6462 - (void) queueStatusDidChange;
6465 @implementation ManageController
6468 if ((self = [super init]) != nil) {
6469 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6471 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6472 initWithTitle:UCLocalize("SETTINGS")
6473 style:UIBarButtonItemStylePlain
6475 action:@selector(settingsButtonClicked)
6478 [self queueStatusDidChange];
6482 - (void) settingsButtonClicked {
6483 [delegate_ showSettings];
6487 - (void) queueButtonClicked {
6491 - (void) applyLoadingTitle {
6492 // No "Loading" title.
6495 - (void) applyRightButton {
6500 - (void) queueStatusDidChange {
6502 if (!IsWildcat_ && Queuing_) {
6503 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6504 initWithTitle:UCLocalize("QUEUE")
6505 style:UIBarButtonItemStyleDone
6507 action:@selector(queueButtonClicked)
6510 [[self navigationItem] setRightBarButtonItem:nil];
6515 - (bool) isLoading {
6522 /* Refresh Bar {{{ */
6523 @interface RefreshBar : UINavigationBar {
6524 UIProgressIndicator *indicator_;
6525 UITextLabel *prompt_;
6526 UIProgressBar *progress_;
6527 UINavigationButton *cancel_;
6532 @implementation RefreshBar
6535 [indicator_ release];
6537 [progress_ release];
6542 - (void) positionViews {
6543 CGRect frame = [cancel_ frame];
6544 frame.size = [cancel_ sizeThatFits:frame.size];
6545 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6546 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6547 [cancel_ setFrame:frame];
6549 CGSize prgsize = {75, 100};
6551 [self frame].size.width - prgsize.width - 10,
6552 ([self frame].size.height - prgsize.height) / 2
6554 [progress_ setFrame:prgrect];
6556 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6557 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6558 CGRect indrect = {{indoffset, indoffset}, indsize};
6559 [indicator_ setFrame:indrect];
6561 CGSize prmsize = {215, indsize.height + 4};
6563 indoffset * 2 + indsize.width,
6564 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6566 [prompt_ setFrame:prmrect];
6569 - (void)setFrame:(CGRect)frame {
6570 [super setFrame:frame];
6572 [self positionViews];
6575 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6576 if ((self = [super initWithFrame:frame])) {
6577 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6579 [self setBarStyle:UIBarStyleBlack];
6581 UIBarStyle barstyle([self _barStyle:NO]);
6582 bool ugly(barstyle == UIBarStyleDefault);
6584 UIProgressIndicatorStyle style = ugly ?
6585 UIProgressIndicatorStyleMediumBrown :
6586 UIProgressIndicatorStyleMediumWhite;
6588 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6589 [indicator_ setStyle:style];
6590 [indicator_ startAnimation];
6591 [self addSubview:indicator_];
6593 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6594 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6595 [prompt_ setBackgroundColor:[UIColor clearColor]];
6596 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6597 [self addSubview:prompt_];
6599 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6600 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6601 [progress_ setStyle:0];
6602 [self addSubview:progress_];
6604 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6605 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6606 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6607 [cancel_ setBarStyle:barstyle];
6609 [self positionViews];
6614 [cancel_ removeFromSuperview];
6618 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6619 [progress_ setProgress:0];
6620 [self addSubview:cancel_];
6624 [cancel_ removeFromSuperview];
6627 - (void) setPrompt:(NSString *)prompt {
6628 [prompt_ setText:prompt];
6631 - (void) setProgress:(float)progress {
6632 [progress_ setProgress:progress];
6638 @class CYNavigationController;
6640 /* Cydia Tab Bar Controller {{{ */
6641 @interface CYTabBarController : UITabBarController <
6644 _transient Database *database_;
6645 RefreshBar *refreshbar_;
6649 // XXX: ok, "updatedelegate_"?...
6650 _transient NSObject<CydiaDelegate> *updatedelegate_;
6655 - (void) dropBar:(BOOL)animated;
6656 - (void) beginUpdate;
6657 - (void) raiseBar:(BOOL)animated;
6662 @implementation CYTabBarController
6664 /* XXX: some logic should probably go here related to
6665 freeing the view controllers on tab change */
6667 - (void) reloadData {
6668 size_t count([[self viewControllers] count]);
6669 for (size_t i(0); i != count; ++i) {
6670 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6675 - (id) initWithDatabase:(Database *)database {
6676 if ((self = [super init]) != nil) {
6677 database_ = database;
6679 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6680 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6682 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6686 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6687 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
6690 - (void) setUpdate:(NSDate *)date {
6694 - (void) beginUpdate {
6695 [refreshbar_ start];
6698 [updatedelegate_ retainNetworkActivityIndicator];
6702 detachNewThreadSelector:@selector(performUpdate)
6708 - (void) performUpdate { _pooled
6710 status.setDelegate(self);
6711 [database_ updateWithStatus:status];
6714 performSelectorOnMainThread:@selector(completeUpdate)
6720 - (void) stopUpdateWithSelector:(SEL)selector {
6722 [updatedelegate_ releaseNetworkActivityIndicator];
6724 [self raiseBar:YES];
6727 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6730 - (void) completeUpdate {
6733 [self stopUpdateWithSelector:@selector(reloadData)];
6736 - (void) cancelUpdate {
6737 [self stopUpdateWithSelector:@selector(updateData)];
6740 - (void) cancelPressed {
6741 [self cancelUpdate];
6748 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6749 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6752 - (void) startProgress {
6755 - (void) setProgressTitle:(NSString *)title {
6757 performSelectorOnMainThread:@selector(_setProgressTitle:)
6763 - (bool) isCancelling:(size_t)received {
6767 - (void) setProgressPercent:(float)percent {
6769 performSelectorOnMainThread:@selector(_setProgressPercent:)
6770 withObject:[NSNumber numberWithFloat:percent]
6775 - (void) addProgressOutput:(NSString *)output {
6777 performSelectorOnMainThread:@selector(_addProgressOutput:)
6783 - (void) _setProgressTitle:(NSString *)title {
6784 [refreshbar_ setPrompt:title];
6787 - (void) _setProgressPercent:(NSNumber *)percent {
6788 [refreshbar_ setProgress:[percent floatValue]];
6791 - (void) _addProgressOutput:(NSString *)output {
6794 - (void) setUpdateDelegate:(id)delegate {
6795 updatedelegate_ = delegate;
6798 - (CGFloat) statusBarHeight {
6799 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6800 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6802 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6806 - (UIView *) transitionView {
6807 if ([self respondsToSelector:@selector(_transitionView)])
6808 return [self _transitionView];
6810 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6813 - (void) dropBar:(BOOL)animated {
6818 UIView *transition([self transitionView]);
6819 [[self view] addSubview:refreshbar_];
6821 CGRect barframe([refreshbar_ frame]);
6823 if (false) // XXX: _UIApplicationLinkedOnOrAfter(4)
6824 barframe.origin.y = [self statusBarHeight];
6826 barframe.origin.y = 0;
6828 [refreshbar_ setFrame:barframe];
6831 [UIView beginAnimations:nil context:NULL];
6833 CGRect viewframe = [transition frame];
6834 viewframe.origin.y += barframe.size.height;
6835 viewframe.size.height -= barframe.size.height;
6836 [transition setFrame:viewframe];
6839 [UIView commitAnimations];
6841 // Ensure bar has the proper width for our view, it might have changed
6842 barframe.size.width = viewframe.size.width;
6843 [refreshbar_ setFrame:barframe];
6845 // XXX: fix Apple's layout bug
6846 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6849 - (void) raiseBar:(BOOL)animated {
6854 UIView *transition([self transitionView]);
6855 [refreshbar_ removeFromSuperview];
6857 CGRect barframe([refreshbar_ frame]);
6860 [UIView beginAnimations:nil context:NULL];
6862 CGRect viewframe = [transition frame];
6863 viewframe.origin.y -= barframe.size.height;
6864 viewframe.size.height += barframe.size.height;
6865 [transition setFrame:viewframe];
6868 [UIView commitAnimations];
6870 // XXX: fix Apple's layout bug
6871 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6875 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6876 // XXX: fix Apple's layout bug
6877 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6881 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6882 bool dropped(dropped_);
6887 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6892 // XXX: fix Apple's layout bug
6893 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6896 - (void) statusBarFrameChanged:(NSNotification *)notification {
6904 [refreshbar_ release];
6905 [[NSNotificationCenter defaultCenter] removeObserver:self];
6912 /* Cydia Navigation Controller {{{ */
6913 @interface CYNavigationController : UINavigationController {
6914 _transient Database *database_;
6915 _transient id<UINavigationControllerDelegate> delegate_;
6918 - (id) initWithDatabase:(Database *)database;
6919 - (void) reloadData;
6924 @implementation CYNavigationController
6926 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6927 // Inherit autorotation settings for modal parents.
6928 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6929 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6931 return [super shouldAutorotateToInterfaceOrientation:orientation];
6939 - (void) reloadData {
6940 size_t count([[self viewControllers] count]);
6941 for (size_t i(0); i != count; ++i) {
6942 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6947 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6948 delegate_ = delegate;
6951 - (id) initWithDatabase:(Database *)database {
6952 if ((self = [super init]) != nil) {
6953 database_ = database;
6959 /* Cydia:// Protocol {{{ */
6960 @interface CydiaURLProtocol : NSURLProtocol {
6965 @implementation CydiaURLProtocol
6967 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6968 NSURL *url([request URL]);
6971 NSString *scheme([[url scheme] lowercaseString]);
6972 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6977 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6981 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6982 id<NSURLProtocolClient> client([self client]);
6984 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6986 NSData *data(UIImagePNGRepresentation(icon));
6988 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6989 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6990 [client URLProtocol:self didLoadData:data];
6991 [client URLProtocolDidFinishLoading:self];
6995 - (void) startLoading {
6996 id<NSURLProtocolClient> client([self client]);
6997 NSURLRequest *request([self request]);
6999 NSURL *url([request URL]);
7000 NSString *href([url absoluteString]);
7002 NSString *path([href substringFromIndex:8]);
7003 NSRange slash([path rangeOfString:@"/"]);
7006 if (slash.location == NSNotFound) {
7010 command = [path substringToIndex:slash.location];
7011 path = [path substringFromIndex:(slash.location + 1)];
7014 Database *database([Database sharedInstance]);
7016 if ([command isEqualToString:@"package-icon"]) {
7019 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7020 Package *package([database packageWithName:path]);
7023 UIImage *icon([package icon]);
7024 [self _returnPNGWithImage:icon forRequest:request];
7025 } else if ([command isEqualToString:@"source-icon"]) {
7028 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7029 NSString *source(Simplify(path));
7030 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7032 icon = [UIImage applicationImageNamed:@"unknown.png"];
7033 [self _returnPNGWithImage:icon forRequest:request];
7034 } else if ([command isEqualToString:@"uikit-image"]) {
7037 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7038 UIImage *icon(_UIImageWithName(path));
7039 [self _returnPNGWithImage:icon forRequest:request];
7040 } else if ([command isEqualToString:@"section-icon"]) {
7043 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7044 NSString *section(Simplify(path));
7045 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7047 icon = [UIImage applicationImageNamed:@"unknown.png"];
7048 [self _returnPNGWithImage:icon forRequest:request];
7050 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7054 - (void) stopLoading {
7060 /* Sections Controller {{{ */
7061 @interface SectionsController : CYViewController <
7062 UITableViewDataSource,
7065 _transient Database *database_;
7066 NSMutableArray *sections_;
7067 NSMutableArray *filtered_;
7073 - (id) initWithDatabase:(Database *)database;
7074 - (void) reloadData;
7077 - (void) editButtonClicked;
7081 @implementation SectionsController
7084 [list_ setDataSource:nil];
7085 [list_ setDelegate:nil];
7087 [sections_ release];
7088 [filtered_ release];
7090 [accessory_ release];
7094 - (void) viewDidAppear:(BOOL)animated {
7095 [super viewDidAppear:animated];
7096 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7099 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7100 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7104 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7105 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7108 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7112 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7113 static NSString *reuseIdentifier = @"SectionCell";
7115 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7117 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7119 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7124 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7128 Section *section = [self sectionAtIndexPath:indexPath];
7129 NSString *name = [section name];
7132 if ([indexPath row] == 0) {
7135 title = UCLocalize("ALL_PACKAGES");
7138 name = [NSString stringWithString:name];
7139 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7142 title = UCLocalize("NO_SECTION");
7146 FilteredPackageController *table = [[[FilteredPackageController alloc]
7147 initWithDatabase:database_
7149 filter:@selector(isVisibleInSection:)
7153 [table setDelegate:delegate_];
7155 [[self navigationController] pushViewController:table animated:YES];
7158 - (NSString *) title { return UCLocalize("SECTIONS"); }
7160 - (id) initWithDatabase:(Database *)database {
7161 if ((self = [super init]) != nil) {
7162 database_ = database;
7164 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7166 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7167 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7169 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7170 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7171 [list_ setRowHeight:45.0f];
7172 [[self view] addSubview:list_];
7174 [list_ setDataSource:self];
7175 [list_ setDelegate:self];
7181 - (void) reloadData {
7182 NSArray *packages = [database_ packages];
7184 [sections_ removeAllObjects];
7185 [filtered_ removeAllObjects];
7187 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7190 for (Package *package in packages) {
7191 NSString *name([package section]);
7192 NSString *key(name == nil ? @"" : name);
7196 _profile(SectionsView$reloadData$Section)
7197 section = [sections objectForKey:key];
7198 if (section == nil) {
7199 _profile(SectionsView$reloadData$Section$Allocate)
7200 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
7201 [sections setObject:section forKey:key];
7206 [section addToCount];
7208 _profile(SectionsView$reloadData$Filter)
7209 if (![package valid] || ![package visible])
7217 [sections_ addObjectsFromArray:[sections allValues]];
7219 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7221 for (Section *section in sections_) {
7222 size_t count([section row]);
7226 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7227 [section setCount:count];
7228 [filtered_ addObject:section];
7231 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7232 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
7233 style:UIBarButtonItemStylePlain
7235 action:@selector(editButtonClicked)
7236 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7242 - (void) resetView {
7244 [self editButtonClicked];
7247 - (void) editButtonClicked {
7248 if ((editing_ = !editing_))
7251 [delegate_ updateData];
7253 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7254 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
7255 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
7258 - (UIView *) accessoryView {
7264 /* Changes Controller {{{ */
7265 @interface ChangesController : CYViewController <
7266 UITableViewDataSource,
7269 _transient Database *database_;
7271 CFMutableArrayRef packages_;
7272 NSMutableArray *sections_;
7275 BOOL hasSentFirstLoad_;
7278 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
7279 - (void) reloadData;
7283 @implementation ChangesController
7286 [list_ setDelegate:nil];
7287 [list_ setDataSource:nil];
7289 CFRelease(packages_);
7291 [sections_ release];
7296 - (void) viewDidAppear:(BOOL)animated {
7297 [super viewDidAppear:animated];
7298 if (!hasSentFirstLoad_) {
7299 hasSentFirstLoad_ = YES;
7300 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7302 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7306 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7307 NSInteger count([sections_ count]);
7308 return count == 0 ? 1 : count;
7311 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7312 if ([sections_ count] == 0)
7314 return [[sections_ objectAtIndex:section] name];
7317 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7318 if ([sections_ count] == 0)
7320 return [[sections_ objectAtIndex:section] count];
7323 - (Package *) packageAtIndex:(NSUInteger)index {
7324 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7327 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7328 @synchronized (database_) {
7329 if ([database_ era] != era_)
7332 Section *section([sections_ objectAtIndex:[path section]]);
7333 NSInteger row([path row]);
7334 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7337 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7338 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7340 cell = [[[PackageCell alloc] init] autorelease];
7341 [cell setPackage:[self packageAtIndexPath:path]];
7345 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7346 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7349 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7350 Package *package([self packageAtIndexPath:path]);
7351 PackageController *view([delegate_ packageController]);
7352 [view setDelegate:delegate_];
7353 [view setPackage:package];
7354 [[self navigationController] pushViewController:view animated:YES];
7358 - (void) refreshButtonClicked {
7359 [delegate_ beginUpdate];
7360 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7363 - (void) upgradeButtonClicked {
7364 [delegate_ distUpgrade];
7367 - (NSString *) title { return UCLocalize("CHANGES"); }
7369 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7370 if ((self = [super init]) != nil) {
7371 database_ = database;
7372 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7374 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7376 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7378 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7379 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7380 [list_ setRowHeight:73.0f];
7381 [[self view] addSubview:list_];
7383 [list_ setDataSource:self];
7384 [list_ setDelegate:self];
7386 delegate_ = delegate;
7390 - (void) _reloadPackages:(NSArray *)packages {
7392 for (Package *package in packages)
7393 if ([package upgradableAndEssential:YES] || [package visible])
7394 CFArrayAppendValue(packages_, package);
7397 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7401 - (void) reloadData {
7402 era_ = [database_ era];
7403 NSArray *packages = [database_ packages];
7405 CFArrayRemoveAllValues(packages_);
7407 [sections_ removeAllObjects];
7410 UIProgressHUD *hud([delegate_ addProgressHUD]);
7411 [hud setText:UCLocalize("LOADING")];
7412 //NSLog(@"HUD:%@::%@", delegate_, hud);
7413 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7414 [delegate_ removeProgressHUD:hud];
7416 [self _reloadPackages:packages];
7419 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7420 Section *ignored = nil;
7421 Section *section = nil;
7425 bool unseens = false;
7427 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7429 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7430 Package *package = [self packageAtIndex:offset];
7432 BOOL uae = [package upgradableAndEssential:YES];
7436 time_t seen([package seen]);
7438 if (section == nil || last != seen) {
7442 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7445 _profile(ChangesController$reloadData$Allocate)
7446 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7447 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7448 [sections_ addObject:section];
7452 [section addToCount];
7453 } else if ([package ignored]) {
7454 if (ignored == nil) {
7455 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7457 [ignored addToCount];
7460 [upgradable addToCount];
7465 CFRelease(formatter);
7468 Section *last = [sections_ lastObject];
7469 size_t count = [last count];
7470 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7471 [sections_ removeLastObject];
7474 if ([ignored count] != 0)
7475 [sections_ insertObject:ignored atIndex:0];
7477 [sections_ insertObject:upgradable atIndex:0];
7482 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7483 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7484 style:UIBarButtonItemStylePlain
7486 action:@selector(upgradeButtonClicked)
7489 if (![delegate_ updating])
7490 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7491 initWithTitle:UCLocalize("REFRESH")
7492 style:UIBarButtonItemStylePlain
7494 action:@selector(refreshButtonClicked)
7500 /* Search Controller {{{ */
7501 @interface SearchController : FilteredPackageController <
7504 UISearchBar *search_;
7507 - (id) initWithDatabase:(Database *)database;
7508 - (void) reloadData;
7512 @implementation SearchController
7519 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7520 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7521 [search_ resignFirstResponder];
7525 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7526 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7530 - (NSString *) title { return nil; }
7532 - (id) initWithDatabase:(Database *)database {
7533 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7536 - (void)viewDidAppear:(BOOL)animated {
7537 [super viewDidAppear:animated];
7539 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7540 [search_ layoutSubviews];
7541 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7543 UITextField *textField;
7544 if ([search_ respondsToSelector:@selector(searchField)])
7545 textField = [search_ searchField];
7547 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7549 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7550 [search_ setDelegate:self];
7551 [textField setEnablesReturnKeyAutomatically:NO];
7552 [[self navigationItem] setTitleView:textField];
7556 - (void) _reloadData {
7559 - (void) reloadData {
7560 _profile(SearchController$reloadData)
7561 [packages_ reloadData];
7564 [packages_ resetCursor];
7567 - (void) didSelectPackage:(Package *)package {
7568 [search_ resignFirstResponder];
7569 [super didSelectPackage:package];
7574 /* Settings Controller {{{ */
7575 @interface CYPackageSettingsController : CYViewController <
7576 UITableViewDataSource,
7579 _transient Database *database_;
7582 UITableView *table_;
7583 UISwitch *subscribedSwitch_;
7584 UISwitch *ignoredSwitch_;
7585 UITableViewCell *subscribedCell_;
7586 UITableViewCell *ignoredCell_;
7589 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7593 @implementation CYPackageSettingsController
7597 if (package_ != nil)
7600 [subscribedSwitch_ release];
7601 [ignoredSwitch_ release];
7602 [subscribedCell_ release];
7603 [ignoredCell_ release];
7608 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7609 if (package_ == nil)
7615 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7616 if (package_ == nil)
7622 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7623 return UCLocalize("SHOW_ALL_CHANGES_EX");
7626 - (void) onSubscribed:(id)control {
7627 bool value([control isOn]);
7628 if (package_ == nil)
7630 if ([package_ setSubscribed:value])
7631 [delegate_ updateData];
7634 - (void) onIgnored:(id)control {
7635 // TODO: set Held state - possibly call out to dpkg, etc.
7638 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7639 if (package_ == nil)
7642 switch ([indexPath row]) {
7643 case 0: return subscribedCell_;
7644 case 1: return ignoredCell_;
7652 - (NSString *) title { return UCLocalize("SETTINGS"); }
7654 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7655 if ((self = [super init])) {
7656 database_ = database;
7657 name_ = [package retain];
7659 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7661 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7662 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7663 [[self view] addSubview:table_];
7665 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7666 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7667 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7669 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7670 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7671 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7673 subscribedCell_ = [[UITableViewCell alloc] init];
7674 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7675 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7676 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7678 ignoredCell_ = [[UITableViewCell alloc] init];
7679 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7680 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7681 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7683 [table_ setDataSource:self];
7684 [table_ setDelegate:self];
7689 - (void) reloadData {
7690 if (package_ != nil)
7691 [package_ autorelease];
7692 package_ = [database_ packageWithName:name_];
7693 if (package_ != nil) {
7695 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7696 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7699 [table_ reloadData];
7704 /* Signature Controller {{{ */
7705 @interface SignatureController : CYBrowserController {
7706 _transient Database *database_;
7710 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7714 @implementation SignatureController
7721 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7723 [super webView:view didClearWindowObject:window forFrame:frame];
7726 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7727 if ((self = [super init]) != nil) {
7728 database_ = database;
7729 package_ = [package retain];
7734 - (void) reloadData {
7735 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7741 /* Role Controller {{{ */
7742 @interface CYSettingsController : CYViewController <
7743 UITableViewDataSource,
7746 _transient Database *database_;
7747 // XXX: ok, "roledelegate_"?...
7748 _transient id roledelegate_;
7749 UITableView *table_;
7750 UISegmentedControl *segment_;
7754 - (void) showDoneButton;
7755 - (void) resizeSegmentedControl;
7759 @implementation CYSettingsController
7763 [container_ release];
7768 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7769 if ((self = [super init])) {
7770 database_ = database;
7771 roledelegate_ = delegate;
7773 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7775 NSArray *items = [NSArray arrayWithObjects:
7777 UCLocalize("HACKER"),
7778 UCLocalize("DEVELOPER"),
7780 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7781 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7782 [container_ addSubview:segment_];
7785 if ([Role_ isEqualToString:@"User"]) index = 0;
7786 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7787 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7789 [segment_ setSelectedSegmentIndex:index];
7790 [self showDoneButton];
7793 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7794 [self resizeSegmentedControl];
7796 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7797 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7798 [table_ setDelegate:self];
7799 [table_ setDataSource:self];
7800 [[self view] addSubview:table_];
7801 [table_ reloadData];
7805 - (void) resizeSegmentedControl {
7806 CGFloat width = [[self view] frame].size.width;
7807 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7810 - (void) viewWillAppear:(BOOL)animated {
7811 [super viewWillAppear:animated];
7813 [self resizeSegmentedControl];
7816 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7817 [self resizeSegmentedControl];
7820 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7821 [self resizeSegmentedControl];
7825 NSString *role(nil);
7827 switch ([segment_ selectedSegmentIndex]) {
7828 case 0: role = @"User"; break;
7829 case 1: role = @"Hacker"; break;
7830 case 2: role = @"Developer"; break;
7835 if (![role isEqualToString:Role_]) {
7836 bool rolling(Role_ == nil);
7839 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7843 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7847 [roledelegate_ loadData];
7849 [roledelegate_ updateData];
7853 - (void) segmentChanged:(UISegmentedControl *)control {
7854 [self showDoneButton];
7857 - (void) saveAndClose {
7860 [[self navigationItem] setRightBarButtonItem:nil];
7861 [[self navigationController] dismissModalViewControllerAnimated:YES];
7864 - (void) doneButtonClicked {
7865 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7866 [spinner startAnimating];
7867 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7868 [[self navigationItem] setRightBarButtonItem:spinItem];
7870 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7873 - (void) showDoneButton {
7874 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7875 initWithTitle:UCLocalize("DONE")
7876 style:UIBarButtonItemStyleDone
7878 action:@selector(doneButtonClicked)
7879 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7882 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7883 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7887 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7891 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7892 return nil; // This method is required by the protocol.
7895 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7897 return UCLocalize("ROLE_EX");
7899 return [NSString stringWithFormat:
7900 @"%@: %@\n%@: %@\n%@: %@",
7901 UCLocalize("USER"), UCLocalize("USER_EX"),
7902 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7903 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7908 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7909 return section == 3 ? 44.0f : 0;
7912 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7913 return section == 3 ? container_ : nil;
7918 /* Stash Controller {{{ */
7919 @interface CYStashController : CYViewController {
7920 // XXX: just delete these things
7921 _transient UIActivityIndicatorView *spinner_;
7922 _transient UILabel *status_;
7923 _transient UILabel *caption_;
7927 @implementation CYStashController
7929 if ((self = [super init])) {
7930 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7932 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7933 CGRect spinrect = [spinner_ frame];
7934 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7935 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7936 [spinner_ setFrame:spinrect];
7937 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7938 [[self view] addSubview:spinner_];
7939 [spinner_ startAnimating];
7942 captrect.size.width = [[self view] frame].size.width;
7943 captrect.size.height = 40.0f;
7944 captrect.origin.x = 0;
7945 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7946 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7947 [caption_ setText:@"Initializing Filesystem"];
7948 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7949 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7950 [caption_ setTextColor:[UIColor whiteColor]];
7951 [caption_ setBackgroundColor:[UIColor clearColor]];
7952 [caption_ setShadowColor:[UIColor blackColor]];
7953 [caption_ setTextAlignment:UITextAlignmentCenter];
7954 [[self view] addSubview:caption_];
7957 statusrect.size.width = [[self view] frame].size.width;
7958 statusrect.size.height = 30.0f;
7959 statusrect.origin.x = 0;
7960 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7961 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7962 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7963 [status_ setText:@"(Cydia will exit when complete.)"];
7964 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7965 [status_ setTextColor:[UIColor whiteColor]];
7966 [status_ setBackgroundColor:[UIColor clearColor]];
7967 [status_ setShadowColor:[UIColor blackColor]];
7968 [status_ setTextAlignment:UITextAlignmentCenter];
7969 [[self view] addSubview:status_];
7973 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7974 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7989 @interface Cydia : UIApplication <
7990 ConfirmationControllerDelegate,
7991 ProgressControllerDelegate,
7993 UINavigationControllerDelegate,
7994 UITabBarControllerDelegate
7996 // XXX: evaluate all fields for _transient
7999 CYTabBarController *tabbar_;
8001 NSMutableArray *essential_;
8002 NSMutableArray *broken_;
8004 Database *database_;
8012 SectionsController *sections_;
8013 ChangesController *changes_;
8014 ManageController *manage_;
8015 SearchController *search_;
8016 SourceTable *sources_;
8017 InstalledController *installed_;
8020 CYStashController *stash_;
8025 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
8026 - (void) setPage:(CYViewController *)page;
8029 // XXX: I hate prototypes
8030 - (id) queueBadgeController;
8034 static _finline void _setHomePage(Cydia *self) {
8035 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
8038 @implementation Cydia
8040 - (void) beginUpdate {
8041 [tabbar_ beginUpdate];
8045 return [tabbar_ updating];
8048 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8053 if ([broken_ count] != 0) {
8054 int count = [broken_ count];
8056 UIAlertView *alert = [[[UIAlertView alloc]
8057 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8058 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8060 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8061 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8064 [alert setContext:@"fixhalf"];
8066 } else if (!Ignored_ && [essential_ count] != 0) {
8067 int count = [essential_ count];
8069 UIAlertView *alert = [[[UIAlertView alloc]
8070 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8071 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8073 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8074 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8077 [alert setContext:@"upgrade"];
8082 - (void) _saveConfig {
8088 NSString *error(nil);
8090 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8092 NSError *error(nil);
8093 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8094 NSLog(@"failure to save metadata data: %@", error);
8099 NSLog(@"failure to serialize metadata: %@", error);
8104 - (void) _updateData {
8107 /* XXX: this is just stupid */
8108 if (tag_ != 1 && sections_ != nil)
8109 [sections_ reloadData];
8110 if (tag_ != 2 && changes_ != nil)
8111 [changes_ reloadData];
8112 if (tag_ != 4 && search_ != nil)
8113 [search_ reloadData];
8115 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8117 [queueDelegate_ queueStatusDidChange];
8118 [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8121 - (int)indexOfTabWithTag:(int)tag {
8123 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8124 if ([[controller tabBarItem] tag] == tag)
8132 - (void) _refreshIfPossible {
8133 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8135 bool recently = false;
8136 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8137 if (update != nil) {
8138 NSTimeInterval interval([update timeIntervalSinceNow]);
8139 if (interval <= 0 && interval > -(15*60))
8143 // Don't automatic refresh if:
8144 // - We already refreshed recently.
8145 // - We already auto-refreshed this launch.
8146 // - Auto-refresh is disabled.
8147 if (recently || loaded_ || ManualRefresh) {
8148 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8150 // If we are cancelling due to ManualRefresh or a recent refresh
8151 // we need to make sure it knows it's already loaded.
8155 // We are going to load, so remember that.
8159 SCNetworkReachabilityFlags flags; {
8160 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8161 SCNetworkReachabilityGetFlags(reachability, &flags);
8162 CFRelease(reachability);
8165 // XXX: this elaborate mess is what Apple is using to determine this? :(
8166 // XXX: do we care if the user has to intervene? maybe that's ok?
8168 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8169 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8170 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8171 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8172 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8173 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8177 // If we can reach the server, auto-refresh!
8179 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8184 - (void) refreshIfPossible {
8185 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8188 - (void) _reloadData {
8189 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8190 [hud setText:UCLocalize("RELOADING_DATA")];
8192 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8195 [self removeProgressHUD:hud];
8199 [essential_ removeAllObjects];
8200 [broken_ removeAllObjects];
8202 NSArray *packages([database_ packages]);
8203 for (Package *package in packages) {
8205 [broken_ addObject:package];
8206 if ([package upgradableAndEssential:NO]) {
8207 if ([package essential])
8208 [essential_ addObject:package];
8213 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8215 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8216 [changesItem setBadgeValue:badge];
8217 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8219 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8220 [self setApplicationBadge:badge];
8222 [self setApplicationBadgeString:badge];
8224 [changesItem setBadgeValue:nil];
8225 [changesItem setAnimatedBadge:NO];
8227 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8228 [self removeApplicationBadge];
8229 else // XXX: maybe use setApplicationBadgeString also?
8230 [self setApplicationIconBadgeNumber:0];
8235 [self refreshIfPossible];
8238 - (void) updateData {
8247 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8248 _assert(file != NULL);
8250 for (NSString *key in [Sources_ allKeys]) {
8251 NSDictionary *source([Sources_ objectForKey:key]);
8253 fprintf(file, "%s %s %s\n",
8254 [[source objectForKey:@"Type"] UTF8String],
8255 [[source objectForKey:@"URI"] UTF8String],
8256 [[source objectForKey:@"Distribution"] UTF8String]
8264 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8265 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8267 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8268 [tabbar_ presentModalViewController:navigation animated:YES];
8271 detachNewThreadSelector:@selector(update_)
8274 title:UCLocalize("UPDATING_SOURCES")
8278 - (void) reloadData {
8279 @synchronized (self) {
8285 pkgProblemResolver *resolver = [database_ resolver];
8287 resolver->InstallProtect();
8288 if (!resolver->Resolve(true))
8292 - (CGRect) popUpBounds {
8293 return [[tabbar_ view] bounds];
8297 if (![database_ prepare])
8300 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8301 [page setDelegate:self];
8302 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8303 [confirm_ setDelegate:self];
8306 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8307 [tabbar_ presentModalViewController:confirm_ animated:YES];
8313 @synchronized (self) {
8318 - (void) clearPackage:(Package *)package {
8319 @synchronized (self) {
8326 - (void) installPackages:(NSArray *)packages {
8327 @synchronized (self) {
8328 for (Package *package in packages)
8335 - (void) installPackage:(Package *)package {
8336 @synchronized (self) {
8343 - (void) removePackage:(Package *)package {
8344 @synchronized (self) {
8351 - (void) distUpgrade {
8352 @synchronized (self) {
8353 if (![database_ upgrade])
8360 @synchronized (self) {
8365 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8368 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8370 if (navigation != nil) {
8371 [navigation pushViewController:progress animated:YES];
8373 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8375 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8376 [tabbar_ presentModalViewController:navigation animated:YES];
8380 detachNewThreadSelector:@selector(perform)
8383 title:UCLocalize("RUNNING")
8389 - (void) progressControllerIsComplete:(ProgressController *)progress {
8394 - (void) setPage:(CYViewController *)page {
8395 [page setDelegate:self];
8397 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8398 [navController setViewControllers:[NSArray arrayWithObject:page]];
8399 for (CYNavigationController *page in [tabbar_ viewControllers])
8400 if (page != navController)
8401 [page setViewControllers:nil];
8404 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8405 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8406 [browser loadURL:url];
8410 - (SectionsController *) sectionsController {
8411 if (sections_ == nil)
8412 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8416 - (ChangesController *) changesController {
8417 if (changes_ == nil)
8418 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8422 - (ManageController *) manageController {
8423 if (manage_ == nil) {
8424 manage_ = (ManageController *) [[self
8425 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8426 withClass:[ManageController class]
8429 queueDelegate_ = manage_;
8434 - (SearchController *) searchController {
8436 search_ = [[SearchController alloc] initWithDatabase:database_];
8440 - (SourceTable *) sourcesController {
8441 if (sources_ == nil)
8442 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8446 - (InstalledController *) installedController {
8447 if (installed_ == nil) {
8448 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8450 queueDelegate_ = installed_;
8455 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8456 int tag = [[viewController tabBarItem] tag];
8458 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8460 } else if (tag_ == 1) {
8461 [[self sectionsController] resetView];
8465 case kCydiaTag: _setHomePage(self); break;
8467 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8468 case kChangesTag: [self setPage:[self changesController]]; break;
8469 case kManageTag: [self setPage:[self manageController]]; break;
8470 case kInstalledTag: [self setPage:[self installedController]]; break;
8471 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8472 case kSearchTag: [self setPage:[self searchController]]; break;
8480 - (void) showSettings {
8481 CYSettingsController *role = [[[CYSettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8482 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8484 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8485 [tabbar_ presentModalViewController:nav animated:YES];
8488 - (void) retainNetworkActivityIndicator {
8489 if (activity_++ == 0)
8490 [self setNetworkActivityIndicatorVisible:YES];
8493 - (void) releaseNetworkActivityIndicator {
8494 if (--activity_ == 0)
8495 [self setNetworkActivityIndicatorVisible:NO];
8498 - (void) setPackageController:(PackageController *)view {
8500 [view setPackage:nil];
8504 - (PackageController *) _packageController {
8505 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8508 - (PackageController *) packageController {
8509 return [self _packageController];
8512 // Returns the navigation controller for the queuing badge.
8513 - (id) queueBadgeController {
8514 int index = [self indexOfTabWithTag:kManageTag];
8516 index = [self indexOfTabWithTag:kInstalledTag];
8518 return [[tabbar_ viewControllers] objectAtIndex:index];
8521 - (void) cancelAndClear:(bool)clear {
8522 @synchronized (self) {
8534 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8535 NSString *context([alert context]);
8537 if ([context isEqualToString:@"fixhalf"]) {
8538 if (button == [alert firstOtherButtonIndex]) {
8539 @synchronized (self) {
8540 for (Package *broken in broken_) {
8543 NSString *id = [broken id];
8544 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8545 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8546 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8547 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8553 } else if (button == [alert cancelButtonIndex]) {
8554 [broken_ removeAllObjects];
8558 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8559 } else if ([context isEqualToString:@"upgrade"]) {
8560 if (button == [alert firstOtherButtonIndex]) {
8561 @synchronized (self) {
8562 for (Package *essential in essential_)
8563 [essential install];
8568 } else if (button == [alert firstOtherButtonIndex] + 1) {
8570 } else if (button == [alert cancelButtonIndex]) {
8574 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8578 - (void) system:(NSString *)command { _pooled
8579 system([command UTF8String]);
8582 - (void) applicationWillSuspend {
8584 [super applicationWillSuspend];
8587 - (BOOL) isSafeToSuspend {
8588 // Use external process status API internally.
8589 // This is probably a really bad idea.
8590 // XXX: what is the point of this? does this solve anything at all?
8591 uint64_t status = 0;
8593 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8594 notify_get_state(notify_token, &status);
8595 notify_cancel(notify_token);
8598 return locked_ == 0 && status == 0;
8601 - (void) applicationSuspend:(__GSEvent *)event {
8602 if ([self isSafeToSuspend])
8603 [super applicationSuspend:event];
8606 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8607 if ([self isSafeToSuspend])
8608 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8611 - (void) _setSuspended:(BOOL)value {
8612 if ([self isSafeToSuspend])
8613 [super _setSuspended:value];
8616 - (UIProgressHUD *) addProgressHUD {
8617 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8618 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8620 [window_ setUserInteractionEnabled:NO];
8623 UIViewController *target = tabbar_;
8624 while ([target modalViewController] != nil) target = [target modalViewController];
8625 [[target view] addSubview:hud];
8631 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8633 [hud removeFromSuperview];
8634 [window_ setUserInteractionEnabled:YES];
8638 - (CYViewController *) pageForPackage:(NSString *)name {
8639 if (Package *package = [database_ packageWithName:name]) {
8640 PackageController *view([self packageController]);
8641 [view setPackage:package];
8644 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8645 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8646 return [self _pageForURL:url withClass:[CYBrowserController class]];
8650 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8654 NSString *href([url absoluteString]);
8655 if ([href hasPrefix:@"apptapp://package/"])
8656 return [self pageForPackage:[href substringFromIndex:18]];
8658 NSString *scheme([[url scheme] lowercaseString]);
8659 if (![scheme isEqualToString:@"cydia"])
8661 NSString *path([url absoluteString]);
8662 if ([path length] < 8)
8664 path = [path substringFromIndex:8];
8665 if (![path hasPrefix:@"/"])
8666 path = [@"/" stringByAppendingString:path];
8668 if ([path isEqualToString:@"/add-source"])
8669 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8670 else if ([path isEqualToString:@"/storage"])
8671 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8672 else if ([path isEqualToString:@"/sources"])
8673 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8674 else if ([path isEqualToString:@"/packages"])
8675 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8676 else if ([path hasPrefix:@"/url/"])
8677 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8678 else if ([path hasPrefix:@"/launch/"])
8679 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8680 else if ([path hasPrefix:@"/package-settings/"])
8681 return [[[CYPackageSettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8682 else if ([path hasPrefix:@"/package-signature/"])
8683 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8684 else if ([path hasPrefix:@"/package/"])
8685 return [self pageForPackage:[path substringFromIndex:9]];
8686 else if ([path hasPrefix:@"/files/"]) {
8687 NSString *name = [path substringFromIndex:7];
8689 if (Package *package = [database_ packageWithName:name]) {
8690 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8691 [files setPackage:package];
8699 - (BOOL) openCydiaURL:(NSURL *)url {
8700 CYViewController *page = nil;
8703 NSLog(@"open url: %@", url);
8705 if ((page = [self pageForURL:url hasTag:&tag])) {
8706 [self setPage:page];
8708 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8714 - (void) applicationOpenURL:(NSURL *)url {
8715 [super applicationOpenURL:url];
8716 NSLog(@"first: %@", url);
8717 if (!loaded_) starturl_ = [url retain];
8718 else [self openCydiaURL:url];
8721 - (void) applicationWillResignActive:(UIApplication *)application {
8722 // Stop refreshing if you get a phone call or lock the device.
8723 if ([tabbar_ updating])
8724 [tabbar_ cancelUpdate];
8726 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8727 [super applicationWillResignActive:application];
8730 - (void) addStashController {
8732 stash_ = [[CYStashController alloc] init];
8733 [window_ addSubview:[stash_ view]];
8736 - (void) removeStashController {
8737 [[stash_ view] removeFromSuperview];
8743 [self setIdleTimerDisabled:YES];
8745 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8746 [self setStatusBarShowsProgress:YES];
8747 UpdateExternalStatus(1);
8749 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8751 UpdateExternalStatus(0);
8752 [self setStatusBarShowsProgress:NO];
8754 [self removeStashController];
8756 if (ExecFork() == 0) {
8757 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8758 perror("launchctl stop");
8762 - (void) setupTabBarController {
8763 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8764 [tabbar_ setDelegate:self];
8766 NSMutableArray *items([NSMutableArray arrayWithObjects:
8767 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8768 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8769 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8770 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8774 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8775 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8777 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8780 NSMutableArray *controllers([NSMutableArray array]);
8782 for (UITabBarItem *item in items) {
8783 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8784 [controller setTabBarItem:item];
8785 [controllers addObject:controller];
8788 [tabbar_ setViewControllers:controllers];
8791 - (void) applicationDidFinishLaunching:(id)unused {
8795 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
8796 initWithMemoryCapacity:524288
8797 diskCapacity:10485760
8798 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
8801 [CYBrowserController _initialize];
8803 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8805 Font12_ = [[UIFont systemFontOfSize:12] retain];
8806 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8807 Font14_ = [[UIFont systemFontOfSize:14] retain];
8808 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8809 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8813 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8814 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8816 UIScreen *screen([UIScreen mainScreen]);
8818 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8819 [window_ orderFront:self];
8820 [window_ makeKey:self];
8821 [window_ setHidden:NO];
8824 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8825 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8826 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8827 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8828 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8829 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8830 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8831 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8832 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8835 [self addStashController];
8836 // XXX: this would be much cleaner as a yieldToSelector:
8837 // that way the removeStashController could happen right here inline
8838 // we also could no longer require the useless stash_ field anymore
8839 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8843 database_ = [Database sharedInstance];
8845 [self setupTabBarController];
8846 [tabbar_ setUpdateDelegate:self];
8847 [window_ addSubview:[tabbar_ view]];
8849 // Show pinstripes while loading data.
8850 [[tabbar_ view] setBackgroundColor:[UIColor pinStripeColor]];
8852 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8859 [self showSettings];
8863 [window_ setUserInteractionEnabled:NO];
8865 UIView *container = [[[UIView alloc] init] autorelease];
8866 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8868 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8869 [spinner startAnimating];
8870 [container addSubview:spinner];
8872 UILabel *label = [[[UILabel alloc] init] autorelease];
8873 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8874 [label setBackgroundColor:[UIColor clearColor]];
8875 [label setTextColor:[UIColor blackColor]];
8876 [label setShadowColor:[UIColor whiteColor]];
8877 [label setShadowOffset:CGSizeMake(0, 1)];
8878 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8879 [container addSubview:label];
8881 CGSize viewsize = [[tabbar_ view] frame].size;
8882 CGSize spinnersize = [spinner bounds].size;
8883 CGSize textsize = [[label text] sizeWithFont:[label font]];
8884 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8886 CGRect containrect = {
8887 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8888 CGSizeMake(bothwidth, spinnersize.height)
8891 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8899 [container setFrame:containrect];
8900 [spinner setFrame:spinrect];
8901 [label setFrame:textrect];
8902 [[tabbar_ view] addSubview:container];
8907 // Show the initial page
8908 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
8909 [tabbar_ setSelectedIndex:0];
8913 [starturl_ release];
8916 [window_ setUserInteractionEnabled:YES];
8918 // XXX: does this actually slow anything down?
8919 [[tabbar_ view] setBackgroundColor:[UIColor clearColor]];
8920 [container removeFromSuperview];
8923 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8924 if (item != nil && IsWildcat_) {
8925 [sheet showFromBarButtonItem:item animated:YES];
8927 [sheet showInView:window_];
8934 id Alloc_(id self, SEL selector) {
8935 id object = alloc_(self, selector);
8936 lprintf("[%s]A-%p\n", self->isa->name, object);
8941 id Dealloc_(id self, SEL selector) {
8942 id object = dealloc_(self, selector);
8943 lprintf("[%s]D-%p\n", self->isa->name, object);
8947 Class $WebDefaultUIKitDelegate;
8949 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8950 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8951 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8952 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8955 static NSNumber *shouldPlayKeyboardSounds;
8959 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8961 case 1104: // Keyboard Button Clicked
8962 case 1105: // Keyboard Delete Repeated
8963 if (shouldPlayKeyboardSounds == nil) {
8964 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8965 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8968 if (![shouldPlayKeyboardSounds boolValue])
8972 _UIHardware$_playSystemSound$(self, _cmd, sound);
8976 int main(int argc, char *argv[]) { _pooled
8979 if (Class $UIDevice = objc_getClass("UIDevice")) {
8980 UIDevice *device([$UIDevice currentDevice]);
8981 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8985 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8987 /* Library Hacks {{{ */
8988 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8990 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8991 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8992 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8993 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8994 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8997 $UIHardware = objc_getClass("UIHardware");
8998 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8999 if (UIHardware$_playSystemSound$ != NULL) {
9000 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9001 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9004 /* Set Locale {{{ */
9005 Locale_ = CFLocaleCopyCurrent();
9006 Languages_ = [NSLocale preferredLanguages];
9007 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9008 //NSLog(@"%@", [Languages_ description]);
9011 if (Languages_ == nil || [Languages_ count] == 0)
9012 // XXX: consider just setting to C and then falling through?
9015 lang = [[Languages_ objectAtIndex:0] UTF8String];
9016 setenv("LANG", lang, true);
9019 //std::setlocale(LC_ALL, lang);
9020 NSLog(@"Setting Language: %s", lang);
9023 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9025 /* Parse Arguments {{{ */
9026 bool substrate(false);
9032 for (int argi(1); argi != argc; ++argi)
9033 if (strcmp(argv[argi], "--") == 0) {
9035 argv[argi] = argv[0];
9041 for (int argi(1); argi != arge; ++argi)
9042 if (strcmp(args[argi], "--substrate") == 0)
9045 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9049 App_ = [[NSBundle mainBundle] bundlePath];
9050 Home_ = NSHomeDirectory();
9056 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9057 alloc_ = alloc->method_imp;
9058 alloc->method_imp = (IMP) &Alloc_;*/
9060 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9061 dealloc_ = dealloc->method_imp;
9062 dealloc->method_imp = (IMP) &Dealloc_;*/
9064 /* System Information {{{ */
9068 size = sizeof(maxproc);
9069 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9070 perror("sysctlbyname(\"kern.maxproc\", ?)");
9071 else if (maxproc < 64) {
9073 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9074 perror("sysctlbyname(\"kern.maxproc\", #)");
9077 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9078 char *osversion = new char[size];
9079 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9080 perror("sysctlbyname(\"kern.osversion\", ?)");
9082 System_ = [NSString stringWithUTF8String:osversion];
9084 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9085 char *machine = new char[size];
9086 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9087 perror("sysctlbyname(\"hw.machine\", ?)");
9091 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9092 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9093 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9094 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9098 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9099 NSData *data((NSData *) ecid);
9100 size_t length([data length]);
9101 uint8_t bytes[length];
9102 [data getBytes:bytes];
9103 char string[length * 2 + 1];
9104 for (size_t i(0); i != length; ++i)
9105 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9106 ChipID_ = [NSString stringWithUTF8String:string];
9110 IOObjectRelease(service);
9114 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9116 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9117 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9118 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9120 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9121 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9122 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9124 if (mcc != NULL && mnc != NULL)
9125 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9132 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9133 Build_ = [system objectForKey:@"ProductBuildVersion"];
9134 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9135 Product_ = [info objectForKey:@"SafariProductVersion"];
9136 Safari_ = [info objectForKey:@"CFBundleVersion"];
9139 /* Load Database {{{ */
9141 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9143 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9145 if (Metadata_ == NULL)
9146 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9148 Settings_ = [Metadata_ objectForKey:@"Settings"];
9150 Packages_ = [Metadata_ objectForKey:@"Packages"];
9151 Sections_ = [Metadata_ objectForKey:@"Sections"];
9152 Sources_ = [Metadata_ objectForKey:@"Sources"];
9154 Token_ = [Metadata_ objectForKey:@"Token"];
9157 if (Settings_ != nil)
9158 Role_ = [Settings_ objectForKey:@"Role"];
9160 if (Sections_ == nil) {
9161 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9162 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9165 if (Sources_ == nil) {
9166 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9167 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9172 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9175 if (Packages_ != nil) {
9176 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9178 [Metadata_ removeObjectForKey:@"Packages"];
9183 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9185 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9186 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9187 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9188 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9189 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9190 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9192 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9194 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9195 unlink("/tmp/.cydia.fw");
9197 } else if (access("/User", F_OK) != 0 || version < 2) {
9200 system("/usr/libexec/cydia/firmware.sh");
9204 _assert([[NSFileManager defaultManager]
9205 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9206 withIntermediateDirectories:YES
9211 if (access("/tmp/cydia.chk", F_OK) == 0) {
9212 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9213 _assert(errno == ENOENT);
9214 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9215 _assert(errno == ENOENT);
9218 /* APT Initialization {{{ */
9219 _assert(pkgInitConfig(*_config));
9220 _assert(pkgInitSystem(*_config, _system));
9223 _config->Set("APT::Acquire::Translation", lang);
9225 // XXX: this timeout might be important :(
9226 //_config->Set("Acquire::http::Timeout", 15);
9228 _config->Set("Acquire::http::MaxParallel", 3);
9230 /* Color Choices {{{ */
9231 space_ = CGColorSpaceCreateDeviceRGB();
9233 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9234 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9235 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9236 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9237 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9238 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9239 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9240 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9241 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9243 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9244 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9246 /* UIKit Configuration {{{ */
9247 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9248 if ($GSFontSetUseLegacyFontMetrics != NULL)
9249 $GSFontSetUseLegacyFontMetrics(YES);
9251 // XXX: I have a feeling this was important
9252 //UIKeyboardDisableAutomaticAppearance();
9255 Colon_ = UCLocalize("COLON_DELIMITED");
9256 Elision_ = UCLocalize("ELISION");
9257 Error_ = UCLocalize("ERROR");
9258 Warning_ = UCLocalize("WARNING");
9261 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9263 CGColorSpaceRelease(space_);