1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
111 #include <mach-o/nlist.h>
121 #include <Cytore.hpp>
123 #include "UICaboodle/BrowserView.h"
124 #include "SDURLCache/SDURLCache.h"
126 #include "substrate.h"
133 #define _timestamp ({ \
135 gettimeofday(&tv, NULL); \
136 tv.tv_sec * 1000000 + tv.tv_usec; \
139 typedef std::vector<class ProfileTime *> TimeList;
149 ProfileTime(const char *name) :
153 times_.push_back(this);
156 void AddTime(uint64_t time) {
163 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
175 ProfileTimer(ProfileTime &time) :
182 time_.AddTime(_timestamp - start_);
187 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
189 std::cerr << "========" << std::endl;
192 #define _profile(name) { \
193 static ProfileTime name(#name); \
194 ProfileTimer _ ## name(name);
199 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
201 #define CYPoolStart() \
202 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
204 #define CYPoolEnd() \
208 // Hash Functions/Structures {{{
209 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
217 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
219 void NSLogPoint(const char *fix, const CGPoint &point) {
220 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
223 void NSLogRect(const char *fix, const CGRect &rect) {
224 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
227 static _finline NSString *CydiaURL(NSString *path) {
229 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
230 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
231 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
232 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
233 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
234 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
237 static _finline void UpdateExternalStatus(uint64_t newStatus) {
239 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
240 notify_set_state(notify_token, newStatus);
241 notify_cancel(notify_token);
243 notify_post("com.saurik.Cydia.status");
246 /* [NSObject yieldToSelector:(withObject:)] {{{*/
247 @interface NSObject (Cydia)
248 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
249 - (id) yieldToSelector:(SEL)selector;
252 @implementation NSObject (Cydia)
257 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
258 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
259 id object([[context objectAtIndex:1] nonretainedObjectValue]);
260 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
262 /* XXX: deal with exceptions */
263 id value([self performSelector:selector withObject:object]);
265 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
266 [context removeAllObjects];
267 if ([signature methodReturnLength] != 0 && value != nil)
268 [context addObject:value];
273 performSelectorOnMainThread:@selector(doNothing)
279 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
280 volatile bool stopped(false);
282 NSMutableArray *context([NSMutableArray arrayWithObjects:
283 [NSValue valueWithPointer:selector],
284 [NSValue valueWithNonretainedObject:object],
285 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
288 NSThread *thread([[[NSThread alloc]
290 selector:@selector(_yieldToContext:)
296 NSRunLoop *loop([NSRunLoop currentRunLoop]);
297 NSDate *future([NSDate distantFuture]);
299 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
301 return [context count] == 0 ? nil : [context objectAtIndex:0];
304 - (id) yieldToSelector:(SEL)selector {
305 return [self yieldToSelector:selector withObject:nil];
311 /* Cydia Action Sheet {{{ */
312 @interface CYActionSheet : UIAlertView {
316 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
319 @implementation CYActionSheet
321 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
322 if ((self = [super init])) {
323 [self setTitle:title];
324 [self setDelegate:self];
325 for (NSString *button in buttons) [self addButtonWithTitle:button];
326 [self setCancelButtonIndex:index];
330 - (void) _updateFrameForDisplay {
331 [super _updateFrameForDisplay];
332 if ([self cancelButtonIndex] == -1) {
333 NSArray *buttons = [self buttons];
334 if ([buttons count]) {
335 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
336 for (UIThreePartButton *button in buttons)
337 [button setBackground:background forState:0];
342 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
343 button_ = buttonIndex + 1;
347 [self dismissWithClickedButtonIndex:-1 animated:YES];
350 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
351 [self setRunsModal:YES];
360 /* NSForcedOrderingSearch doesn't work on the iPhone */
361 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
362 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
363 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
365 /* Information Dictionaries {{{ */
366 @interface NSMutableArray (Cydia)
367 - (void) addInfoDictionary:(NSDictionary *)info;
370 @implementation NSMutableArray (Cydia)
372 - (void) addInfoDictionary:(NSDictionary *)info {
373 [self addObject:info];
378 @interface NSMutableDictionary (Cydia)
379 - (void) addInfoDictionary:(NSDictionary *)info;
382 @implementation NSMutableDictionary (Cydia)
384 - (void) addInfoDictionary:(NSDictionary *)info {
385 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
391 #define lprintf(args...) fprintf(stderr, args)
394 #define TraceLogging (1 && !ForRelease)
395 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
396 #define ProfileTimes (0 && !ForRelease)
397 #define ForSaurik (0 && !ForRelease)
398 #define LogBrowser (0 && !ForRelease)
399 #define TrackResize (0 && !ForRelease)
400 #define ManualRefresh (1 && !ForRelease)
401 #define ShowInternals (0 && !ForRelease)
402 #define IgnoreInstall (0 && !ForRelease)
403 #define AlwaysReload (0 && !ForRelease)
407 #define _trace(args...)
412 #define _profile(name) {
415 #define PrintTimes() do {} while (false)
419 typedef uint32_t (*SKRadixFunction)(id, void *);
421 @interface NSMutableArray (Radix)
422 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
430 @implementation NSMutableArray (Radix)
432 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
433 size_t count([self count]);
434 struct RadixItem_ *swap(new RadixItem_[count * 2]);
436 for (size_t i(0); i != count; ++i) {
437 RadixItem_ &item(swap[i]);
440 id object([self objectAtIndex:i]);
441 item.key = function(object, argument);
444 struct RadixItem_ *lhs(swap), *rhs(swap + count);
446 static const size_t width = 32;
447 static const size_t bits = 11;
448 static const size_t slots = 1 << bits;
449 static const size_t passes = (width + (bits - 1)) / bits;
451 size_t *hist(new size_t[slots]);
453 for (size_t pass(0); pass != passes; ++pass) {
454 memset(hist, 0, sizeof(size_t) * slots);
456 for (size_t i(0); i != count; ++i) {
457 uint32_t key(lhs[i].key);
459 key &= _not(uint32_t) >> width - bits;
464 for (size_t i(0); i != slots; ++i) {
465 size_t local(offset);
470 for (size_t i(0); i != count; ++i) {
471 uint32_t key(lhs[i].key);
473 key &= _not(uint32_t) >> width - bits;
474 rhs[hist[key]++] = lhs[i];
477 RadixItem_ *tmp(lhs);
484 const void **values(new const void *[count]);
485 for (size_t i(0); i != count; ++i)
486 values[i] = [self objectAtIndex:lhs[i].index];
487 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
495 /* Insertion Sort {{{ */
497 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
498 const char *ptr = (const char *)list;
500 CFIndex half = count / 2;
501 const char *probe = ptr + elementSize * half;
502 CFComparisonResult cr = comparator(element, probe, context);
503 if (0 == cr) return (probe - (const char *)list) / elementSize;
504 ptr = (cr < 0) ? ptr : probe + elementSize;
505 count = (cr < 0) ? half : (half + (count & 1) - 1);
507 return (ptr - (const char *)list) / elementSize;
510 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
511 const char *ptr = (const char *)list;
513 CFIndex half = count / 2;
514 const char *probe = ptr + elementSize * half;
515 CFComparisonResult cr = comparator(element, probe, context);
516 if (0 == cr) return (probe - (const char *)list) / elementSize;
517 ptr = (cr < 0) ? ptr : probe + elementSize;
518 count = (cr < 0) ? half : (half + (count & 1) - 1);
520 return (ptr - (const char *)list) / elementSize;
523 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
524 if (range.length == 0)
526 const void **values(new const void *[range.length]);
527 CFArrayGetValues(array, range, values);
529 #if HistogramInsertionSort > 0
530 uint32_t total(0), *offsets(new uint32_t[range.length]);
533 for (CFIndex index(1); index != range.length; ++index) {
534 const void *value(values[index]);
535 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
536 CFIndex correct(index);
537 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
538 #if HistogramInsertionSort > 1
539 NSLog(@"%@ < %@", value, values[correct - 1]);
544 if (correct != index) {
545 size_t offset(index - correct);
546 #if HistogramInsertionSort
550 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
552 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
553 values[correct] = value;
557 CFArrayReplaceValues(array, range, values, range.length);
560 #if HistogramInsertionSort > 0
561 for (CFIndex index(0); index != range.length; ++index)
562 if (offsets[index] != 0)
563 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
564 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
571 /* Apple Bug Fixes {{{ */
572 @implementation UIWebDocumentView (Cydia)
574 - (void) _setScrollerOffset:(CGPoint)offset {
575 UIScroller *scroller([self _scroller]);
577 CGSize size([scroller contentSize]);
578 CGSize bounds([scroller bounds].size);
581 max.x = size.width - bounds.width;
582 max.y = size.height - bounds.height;
590 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
591 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
593 [scroller setOffset:offset];
599 @implementation WebScriptObject (NSFastEnumeration)
601 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
602 size_t length([self count] - state->state);
605 else if (length > count)
607 for (size_t i(0); i != length; ++i)
608 objects[i] = [self objectAtIndex:state->state++];
609 state->itemsPtr = objects;
610 state->mutationsPtr = (unsigned long *) self;
616 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
617 size_t length([self length] - state->state);
620 else if (length > count)
622 for (size_t i(0); i != length; ++i)
623 objects[i] = [self item:state->state++];
624 state->itemsPtr = objects;
625 state->mutationsPtr = (unsigned long *) self;
629 /* Cydia NSString Additions {{{ */
630 @interface NSString (Cydia)
631 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
632 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
633 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
634 - (NSComparisonResult) compareByPath:(NSString *)other;
635 - (NSString *) stringByCachingURLWithCurrentCDN;
636 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
639 @implementation NSString (Cydia)
641 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
642 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
645 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
646 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
647 memcpy(data, bytes, length);
648 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
651 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
652 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
655 - (NSComparisonResult) compareByPath:(NSString *)other {
656 NSString *prefix = [self commonPrefixWithString:other options:0];
657 size_t length = [prefix length];
659 NSRange lrange = NSMakeRange(length, [self length] - length);
660 NSRange rrange = NSMakeRange(length, [other length] - length);
662 lrange = [self rangeOfString:@"/" options:0 range:lrange];
663 rrange = [other rangeOfString:@"/" options:0 range:rrange];
665 NSComparisonResult value;
667 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
668 value = NSOrderedSame;
669 else if (lrange.location == NSNotFound)
670 value = NSOrderedAscending;
671 else if (rrange.location == NSNotFound)
672 value = NSOrderedDescending;
674 value = NSOrderedSame;
676 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
677 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
678 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
679 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
681 NSComparisonResult result = [lpath compare:rpath];
682 return result == NSOrderedSame ? value : result;
685 - (NSString *) stringByCachingURLWithCurrentCDN {
687 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
688 withString:@"://cache.cydia.saurik.com/"
692 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
693 return [(id)CFURLCreateStringByAddingPercentEscapes(
698 kCFStringEncodingUTF8
705 /* C++ NSString Wrapper Cache {{{ */
706 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
707 return size == 0 ? NULL :
708 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
709 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
712 static _finline CFStringRef CYStringCreate(const char *data) {
713 return CYStringCreate(data, strlen(data));
722 _finline void clear_() {
723 if (cache_ != NULL) {
730 _finline bool empty() const {
734 _finline size_t size() const {
738 _finline char *data() const {
742 _finline void clear() {
747 _finline CYString() :
754 _finline ~CYString() {
758 void operator =(const CYString &rhs) {
762 if (rhs.cache_ == nil)
765 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
768 void copy(apr_pool_t *pool) {
769 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
770 memcpy(temp, data_, size_);
775 void set(apr_pool_t *pool, const char *data, size_t size) {
781 data_ = const_cast<char *>(data);
789 _finline void set(apr_pool_t *pool, const char *data) {
790 set(pool, data, data == NULL ? 0 : strlen(data));
793 _finline void set(apr_pool_t *pool, const std::string &rhs) {
794 set(pool, rhs.data(), rhs.size());
797 bool operator ==(const CYString &rhs) const {
798 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
801 _finline operator CFStringRef() {
803 cache_ = CYStringCreate(data_, size_);
807 _finline operator id() {
808 return (NSString *) static_cast<CFStringRef>(*this);
811 _finline operator const char *() {
812 return reinterpret_cast<const char *>(data_);
816 /* C++ NSString Algorithm Adapters {{{ */
818 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
821 struct NSStringMapHash :
822 std::unary_function<NSString *, size_t>
824 _finline size_t operator ()(NSString *value) const {
825 return CFStringHashNSString((CFStringRef) value);
829 struct NSStringMapLess :
830 std::binary_function<NSString *, NSString *, bool>
832 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
833 return [lhs compare:rhs] == NSOrderedAscending;
837 struct NSStringMapEqual :
838 std::binary_function<NSString *, NSString *, bool>
840 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
841 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
842 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
843 //[lhs isEqualToString:rhs];
848 /* Perl-Compatible RegEx {{{ */
858 Pcre(const char *regex) :
863 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
866 lprintf("%d:%s\n", offset, error);
870 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
871 matches_ = new int[(capture_ + 1) * 3];
879 NSString *operator [](size_t match) {
880 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
883 bool operator ()(NSString *data) {
884 // XXX: length is for characters, not for bytes
885 return operator ()([data UTF8String], [data length]);
888 bool operator ()(const char *data, size_t size) {
890 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
894 /* Mime Addresses {{{ */
895 @interface Address : NSObject {
901 - (NSString *) address;
903 - (void) setAddress:(NSString *)address;
905 + (Address *) addressWithString:(NSString *)string;
906 - (Address *) initWithString:(NSString *)string;
909 @implementation Address
918 - (NSString *) name {
922 - (NSString *) address {
926 - (void) setAddress:(NSString *)address {
928 [address_ autorelease];
932 address_ = [address retain];
935 + (Address *) addressWithString:(NSString *)string {
936 return [[[Address alloc] initWithString:string] autorelease];
939 + (NSArray *) _attributeKeys {
940 return [NSArray arrayWithObjects:@"address", @"name", nil];
943 - (NSArray *) attributeKeys {
944 return [[self class] _attributeKeys];
947 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
948 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
951 - (Address *) initWithString:(NSString *)string {
952 if ((self = [super init]) != nil) {
953 const char *data = [string UTF8String];
954 size_t size = [string length];
956 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
958 if (address_r(data, size)) {
959 name_ = [address_r[1] retain];
960 address_ = [address_r[2] retain];
962 name_ = [string retain];
970 /* CoreGraphics Primitives {{{ */
975 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
976 CGFloat color[] = {red, green, blue, alpha};
977 return CGColorCreate(space, color);
986 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
987 color_(Create_(space, red, green, blue, alpha))
989 Set(space, red, green, blue, alpha);
994 CGColorRelease(color_);
1001 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1003 color_ = Create_(space, red, green, blue, alpha);
1006 operator CGColorRef() {
1012 /* Random Global Variables {{{ */
1013 static const int PulseInterval_ = 50000;
1014 static const int ButtonBarWidth_ = 60;
1015 static const int ButtonBarHeight_ = 48;
1016 static const float KeyboardTime_ = 0.3f;
1019 static NSArray *Finishes_;
1021 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1022 #define NotifyConfig_ "/etc/notify.conf"
1024 static bool Queuing_;
1026 static CYColor Blue_;
1027 static CYColor Blueish_;
1028 static CYColor Black_;
1029 static CYColor Off_;
1030 static CYColor White_;
1031 static CYColor Gray_;
1032 static CYColor Green_;
1033 static CYColor Purple_;
1034 static CYColor Purplish_;
1036 static UIColor *InstallingColor_;
1037 static UIColor *RemovingColor_;
1039 static NSString *App_;
1040 static NSString *Home_;
1042 static BOOL Advanced_;
1043 static BOOL Ignored_;
1045 static UIFont *Font12_;
1046 static UIFont *Font12Bold_;
1047 static UIFont *Font14_;
1048 static UIFont *Font18Bold_;
1049 static UIFont *Font22Bold_;
1051 static const char *Machine_ = NULL;
1052 static NSString *System_ = nil;
1053 static NSString *SerialNumber_ = nil;
1054 static NSString *ChipID_ = nil;
1055 static NSString *Token_ = nil;
1056 static NSString *UniqueID_ = nil;
1057 static NSString *PLMN_ = nil;
1058 static NSString *Build_ = nil;
1059 static NSString *Product_ = nil;
1060 static NSString *Safari_ = nil;
1062 static CFLocaleRef Locale_;
1063 static NSArray *Languages_;
1064 static CGColorSpaceRef space_;
1066 static NSDictionary *SectionMap_;
1067 static NSMutableDictionary *Metadata_;
1068 static _transient NSMutableDictionary *Settings_;
1069 static _transient NSString *Role_;
1070 static _transient NSMutableDictionary *Packages_;
1071 static _transient NSMutableDictionary *Sections_;
1072 static _transient NSMutableDictionary *Sources_;
1073 static bool Changed_;
1076 static bool IsWildcat_;
1079 /* Display Helpers {{{ */
1080 inline float Interpolate(float begin, float end, float fraction) {
1081 return (end - begin) * fraction + begin;
1084 /* XXX: localize this! */
1085 NSString *SizeString(double size) {
1086 bool negative = size < 0;
1091 while (size > 1024) {
1096 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1098 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1101 static _finline const char *StripVersion_(const char *version) {
1102 const char *colon(strchr(version, ':'));
1103 return colon == NULL ? version : colon + 1;
1106 NSString *LocalizeSection(NSString *section) {
1107 static Pcre title_r("^(.*?) \\((.*)\\)$");
1108 if (title_r(section)) {
1109 NSString *parent(title_r[1]);
1110 NSString *child(title_r[2]);
1112 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1113 LocalizeSection(parent),
1114 LocalizeSection(child)
1118 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1121 NSString *Simplify(NSString *title) {
1122 const char *data = [title UTF8String];
1123 size_t size = [title length];
1125 static Pcre square_r("^\\[(.*)\\]$");
1126 if (square_r(data, size))
1127 return Simplify(square_r[1]);
1129 static Pcre paren_r("^\\((.*)\\)$");
1130 if (paren_r(data, size))
1131 return Simplify(paren_r[1]);
1133 static Pcre title_r("^(.*?) \\((.*)\\)$");
1134 if (title_r(data, size))
1135 return Simplify(title_r[1]);
1141 NSString *GetLastUpdate() {
1142 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1145 return UCLocalize("NEVER_OR_UNKNOWN");
1147 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1148 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1150 CFRelease(formatter);
1152 return [(NSString *) formatted autorelease];
1155 bool isSectionVisible(NSString *section) {
1156 NSDictionary *metadata([Sections_ objectForKey:section]);
1157 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1158 return hidden == nil || ![hidden boolValue];
1163 /* Delegate Prototypes {{{ */
1167 @interface NSObject (ProgressDelegate)
1170 @protocol ProgressDelegate
1171 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1172 - (void) setProgressTitle:(NSString *)title;
1173 - (void) setProgressPercent:(float)percent;
1174 - (void) startProgress;
1175 - (void) addProgressOutput:(NSString *)output;
1176 - (bool) isCancelling:(size_t)received;
1179 @protocol ConfigurationDelegate
1180 - (void) repairWithSelector:(SEL)selector;
1181 - (void) setConfigurationData:(NSString *)data;
1184 @class PackageController;
1186 @protocol CydiaDelegate
1187 - (void) retainNetworkActivityIndicator;
1188 - (void) releaseNetworkActivityIndicator;
1189 - (void) setPackageController:(PackageController *)view;
1190 - (void) clearPackage:(Package *)package;
1191 - (void) installPackage:(Package *)package;
1192 - (void) installPackages:(NSArray *)packages;
1193 - (void) removePackage:(Package *)package;
1194 - (void) beginUpdate;
1196 - (void) distUpgrade;
1198 - (void) updateData;
1200 - (void) showSettings;
1201 - (UIProgressHUD *) addProgressHUD;
1202 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1203 - (CYViewController *) pageForPackage:(NSString *)name;
1204 - (PackageController *) packageController;
1205 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1208 static id<CydiaDelegate> CydiaApp;
1211 /* Status Delegation {{{ */
1213 public pkgAcquireStatus
1216 _transient NSObject<ProgressDelegate> *delegate_;
1224 void setDelegate(id delegate) {
1225 delegate_ = delegate;
1228 NSObject<ProgressDelegate> *getDelegate() const {
1232 virtual bool MediaChange(std::string media, std::string drive) {
1236 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1239 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1240 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1241 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1244 virtual void Done(pkgAcquire::ItemDesc &item) {
1247 virtual void Fail(pkgAcquire::ItemDesc &item) {
1249 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1250 item.Owner->Status == pkgAcquire::Item::StatDone
1254 std::string &error(item.Owner->ErrorText);
1258 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1259 NSArray *fields([description componentsSeparatedByString:@" "]);
1260 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1262 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1263 withObject:[NSArray arrayWithObjects:
1264 [NSString stringWithUTF8String:error.c_str()],
1271 virtual bool Pulse(pkgAcquire *Owner) {
1272 bool value = pkgAcquireStatus::Pulse(Owner);
1275 double(CurrentBytes + CurrentItems) /
1276 double(TotalBytes + TotalItems)
1279 [delegate_ setProgressPercent:percent];
1280 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1283 virtual void Start() {
1284 [delegate_ startProgress];
1287 virtual void Stop() {
1291 /* Progress Delegation {{{ */
1296 _transient id<ProgressDelegate> delegate_;
1300 virtual void Update() {
1301 /*if (abs(Percent - percent_) > 2)
1302 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1306 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1307 [delegate_ setProgressPercent:(Percent / 100)];*/
1317 void setDelegate(id delegate) {
1318 delegate_ = delegate;
1321 id getDelegate() const {
1325 virtual void Done() {
1327 //[delegate_ setProgressPercent:1];
1332 /* Database Interface {{{ */
1333 typedef std::map< unsigned long, _H<Source> > SourceMap;
1335 @interface Database : NSObject {
1341 pkgCacheFile cache_;
1342 pkgDepCache::Policy *policy_;
1343 pkgRecords *records_;
1344 pkgProblemResolver *resolver_;
1345 pkgAcquire *fetcher_;
1347 SPtr<pkgPackageManager> manager_;
1348 pkgSourceList *list_;
1351 CFMutableArrayRef packages_;
1353 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1362 + (Database *) sharedInstance;
1365 - (void) _readCydia:(NSNumber *)fd;
1366 - (void) _readStatus:(NSNumber *)fd;
1367 - (void) _readOutput:(NSNumber *)fd;
1371 - (Package *) packageWithName:(NSString *)name;
1373 - (pkgCacheFile &) cache;
1374 - (pkgDepCache::Policy *) policy;
1375 - (pkgRecords *) records;
1376 - (pkgProblemResolver *) resolver;
1377 - (pkgAcquire &) fetcher;
1378 - (pkgSourceList &) list;
1379 - (NSArray *) packages;
1380 - (NSArray *) sources;
1381 - (void) reloadData;
1389 - (void) updateWithStatus:(Status &)status;
1391 - (void) setDelegate:(id)delegate;
1392 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1395 /* Delegate Helpers {{{ */
1396 @implementation NSObject (ProgressDelegate)
1398 - (void) _setProgressErrorPackage:(NSArray *)args {
1399 [self performSelector:@selector(setProgressError:forPackage:)
1400 withObject:[args objectAtIndex:0]
1401 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1405 - (void) _setProgressErrorTitle:(NSArray *)args {
1406 [self performSelector:@selector(setProgressError:withTitle:)
1407 withObject:[args objectAtIndex:0]
1408 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1412 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1413 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1414 withObject:[NSArray arrayWithObjects:error, title, nil]
1419 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1420 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1422 [self performSelector:@selector(setProgressError:withTitle:)
1424 withObject:(package == nil ? id : [package name])
1431 // Cytore Definitions {{{
1432 struct PackageValue :
1435 Cytore::Offset<PackageValue> next_;
1437 uint32_t index_ : 23;
1438 uint32_t subscribed_ : 1;
1455 Cytore::Offset<PackageValue> packages_[1 << 16];
1458 static Cytore::File<MetaValue> MetaFile_;
1460 // Cytore Helper Functions {{{
1461 static PackageValue *PackageFind(const char *name, size_t length) {
1462 SplitHash nhash = { hashlittle(name, length) };
1464 PackageValue *metadata;
1466 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1467 offset: if (offset->IsNull()) {
1468 *offset = MetaFile_.New<PackageValue>(length + 1);
1469 metadata = &MetaFile_.Get(*offset);
1471 memcpy(metadata->name_, name, length + 1);
1472 metadata->nhash_ = nhash.u16[1];
1474 metadata = &MetaFile_.Get(*offset);
1476 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1477 offset = &metadata->next_;
1485 static void PackageImport(const void *key, const void *value, void *context) {
1487 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1488 NSLog(@"failed to import package %@", key);
1492 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1493 NSDictionary *package((NSDictionary *) value);
1495 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1496 if ([subscribed boolValue])
1497 metadata->subscribed_ = true;
1499 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1500 time_t time([date timeIntervalSince1970]);
1501 if (metadata->first_ > time || metadata->first_ == 0)
1502 metadata->first_ = time;
1505 bool versioned(false);
1507 if (NSDate *date = [package objectForKey:@"LastSeen"]) {
1508 time_t time([date timeIntervalSince1970]);
1509 if (metadata->last_ < time || metadata->last_ == 0) {
1510 metadata->last_ = time;
1513 } else if (metadata->last_ == 0) {
1514 metadata->last_ = metadata->first_;
1515 if (metadata->version_[0] == '\0')
1520 if (NSString *version = [package objectForKey:@"LastVersion"])
1521 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1522 size_t length(strlen(buffer));
1523 uint16_t vhash(hashlittle(buffer, length));
1525 size_t capped(std::min<size_t>(8, length));
1526 char *latest(buffer + length - capped);
1528 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1529 metadata->vhash_ = vhash;
1534 /* Source Class {{{ */
1535 @interface Source : NSObject {
1536 CYString depiction_;
1537 CYString description_;
1543 CYString distribution_;
1548 NSString *authority_;
1550 CYString defaultIcon_;
1552 NSDictionary *record_;
1556 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1558 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1560 - (NSString *) depictionForPackage:(NSString *)package;
1561 - (NSString *) supportForPackage:(NSString *)package;
1563 - (NSDictionary *) record;
1567 - (NSString *) distribution;
1568 - (NSString *) type;
1570 - (NSString *) host;
1572 - (NSString *) name;
1573 - (NSString *) description;
1574 - (NSString *) label;
1575 - (NSString *) origin;
1576 - (NSString *) version;
1578 - (NSString *) defaultIcon;
1582 @implementation Source
1586 distribution_.clear();
1589 description_.clear();
1595 defaultIcon_.clear();
1597 if (record_ != nil) {
1607 if (authority_ != nil) {
1608 [authority_ release];
1614 // XXX: this is a very inefficient way to call these deconstructors
1619 + (NSArray *) _attributeKeys {
1620 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1623 - (NSArray *) attributeKeys {
1624 return [[self class] _attributeKeys];
1627 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1628 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1631 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1634 trusted_ = index->IsTrusted();
1636 uri_.set(pool, index->GetURI());
1637 distribution_.set(pool, index->GetDist());
1638 type_.set(pool, index->GetType());
1640 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1641 if (dindex != NULL) {
1643 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1646 pkgTagFile tags(&fd);
1648 pkgTagSection section;
1655 {"default-icon", &defaultIcon_},
1656 {"depiction", &depiction_},
1657 {"description", &description_},
1659 {"origin", &origin_},
1660 {"support", &support_},
1661 {"version", &version_},
1664 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1665 const char *start, *end;
1667 if (section.Find(names[i].name_, start, end)) {
1668 CYString &value(*names[i].value_);
1669 value.set(pool, start, end - start);
1675 record_ = [Sources_ objectForKey:[self key]];
1677 record_ = [record_ retain];
1679 NSURL *url([NSURL URLWithString:uri_]);
1683 host_ = [[host_ lowercaseString] retain];
1688 authority_ = [url path];
1690 if (authority_ != nil)
1691 authority_ = [authority_ retain];
1694 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1695 if ((self = [super init]) != nil) {
1696 [self setMetaIndex:index inPool:pool];
1700 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1701 NSDictionary *lhr = [self record];
1702 NSDictionary *rhr = [source record];
1705 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1707 NSString *lhs = [self name];
1708 NSString *rhs = [source name];
1710 if ([lhs length] != 0 && [rhs length] != 0) {
1711 unichar lhc = [lhs characterAtIndex:0];
1712 unichar rhc = [rhs characterAtIndex:0];
1714 if (isalpha(lhc) && !isalpha(rhc))
1715 return NSOrderedAscending;
1716 else if (!isalpha(lhc) && isalpha(rhc))
1717 return NSOrderedDescending;
1720 return [lhs compare:rhs options:LaxCompareOptions_];
1723 - (NSString *) depictionForPackage:(NSString *)package {
1724 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1727 - (NSString *) supportForPackage:(NSString *)package {
1728 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1731 - (NSDictionary *) record {
1739 - (NSString *) uri {
1743 - (NSString *) distribution {
1744 return distribution_;
1747 - (NSString *) type {
1751 - (NSString *) key {
1752 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1755 - (NSString *) host {
1759 - (NSString *) name {
1760 return origin_.empty() ? authority_ : origin_;
1763 - (NSString *) description {
1764 return description_;
1767 - (NSString *) label {
1768 return label_.empty() ? authority_ : label_;
1771 - (NSString *) origin {
1775 - (NSString *) version {
1779 - (NSString *) defaultIcon {
1780 return defaultIcon_;
1785 /* Relationship Class {{{ */
1786 @interface Relationship : NSObject {
1791 - (NSString *) type;
1793 - (NSString *) name;
1797 @implementation Relationship
1805 - (NSString *) type {
1813 - (NSString *) name {
1820 /* Package Class {{{ */
1821 struct ParsedPackage {
1826 CYString depiction_;
1836 @interface Package : NSObject {
1838 uint32_t essential_ : 1;
1839 uint32_t obsolete_ : 1;
1840 uint32_t ignored_ : 1;
1844 _transient Database *database_;
1846 pkgCache::VerIterator version_;
1847 pkgCache::PkgIterator iterator_;
1848 pkgCache::VerFileIterator file_;
1854 CYString installed_;
1857 _transient NSString *section$_;
1861 PackageValue *metadata_;
1862 ParsedPackage *parsed_;
1864 NSMutableArray *tags_;
1868 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1869 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1871 - (pkgCache::PkgIterator) iterator;
1874 - (NSString *) section;
1875 - (NSString *) simpleSection;
1877 - (NSString *) longSection;
1878 - (NSString *) shortSection;
1882 - (Address *) maintainer;
1884 - (NSString *) longDescription;
1885 - (NSString *) shortDescription;
1888 - (PackageValue *) metadata;
1891 - (bool) subscribed;
1892 - (bool) setSubscribed:(bool)subscribed;
1896 - (NSString *) latest;
1897 - (NSString *) installed;
1898 - (BOOL) uninstalled;
1901 - (BOOL) upgradableAndEssential:(BOOL)essential;
1904 - (BOOL) unfiltered;
1908 - (BOOL) halfConfigured;
1909 - (BOOL) halfInstalled;
1911 - (NSString *) mode;
1914 - (NSString *) name;
1916 - (NSString *) homepage;
1917 - (NSString *) depiction;
1918 - (Address *) author;
1920 - (NSString *) support;
1922 - (NSArray *) files;
1923 - (NSArray *) warnings;
1924 - (NSArray *) applications;
1926 - (Source *) source;
1927 - (NSString *) role;
1929 - (BOOL) matches:(NSString *)text;
1931 - (bool) hasSupportingRole;
1932 - (BOOL) hasTag:(NSString *)tag;
1933 - (NSString *) primaryPurpose;
1934 - (NSArray *) purposes;
1935 - (bool) isCommercial;
1937 - (void) setIndex:(size_t)index;
1939 - (CYString &) cyname;
1941 - (uint32_t) compareBySection:(NSArray *)sections;
1946 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1947 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1948 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1949 - (bool) isVisibleInSection:(NSString *)section;
1950 - (bool) isVisibleInSource:(Source *)source;
1954 uint32_t PackageChangesRadix(Package *self, void *) {
1959 uint32_t timestamp : 30;
1960 uint32_t ignored : 1;
1961 uint32_t upgradable : 1;
1965 bool upgradable([self upgradableAndEssential:YES]);
1966 value.bits.upgradable = upgradable ? 1 : 0;
1969 value.bits.timestamp = 0;
1970 value.bits.ignored = [self ignored] ? 0 : 1;
1971 value.bits.upgradable = 1;
1973 value.bits.timestamp = [self seen] >> 2;
1974 value.bits.ignored = 0;
1975 value.bits.upgradable = 0;
1978 return _not(uint32_t) - value.key;
1981 uint32_t PackagePrefixRadix(Package *self, void *context) {
1982 size_t offset(reinterpret_cast<size_t>(context));
1983 CYString &name([self cyname]);
1985 size_t size(name.size());
1988 char *text(name.data());
1991 if (!isdigit(text[0]))
1995 while (size != digits && isdigit(text[digits]))
2003 if (offset == 0 && zeros != 0) {
2004 memset(data, '0', zeros);
2005 memcpy(data + zeros, text, 4 - zeros);
2007 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2008 if (size <= offset - zeros)
2011 text += offset - zeros;
2012 size -= offset - zeros;
2015 memcpy(data, text, 4);
2017 memcpy(data, text, size);
2018 memset(data + size, 0, 4 - size);
2021 for (size_t i(0); i != 4; ++i)
2022 if (isalpha(data[i]))
2030 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2032 /* XXX: ntohl may be more honest */
2033 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2036 CYString &(*PackageName)(Package *self, SEL sel);
2038 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2039 _profile(PackageNameCompare)
2040 CYString &lhi(PackageName(lhs, @selector(cyname)));
2041 CYString &rhi(PackageName(rhs, @selector(cyname)));
2042 CFStringRef lhn(lhi), rhn(rhi);
2045 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2046 else if (rhn == NULL)
2047 return NSOrderedDescending;
2049 _profile(PackageNameCompare$NumbersLast)
2050 if (!lhi.empty() && !rhi.empty()) {
2051 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2052 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2053 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2054 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2055 return lha ? NSOrderedAscending : NSOrderedDescending;
2059 CFIndex length = CFStringGetLength(lhn);
2061 _profile(PackageNameCompare$Compare)
2062 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2067 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2068 return PackageNameCompare(*lhs, *rhs, context);
2071 struct PackageNameOrdering :
2072 std::binary_function<Package *, Package *, bool>
2074 _finline bool operator ()(Package *lhs, Package *rhs) const {
2075 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2079 @implementation Package
2081 - (NSString *) description {
2082 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2086 if (parsed_ != NULL)
2100 + (NSString *) webScriptNameForSelector:(SEL)selector {
2101 if (selector == @selector(hasTag:))
2107 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2108 return [self webScriptNameForSelector:selector] == nil;
2111 + (NSArray *) _attributeKeys {
2112 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];
2115 - (NSArray *) attributeKeys {
2116 return [[self class] _attributeKeys];
2119 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2120 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2124 if (parsed_ != NULL)
2126 @synchronized (database_) {
2127 if ([database_ era] != era_ || file_.end())
2130 ParsedPackage *parsed(new ParsedPackage);
2133 _profile(Package$parse)
2134 pkgRecords::Parser *parser;
2136 _profile(Package$parse$Lookup)
2137 parser = &[database_ records]->Lookup(file_);
2142 _profile(Package$parse$Find)
2147 {"icon", &parsed->icon_},
2148 {"depiction", &parsed->depiction_},
2149 {"homepage", &parsed->homepage_},
2150 {"website", &website},
2151 {"bugs", &parsed->bugs_},
2152 {"support", &parsed->support_},
2153 {"sponsor", &parsed->sponsor_},
2154 {"author", &parsed->author_},
2157 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2158 const char *start, *end;
2160 if (parser->Find(names[i].name_, start, end)) {
2161 CYString &value(*names[i].value_);
2162 _profile(Package$parse$Value)
2163 value.set(pool_, start, end - start);
2169 _profile(Package$parse$Tagline)
2170 const char *start, *end;
2171 if (parser->ShortDesc(start, end)) {
2172 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2175 while (stop != start && stop[-1] == '\r')
2177 parsed->tagline_.set(pool_, start, stop - start);
2181 _profile(Package$parse$Retain)
2182 if (parsed->homepage_.empty())
2183 parsed->homepage_ = website;
2184 if (parsed->homepage_ == parsed->depiction_)
2185 parsed->homepage_.clear();
2190 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2191 if ((self = [super init]) != nil) {
2192 _profile(Package$initWithVersion)
2195 database_ = database;
2196 era_ = [database era];
2200 pkgCache::PkgIterator iterator(version.ParentPkg());
2201 iterator_ = iterator;
2203 _profile(Package$initWithVersion$Version)
2204 if (!version_.end())
2205 file_ = version_.FileList();
2207 pkgCache &cache([database_ cache]);
2208 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2212 _profile(Package$initWithVersion$Cache)
2213 name_.set(NULL, iterator.Display());
2215 latest_.set(NULL, StripVersion_(version_.VerStr()));
2217 pkgCache::VerIterator current(iterator.CurrentVer());
2219 installed_.set(NULL, StripVersion_(current.VerStr()));
2222 _profile(Package$initWithVersion$Tags)
2223 pkgCache::TagIterator tag(iterator.TagList());
2225 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2227 const char *name(tag.Name());
2228 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2230 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2231 role_ = (NSString *) CYStringCreate(name + 6);
2233 if (strncmp(name, "cydia::", 7) == 0) {
2234 if (strcmp(name + 7, "essential") == 0)
2236 else if (strcmp(name + 7, "obsolete") == 0)
2241 } while (!tag.end());
2245 _profile(Package$initWithVersion$Metadata)
2246 const char *mixed(iterator.Name());
2247 size_t size(strlen(mixed));
2248 char lower[size + 1];
2250 for (size_t i(0); i != size; ++i)
2251 lower[i] = mixed[i] | 0x20;
2254 PackageValue *metadata(PackageFind(lower, size));
2255 metadata_ = metadata;
2257 id_.set(NULL, metadata->name_, size);
2259 const char *latest(version_.VerStr());
2260 size_t length(strlen(latest));
2262 uint16_t vhash(hashlittle(latest, length));
2264 size_t capped(std::min<size_t>(8, length));
2265 latest = latest + length - capped;
2267 if (metadata->first_ == 0)
2268 metadata->first_ = now_;
2270 if (metadata->last_ == 0)
2271 metadata->last_ = metadata->first_;
2273 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2274 if (metadata->version_[0] != '\0')
2275 metadata->last_ = now_;
2276 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2277 metadata->vhash_ = vhash;
2281 _profile(Package$initWithVersion$Section)
2282 section_.set(NULL, iterator.Section());
2285 _profile(Package$initWithVersion$Flags)
2286 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2287 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2292 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2293 pkgCache::VerIterator version;
2295 _profile(Package$packageWithIterator$GetCandidateVer)
2296 version = [database policy]->GetCandidateVer(iterator);
2304 _profile(Package$packageWithIterator$Allocate)
2305 package = [Package allocWithZone:zone];
2308 _profile(Package$packageWithIterator$Initialize)
2310 initWithVersion:version
2317 _profile(Package$packageWithIterator$Autorelease)
2318 package = [package autorelease];
2324 - (pkgCache::PkgIterator) iterator {
2328 - (NSString *) section {
2329 if (section$_ == nil) {
2330 if (section_.empty())
2333 _profile(Package$section)
2334 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2335 NSString *name(section_);
2336 section$_ = [SectionMap_ objectForKey:name] ?: name;
2341 - (NSString *) simpleSection {
2342 if (NSString *section = [self section])
2343 return Simplify(section);
2348 - (NSString *) longSection {
2349 return LocalizeSection([self section]);
2352 - (NSString *) shortSection {
2353 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2356 - (NSString *) uri {
2359 pkgIndexFile *index;
2360 pkgCache::PkgFileIterator file(file_.File());
2361 if (![database_ list].FindIndex(file, index))
2363 return [NSString stringWithUTF8String:iterator_->Path];
2364 //return [NSString stringWithUTF8String:file.Site()];
2365 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2369 - (Address *) maintainer {
2370 @synchronized (database_) {
2371 if ([database_ era] != era_ || file_.end())
2374 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2375 const std::string &maintainer(parser->Maintainer());
2376 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2380 @synchronized (database_) {
2381 if ([database_ era] != era_ || version_.end())
2384 return version_->InstalledSize;
2387 - (NSString *) longDescription {
2388 @synchronized (database_) {
2389 if ([database_ era] != era_ || file_.end())
2392 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2393 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2395 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2396 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2397 if ([lines count] < 2)
2400 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2401 for (size_t i(1), e([lines count]); i != e; ++i) {
2402 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2403 [trimmed addObject:trim];
2406 return [trimmed componentsJoinedByString:@"\n"];
2409 - (NSString *) shortDescription {
2410 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2414 _profile(Package$index)
2415 CFStringRef name((CFStringRef) [self name]);
2416 if (CFStringGetLength(name) == 0)
2418 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2419 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2421 return toupper(character);
2425 - (PackageValue *) metadata {
2430 PackageValue *metadata([self metadata]);
2431 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2434 - (bool) subscribed {
2435 return [self metadata]->subscribed_;
2438 - (bool) setSubscribed:(bool)subscribed {
2439 PackageValue *metadata([self metadata]);
2440 if (metadata->subscribed_ == subscribed)
2442 metadata->subscribed_ = subscribed;
2450 - (NSString *) latest {
2454 - (NSString *) installed {
2458 - (BOOL) uninstalled {
2459 return installed_.empty();
2463 return !version_.end();
2466 - (BOOL) upgradableAndEssential:(BOOL)essential {
2467 _profile(Package$upgradableAndEssential)
2468 pkgCache::VerIterator current(iterator_.CurrentVer());
2470 return essential && essential_;
2472 return !version_.end() && version_ != current;
2476 - (BOOL) essential {
2481 return [database_ cache][iterator_].InstBroken();
2484 - (BOOL) unfiltered {
2485 _profile(Package$unfiltered$obsolete)
2490 _profile(Package$unfiltered$hasSupportingRole)
2491 if (![self hasSupportingRole])
2499 if (![self unfiltered])
2502 NSString *section([self section]);
2504 _profile(Package$visible$isSectionVisible)
2505 if (section != nil && !isSectionVisible(section))
2513 unsigned char current(iterator_->CurrentState);
2514 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2517 - (BOOL) halfConfigured {
2518 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2521 - (BOOL) halfInstalled {
2522 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2526 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2527 return state.Mode != pkgDepCache::ModeKeep;
2530 - (NSString *) mode {
2531 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2533 switch (state.Mode) {
2534 case pkgDepCache::ModeDelete:
2535 if ((state.iFlags & pkgDepCache::Purge) != 0)
2539 case pkgDepCache::ModeKeep:
2540 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2541 return @"REINSTALL";
2542 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2546 case pkgDepCache::ModeInstall:
2547 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2548 return @"REINSTALL";
2549 else*/ switch (state.Status) {
2551 return @"DOWNGRADE";
2557 return @"NEW_INSTALL";
2568 - (NSString *) name {
2569 return name_.empty() ? id_ : name_;
2572 - (UIImage *) icon {
2573 NSString *section = [self simpleSection];
2576 if (parsed_ != NULL)
2577 if (NSString *href = parsed_->icon_)
2578 if ([href hasPrefix:@"file:///"])
2579 // XXX: correct escaping
2580 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2581 if (icon == nil) if (section != nil)
2582 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2583 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2584 if ([dicon hasPrefix:@"file:///"])
2585 // XXX: correct escaping
2586 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2588 icon = [UIImage applicationImageNamed:@"unknown.png"];
2592 - (NSString *) homepage {
2593 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2596 - (NSString *) depiction {
2597 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2600 - (Address *) sponsor {
2601 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2604 - (Address *) author {
2605 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2608 - (NSString *) support {
2609 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2612 - (NSArray *) files {
2613 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2614 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2617 fin.open([path UTF8String]);
2622 while (std::getline(fin, line))
2623 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2628 - (NSArray *) warnings {
2629 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2630 const char *name(iterator_.Name());
2632 size_t length(strlen(name));
2633 if (length < 2) invalid:
2634 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2635 else for (size_t i(0); i != length; ++i)
2637 /* XXX: technically this is not allowed */
2638 (name[i] < 'A' || name[i] > 'Z') &&
2639 (name[i] < 'a' || name[i] > 'z') &&
2640 (name[i] < '0' || name[i] > '9') &&
2641 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2644 if (strcmp(name, "cydia") != 0) {
2647 bool _private = false;
2650 bool repository = [[self section] isEqualToString:@"Repositories"];
2652 if (NSArray *files = [self files])
2653 for (NSString *file in files)
2654 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2656 else if (!user && [file isEqualToString:@"/User"])
2658 else if (!_private && [file isEqualToString:@"/private"])
2660 else if (!stash && [file isEqualToString:@"/var/stash"])
2663 /* XXX: this is not sensitive enough. only some folders are valid. */
2664 if (cydia && !repository)
2665 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2667 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2669 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2671 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2674 return [warnings count] == 0 ? nil : warnings;
2677 - (NSArray *) applications {
2678 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2680 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2682 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2683 if (NSArray *files = [self files])
2684 for (NSString *file in files)
2685 if (application_r(file)) {
2686 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2687 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2688 if ([id isEqualToString:me])
2691 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2693 display = application_r[1];
2695 NSString *bundle([file stringByDeletingLastPathComponent]);
2696 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2697 if (icon == nil || [icon length] == 0)
2699 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2701 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2702 [applications addObject:application];
2704 [application addObject:id];
2705 [application addObject:display];
2706 [application addObject:url];
2709 return [applications count] == 0 ? nil : applications;
2712 - (Source *) source {
2713 if (source_ == nil) {
2714 @synchronized (database_) {
2715 if ([database_ era] != era_ || file_.end())
2716 source_ = (Source *) [NSNull null];
2718 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2722 return source_ == (Source *) [NSNull null] ? nil : source_;
2725 - (NSString *) role {
2729 - (BOOL) matches:(NSString *)text {
2735 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2736 if (range.location != NSNotFound)
2739 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2740 if (range.location != NSNotFound)
2743 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2744 if (range.location != NSNotFound)
2750 - (bool) hasSupportingRole {
2753 if ([role_ isEqualToString:@"enduser"])
2755 if ([Role_ isEqualToString:@"User"])
2757 if ([role_ isEqualToString:@"hacker"])
2759 if ([Role_ isEqualToString:@"Hacker"])
2761 if ([role_ isEqualToString:@"developer"])
2763 if ([Role_ isEqualToString:@"Developer"])
2768 - (BOOL) hasTag:(NSString *)tag {
2769 return tags_ == nil ? NO : [tags_ containsObject:tag];
2772 - (NSString *) primaryPurpose {
2773 for (NSString *tag in tags_)
2774 if ([tag hasPrefix:@"purpose::"])
2775 return [tag substringFromIndex:9];
2779 - (NSArray *) purposes {
2780 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2781 for (NSString *tag in tags_)
2782 if ([tag hasPrefix:@"purpose::"])
2783 [purposes addObject:[tag substringFromIndex:9]];
2784 return [purposes count] == 0 ? nil : purposes;
2787 - (bool) isCommercial {
2788 return [self hasTag:@"cydia::commercial"];
2791 - (void) setIndex:(size_t)index {
2792 if (metadata_->index_ != index)
2793 metadata_->index_ = index;
2796 - (CYString &) cyname {
2797 return name_.empty() ? id_ : name_;
2800 - (uint32_t) compareBySection:(NSArray *)sections {
2801 NSString *section([self section]);
2802 for (size_t i(0), e([sections count]); i != e; ++i) {
2803 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2807 return _not(uint32_t);
2811 @synchronized (database_) {
2812 pkgProblemResolver *resolver = [database_ resolver];
2813 resolver->Clear(iterator_);
2815 pkgCacheFile &cache([database_ cache]);
2816 cache->SetReInstall(iterator_, false);
2817 cache->MarkKeep(iterator_, false);
2821 @synchronized (database_) {
2822 pkgProblemResolver *resolver = [database_ resolver];
2823 resolver->Clear(iterator_);
2824 resolver->Protect(iterator_);
2826 pkgCacheFile &cache([database_ cache]);
2827 cache->SetReInstall(iterator_, false);
2828 cache->MarkInstall(iterator_, false);
2830 pkgDepCache::StateCache &state((*cache)[iterator_]);
2831 if (!state.Install())
2832 cache->SetReInstall(iterator_, true);
2836 @synchronized (database_) {
2837 pkgProblemResolver *resolver = [database_ resolver];
2838 resolver->Clear(iterator_);
2839 resolver->Remove(iterator_);
2840 resolver->Protect(iterator_);
2842 pkgCacheFile &cache([database_ cache]);
2843 cache->SetReInstall(iterator_, false);
2844 cache->MarkDelete(iterator_, true);
2847 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2848 _profile(Package$isUnfilteredAndSearchedForBy)
2851 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2852 value &= [self unfiltered];
2855 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2856 value &= [self matches:search];
2863 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2864 if ([search length] == 0)
2867 _profile(Package$isUnfilteredAndSelectedForBy)
2870 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2871 value &= [self unfiltered];
2874 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2875 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2882 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2883 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2886 - (bool) isVisibleInSection:(NSString *)name {
2887 NSString *section([self section]);
2891 section == nil && [name length] == 0 ||
2892 [name isEqualToString:section]
2893 ) && [self visible];
2896 - (bool) isVisibleInSource:(Source *)source {
2897 return [self source] == source && [self visible];
2902 /* Section Class {{{ */
2903 @interface Section : NSObject {
2908 NSString *localized_;
2911 - (NSComparisonResult) compareByLocalized:(Section *)section;
2912 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2913 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2914 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2915 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2916 - (NSString *) name;
2923 - (void) addToCount;
2925 - (void) setCount:(size_t)count;
2926 - (NSString *) localized;
2930 @implementation Section
2934 if (localized_ != nil)
2935 [localized_ release];
2939 - (NSComparisonResult) compareByLocalized:(Section *)section {
2940 NSString *lhs(localized_);
2941 NSString *rhs([section localized]);
2943 /*if ([lhs length] != 0 && [rhs length] != 0) {
2944 unichar lhc = [lhs characterAtIndex:0];
2945 unichar rhc = [rhs characterAtIndex:0];
2947 if (isalpha(lhc) && !isalpha(rhc))
2948 return NSOrderedAscending;
2949 else if (!isalpha(lhc) && isalpha(rhc))
2950 return NSOrderedDescending;
2953 return [lhs compare:rhs options:LaxCompareOptions_];
2956 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2957 if ((self = [self initWithName:name localize:NO]) != nil) {
2958 if (localized != nil)
2959 localized_ = [localized retain];
2963 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2964 return [self initWithName:name row:0 localize:localize];
2967 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2968 if ((self = [super init]) != nil) {
2969 name_ = [name retain];
2973 localized_ = [LocalizeSection(name_) retain];
2977 /* XXX: localize the index thingees */
2978 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2979 if ((self = [super init]) != nil) {
2980 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2986 - (NSString *) name {
3006 - (void) addToCount {
3010 - (void) setCount:(size_t)count {
3014 - (NSString *) localized {
3021 static NSString *Colon_;
3022 static NSString *Elision_;
3023 static NSString *Error_;
3024 static NSString *Warning_;
3026 /* Database Implementation {{{ */
3027 @implementation Database
3029 + (Database *) sharedInstance {
3030 static Database *instance;
3031 if (instance == nil)
3032 instance = [[Database alloc] init];
3040 - (void) releasePackages {
3041 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3042 CFArrayRemoveAllValues(packages_);
3046 // XXX: actually implement this thing
3048 [self releasePackages];
3049 apr_pool_destroy(pool_);
3050 NSRecycleZone(zone_);
3054 - (void) _readCydia:(NSNumber *)fd { _pooled
3055 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3056 std::istream is(&ib);
3059 static Pcre finish_r("^finish:([^:]*)$");
3061 while (std::getline(is, line)) {
3062 const char *data(line.c_str());
3063 size_t size = line.size();
3064 lprintf("C:%s\n", data);
3066 if (finish_r(data, size)) {
3067 NSString *finish = finish_r[1];
3068 int index = [Finishes_ indexOfObject:finish];
3069 if (index != INT_MAX && index > Finish_)
3077 - (void) _readStatus:(NSNumber *)fd { _pooled
3078 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3079 std::istream is(&ib);
3082 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3083 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3085 while (std::getline(is, line)) {
3086 const char *data(line.c_str());
3087 size_t size(line.size());
3088 lprintf("S:%s\n", data);
3090 if (conffile_r(data, size)) {
3091 [delegate_ setConfigurationData:conffile_r[1]];
3092 } else if (strncmp(data, "status: ", 8) == 0) {
3093 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3094 [delegate_ setProgressTitle:string];
3095 } else if (pmstatus_r(data, size)) {
3096 std::string type([pmstatus_r[1] UTF8String]);
3097 NSString *id = pmstatus_r[2];
3099 float percent([pmstatus_r[3] floatValue]);
3100 [delegate_ setProgressPercent:(percent / 100)];
3102 NSString *string = pmstatus_r[4];
3104 if (type == "pmerror")
3105 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3106 withObject:[NSArray arrayWithObjects:string, id, nil]
3109 else if (type == "pmstatus") {
3110 [delegate_ setProgressTitle:string];
3111 } else if (type == "pmconffile")
3112 [delegate_ setConfigurationData:string];
3114 lprintf("E:unknown pmstatus\n");
3116 lprintf("E:unknown status\n");
3122 - (void) _readOutput:(NSNumber *)fd { _pooled
3123 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3124 std::istream is(&ib);
3127 while (std::getline(is, line)) {
3128 lprintf("O:%s\n", line.c_str());
3129 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3139 - (Package *) packageWithName:(NSString *)name {
3140 @synchronized (self) {
3141 if (static_cast<pkgDepCache *>(cache_) == NULL)
3143 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3144 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3148 if ((self = [super init]) != nil) {
3155 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3156 apr_pool_create(&pool_, NULL);
3158 size_t capacity(MetaFile_->active_);
3164 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3168 _assert(pipe(fds) != -1);
3171 _config->Set("APT::Keep-Fds::", cydiafd_);
3172 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3175 detachNewThreadSelector:@selector(_readCydia:)
3177 withObject:[NSNumber numberWithInt:fds[0]]
3180 _assert(pipe(fds) != -1);
3184 detachNewThreadSelector:@selector(_readStatus:)
3186 withObject:[NSNumber numberWithInt:fds[0]]
3189 _assert(pipe(fds) != -1);
3190 _assert(dup2(fds[0], 0) != -1);
3191 _assert(close(fds[0]) != -1);
3193 input_ = fdopen(fds[1], "a");
3195 _assert(pipe(fds) != -1);
3196 _assert(dup2(fds[1], 1) != -1);
3197 _assert(close(fds[1]) != -1);
3200 detachNewThreadSelector:@selector(_readOutput:)
3202 withObject:[NSNumber numberWithInt:fds[0]]
3207 - (pkgCacheFile &) cache {
3211 - (pkgDepCache::Policy *) policy {
3215 - (pkgRecords *) records {
3219 - (pkgProblemResolver *) resolver {
3223 - (pkgAcquire &) fetcher {
3227 - (pkgSourceList &) list {
3231 - (NSArray *) packages {
3232 return (NSArray *) packages_;
3235 - (NSArray *) sources {
3236 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3237 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3238 [sources addObject:i->second];
3242 - (NSArray *) issues {
3243 if (cache_->BrokenCount() == 0)
3246 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3248 for (Package *package in [self packages]) {
3249 if (![package broken])
3251 pkgCache::PkgIterator pkg([package iterator]);
3253 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3254 [entry addObject:[package name]];
3255 [issues addObject:entry];
3257 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3261 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3262 pkgCache::DepIterator start;
3263 pkgCache::DepIterator end;
3264 dep.GlobOr(start, end); // ++dep
3266 if (!cache_->IsImportantDep(end))
3268 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3271 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3272 [entry addObject:failure];
3273 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3275 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3276 if (Package *package = [self packageWithName:name])
3277 name = [package name];
3278 [failure addObject:name];
3280 pkgCache::PkgIterator target(start.TargetPkg());
3281 if (target->ProvidesList != 0)
3282 [failure addObject:@"?"];
3284 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3286 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3287 else if (!cache_[target].CandidateVerIter(cache_).end())
3288 [failure addObject:@"-"];
3289 else if (target->ProvidesList == 0)
3290 [failure addObject:@"!"];
3292 [failure addObject:@"%"];
3296 if (start.TargetVer() != 0)
3297 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3308 - (bool) popErrorWithTitle:(NSString *)title {
3310 std::string message;
3312 while (!_error->empty()) {
3314 bool warning(!_error->PopMessage(error));
3318 size_t size(error.size());
3319 if (size == 0 || error[size - 1] != '\n')
3321 error.resize(size - 1);
3323 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3325 if (!message.empty())
3330 if (fatal && !message.empty())
3331 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3336 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3337 return [self popErrorWithTitle:title] || !success;
3340 - (void) reloadData { CYPoolStart() {
3341 @synchronized (self) {
3344 [self releasePackages];
3365 apr_pool_clear(pool_);
3367 NSRecycleZone(zone_);
3368 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3370 int chk(creat("/tmp/cydia.chk", 0644));
3374 NSString *title(UCLocalize("DATABASE"));
3377 if (!cache_.Open(progress_, true)) { pop:
3379 bool warning(!_error->PopMessage(error));
3380 lprintf("cache_.Open():[%s]\n", error.c_str());
3382 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3383 [delegate_ repairWithSelector:@selector(configure)];
3384 else if (error == "The package lists or status file could not be parsed or opened.")
3385 [delegate_ repairWithSelector:@selector(update)];
3386 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3387 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3388 // else if (error == "The list of sources could not be read.")
3390 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3399 unlink("/tmp/cydia.chk");
3401 now_ = [[NSDate date] timeIntervalSince1970];
3403 policy_ = new pkgDepCache::Policy();
3404 records_ = new pkgRecords(cache_);
3405 resolver_ = new pkgProblemResolver(cache_);
3406 fetcher_ = new pkgAcquire(&status_);
3409 list_ = new pkgSourceList();
3410 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3413 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3414 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3418 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3421 if (cache_->BrokenCount() != 0) {
3422 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3425 if (cache_->BrokenCount() != 0) {
3426 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3430 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3434 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3435 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3436 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3437 // XXX: this could be more intelligent
3438 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3439 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3441 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3446 /*std::vector<Package *> packages;
3447 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3448 [packages_ release];
3453 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3454 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3455 //packages.push_back(package);
3456 CFArrayAppendValue(packages_, [package retain]);
3460 /*if (packages.empty())
3461 packages_ = [[NSArray alloc] init];
3463 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3466 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3467 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3468 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3476 /*if (!packages.empty())
3477 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3478 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3480 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3482 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3484 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3488 size_t count(CFArrayGetCount(packages_));
3489 MetaFile_->active_ = count;
3491 for (size_t index(0); index != count; ++index)
3492 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3496 } } CYPoolEnd() _trace(); }
3499 @synchronized (self) {
3501 resolver_ = new pkgProblemResolver(cache_);
3503 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3504 if (!cache_[iterator].Keep()) {
3505 cache_->MarkKeep(iterator, false);
3506 cache_->SetReInstall(iterator, false);
3511 - (void) configure {
3512 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3513 system([dpkg UTF8String]);
3517 // XXX: I don't remember this condition
3522 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3524 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3526 if ([self popErrorWithTitle:title])
3530 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3533 public pkgArchiveCleaner
3536 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3541 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3548 fetcher_->Shutdown();
3550 pkgRecords records(cache_);
3552 lock_ = new FileFd();
3553 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3555 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3557 if ([self popErrorWithTitle:title])
3561 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3564 manager_ = (_system->CreatePM(cache_));
3565 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3572 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3574 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3576 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3578 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3579 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3582 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3587 [CydiaApp retainNetworkActivityIndicator];
3589 bool failed = false;
3590 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3591 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3593 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3596 std::string uri = (*item)->DescURI();
3597 std::string error = (*item)->ErrorText;
3599 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3602 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3603 withObject:[NSArray arrayWithObjects:
3604 [NSString stringWithUTF8String:error.c_str()],
3610 [CydiaApp releaseNetworkActivityIndicator];
3618 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3620 if (_error->PendingError()) {
3625 if (result == pkgPackageManager::Failed) {
3630 if (result != pkgPackageManager::Completed) {
3635 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3637 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3639 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3640 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3643 if (![before isEqualToArray:after])
3648 NSString *title(UCLocalize("UPGRADE"));
3649 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3655 [self updateWithStatus:status_];
3658 - (void) updateWithStatus:(Status &)status {
3659 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3660 NSString *title(UCLocalize("REFRESHING_DATA"));
3663 if (!list.ReadMainList())
3664 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3667 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3668 if ([self popErrorWithTitle:title])
3671 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3672 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3673 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3675 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3679 - (void) setDelegate:(id)delegate {
3680 delegate_ = delegate;
3681 status_.setDelegate(delegate);
3682 progress_.setDelegate(delegate);
3685 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3686 SourceMap::const_iterator i(sources_.find(file->ID));
3687 return i == sources_.end() ? nil : i->second;
3693 /* Confirmation Controller {{{ */
3694 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3695 if (!iterator.end())
3696 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3697 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3699 pkgCache::PkgIterator package(dep.TargetPkg());
3702 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3710 /* Web Scripting {{{ */
3711 @interface CydiaObject : NSObject {
3713 _transient id delegate_;
3716 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3719 @implementation CydiaObject
3722 [indirect_ release];
3726 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3727 if ((self = [super init]) != nil) {
3728 indirect_ = [indirect retain];
3732 - (void) setDelegate:(id)delegate {
3733 delegate_ = delegate;
3736 + (NSArray *) _attributeKeys {
3737 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3740 - (NSArray *) attributeKeys {
3741 return [[self class] _attributeKeys];
3744 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3745 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3748 - (NSString *) device {
3749 return [[UIDevice currentDevice] uniqueIdentifier];
3752 #if 0 // XXX: implement!
3753 - (NSString *) mac {
3754 if (![indirect_ promptForSensitive:@"Mac Address"])
3758 - (NSString *) serial {
3759 if (![indirect_ promptForSensitive:@"Serial #"])
3763 - (NSString *) firewire {
3764 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3768 - (NSString *) imei {
3769 if (![indirect_ promptForSensitive:@"IMEI"])
3774 + (NSString *) webScriptNameForSelector:(SEL)selector {
3775 if (selector == @selector(close))
3777 else if (selector == @selector(getInstalledPackages))
3778 return @"getInstalledPackages";
3779 else if (selector == @selector(getPackageById:))
3780 return @"getPackageById";
3781 else if (selector == @selector(installPackages:))
3782 return @"installPackages";
3783 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3784 return @"setButtonImage";
3785 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3786 return @"setButtonTitle";
3787 else if (selector == @selector(setPopupHook:))
3788 return @"setPopupHook";
3789 else if (selector == @selector(setSpecial:))
3790 return @"setSpecial";
3791 else if (selector == @selector(setToken:))
3793 else if (selector == @selector(setViewportWidth:))
3794 return @"setViewportWidth";
3795 else if (selector == @selector(supports:))
3797 else if (selector == @selector(stringWithFormat:arguments:))
3799 else if (selector == @selector(localizedStringForKey:value:table:))
3801 else if (selector == @selector(du:))
3803 else if (selector == @selector(statfs:))
3809 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3810 return [self webScriptNameForSelector:selector] == nil;
3813 - (BOOL) supports:(NSString *)feature {
3814 return [feature isEqualToString:@"window.open"];
3817 - (NSArray *) getInstalledPackages {
3818 NSArray *packages([[Database sharedInstance] packages]);
3819 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3820 for (Package *package in packages)
3821 if ([package installed] != nil)
3822 [installed addObject:package];
3826 - (Package *) getPackageById:(NSString *)id {
3827 Package *package([[Database sharedInstance] packageWithName:id]);
3832 - (NSArray *) statfs:(NSString *)path {
3835 if (path == nil || statfs([path UTF8String], &stat) == -1)
3838 return [NSArray arrayWithObjects:
3839 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3840 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3841 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3845 - (NSNumber *) du:(NSString *)path {
3846 NSNumber *value(nil);
3849 _assert(pipe(fds) != -1);
3851 pid_t pid(ExecFork());
3853 _assert(dup2(fds[1], 1) != -1);
3854 _assert(close(fds[0]) != -1);
3855 _assert(close(fds[1]) != -1);
3856 /* XXX: this should probably not use du */
3857 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3862 _assert(close(fds[1]) != -1);
3864 if (FILE *du = fdopen(fds[0], "r")) {
3866 while (fgets(line, sizeof(line), du) != NULL) {
3867 size_t length(strlen(line));
3868 while (length != 0 && line[length - 1] == '\n')
3869 line[--length] = '\0';
3870 if (char *tab = strchr(line, '\t')) {
3872 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3877 } else _assert(close(fds[0]));
3881 if (waitpid(pid, &status, 0) == -1)
3884 else _assert(false);
3893 - (void) installPackages:(NSArray *)packages {
3894 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3897 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3898 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3901 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3902 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3905 - (void) setSpecial:(id)function {
3906 [indirect_ setSpecial:function];
3909 - (void) setToken:(NSString *)token {
3912 Token_ = [token retain];
3914 [Metadata_ setObject:Token_ forKey:@"Token"];
3918 - (void) setPopupHook:(id)function {
3919 [indirect_ setPopupHook:function];
3922 - (void) setViewportWidth:(float)width {
3923 [indirect_ setViewportWidth:width];
3926 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3927 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3928 unsigned count([arguments count]);
3930 for (unsigned i(0); i != count; ++i)
3931 values[i] = [arguments objectAtIndex:i];
3932 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3935 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3936 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3938 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3940 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3946 /* Cydia Browser Controller {{{ */
3947 @interface CYBrowserController : BrowserController {
3948 CydiaObject *cydia_;
3953 @implementation CYBrowserController
3960 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3963 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3964 [super webView:view didClearWindowObject:window forFrame:frame];
3966 WebDataSource *source([frame dataSource]);
3967 NSURLResponse *response([source response]);
3968 NSURL *url([response URL]);
3969 NSString *scheme([url scheme]);
3971 NSHTTPURLResponse *http;
3972 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3973 http = (NSHTTPURLResponse *) response;
3977 NSDictionary *headers([http allHeaderFields]);
3978 NSString *host([url host]);
3979 [self setHeaders:headers forHost:host];
3982 [host isEqualToString:@"cydia.saurik.com"] ||
3983 [host hasSuffix:@".cydia.saurik.com"] ||
3984 [scheme isEqualToString:@"file"]
3986 [window setValue:cydia_ forKey:@"cydia"];
3989 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3990 if (System_ != NULL)
3991 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3992 if (Machine_ != NULL)
3993 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3995 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3997 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4000 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4001 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4002 [self _setMoreHeaders:copy];
4006 - (void) setDelegate:(id)delegate {
4007 [super setDelegate:delegate];
4008 [cydia_ setDelegate:delegate];
4012 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4013 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4015 WebView *webview([[webview_ _documentView] webView]);
4017 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4019 NSString *application = package == nil ? @"Cydia" : [NSString
4020 stringWithFormat:@"Cydia/%@",
4025 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4027 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4028 if (Product_ != nil)
4029 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4031 [webview setApplicationNameForUserAgent:application];
4038 /* Confirmation {{{ */
4039 @protocol ConfirmationControllerDelegate
4040 - (void) cancelAndClear:(bool)clear;
4041 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4045 @interface ConfirmationController : CYBrowserController {
4046 _transient Database *database_;
4047 UIAlertView *essential_;
4054 - (id) initWithDatabase:(Database *)database;
4058 @implementation ConfirmationController
4065 if (essential_ != nil)
4066 [essential_ release];
4070 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4071 NSString *context([alert context]);
4073 if ([context isEqualToString:@"remove"]) {
4074 if (button == [alert cancelButtonIndex]) {
4075 [self dismissModalViewControllerAnimated:YES];
4076 } else if (button == [alert firstOtherButtonIndex]) {
4079 [delegate_ confirmWithNavigationController:[self navigationController]];
4082 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4083 } else if ([context isEqualToString:@"unable"]) {
4084 [self dismissModalViewControllerAnimated:YES];
4085 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4087 [super alertView:alert clickedButtonAtIndex:button];
4091 - (void) _doContinue {
4092 [self dismissModalViewControllerAnimated:YES];
4093 [delegate_ cancelAndClear:NO];
4096 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4097 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4101 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4102 [super webView:view didClearWindowObject:window forFrame:frame];
4103 [window setValue:changes_ forKey:@"changes"];
4104 [window setValue:issues_ forKey:@"issues"];
4105 [window setValue:sizes_ forKey:@"sizes"];
4106 [window setValue:self forKey:@"queue"];
4109 - (id) initWithDatabase:(Database *)database {
4110 if ((self = [super init]) != nil) {
4111 database_ = database;
4113 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4115 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4116 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4117 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4118 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4119 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4123 pkgDepCache::Policy *policy([database_ policy]);
4125 pkgCacheFile &cache([database_ cache]);
4126 NSArray *packages = [database_ packages];
4127 for (Package *package in packages) {
4128 pkgCache::PkgIterator iterator = [package iterator];
4129 pkgDepCache::StateCache &state(cache[iterator]);
4131 NSString *name([package name]);
4133 if (state.NewInstall())
4134 [installing addObject:name];
4135 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4136 [reinstalling addObject:name];
4137 else if (state.Upgrade())
4138 [upgrading addObject:name];
4139 else if (state.Downgrade())
4140 [downgrading addObject:name];
4141 else if (state.Delete()) {
4142 if ([package essential])
4144 [removing addObject:name];
4147 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4148 substrate_ |= DepSubstrate(iterator.CurrentVer());
4153 else if (Advanced_) {
4154 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4156 essential_ = [[UIAlertView alloc]
4157 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4158 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4160 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4161 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4164 [essential_ setContext:@"remove"];
4166 essential_ = [[UIAlertView alloc]
4167 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4168 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4170 cancelButtonTitle:UCLocalize("OKAY")
4171 otherButtonTitles:nil
4174 [essential_ setContext:@"unable"];
4177 changes_ = [[NSArray alloc] initWithObjects:
4185 issues_ = [database_ issues];
4187 issues_ = [issues_ retain];
4189 sizes_ = [[NSArray alloc] initWithObjects:
4190 SizeString([database_ fetcher].FetchNeeded()),
4191 SizeString([database_ fetcher].PartialPresent()),
4194 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4196 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4197 initWithTitle:UCLocalize("CANCEL")
4198 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4199 style:UIBarButtonItemStylePlain
4201 action:@selector(cancelButtonClicked)
4206 - (void) applyRightButton {
4207 #if !AlwaysReload && !IgnoreInstall
4208 if (issues_ == nil && ![self isLoading])
4209 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4210 initWithTitle:UCLocalize("CONFIRM")
4211 style:UIBarButtonItemStylePlain
4213 action:@selector(confirmButtonClicked)
4216 [super applyRightButton];
4218 [[self navigationItem] setRightBarButtonItem:nil];
4222 - (void) cancelButtonClicked {
4223 [self dismissModalViewControllerAnimated:YES];
4224 [delegate_ cancelAndClear:YES];
4228 - (void) confirmButtonClicked {
4232 if (essential_ != nil)
4237 [delegate_ confirmWithNavigationController:[self navigationController]];
4245 /* Progress Data {{{ */
4246 @interface ProgressData : NSObject {
4248 // XXX: should these really both be _transient?
4249 _transient id target_;
4250 _transient id object_;
4253 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4260 @implementation ProgressData
4262 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4263 if ((self = [super init]) != nil) {
4264 selector_ = selector;
4284 /* Progress Controller {{{ */
4285 @interface ProgressController : CYViewController <
4286 ConfigurationDelegate,
4289 _transient Database *database_;
4290 UIProgressBar *progress_;
4291 UITextView *output_;
4292 UITextLabel *status_;
4293 UIPushButton *close_;
4295 SHA1SumValue springlist_;
4296 SHA1SumValue notifyconf_;
4300 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4302 - (void) _retachThread;
4303 - (void) _detachNewThreadData:(ProgressData *)data;
4304 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4310 @protocol ProgressControllerDelegate
4311 - (void) progressControllerIsComplete:(ProgressController *)sender;
4314 @implementation ProgressController
4317 [database_ setDelegate:nil];
4318 [progress_ release];
4327 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4328 if ((self = [super init]) != nil) {
4329 database_ = database;
4330 [database_ setDelegate:self];
4331 delegate_ = delegate;
4333 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4335 progress_ = [[UIProgressBar alloc] init];
4336 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4337 [progress_ setStyle:0];
4339 status_ = [[UITextLabel alloc] init];
4340 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4341 [status_ setColor:[UIColor whiteColor]];
4342 [status_ setBackgroundColor:[UIColor clearColor]];
4343 [status_ setCentersHorizontally:YES];
4344 //[status_ setFont:font];
4346 output_ = [[UITextView alloc] init];
4348 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4349 //[output_ setTextFont:@"Courier New"];
4350 [output_ setFont:[[output_ font] fontWithSize:12]];
4351 [output_ setTextColor:[UIColor whiteColor]];
4352 [output_ setBackgroundColor:[UIColor clearColor]];
4353 [output_ setMarginTop:0];
4354 [output_ setAllowsRubberBanding:YES];
4355 [output_ setEditable:NO];
4356 [[self view] addSubview:output_];
4358 close_ = [[UIPushButton alloc] init];
4359 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4360 [close_ setAutosizesToFit:NO];
4361 [close_ setDrawsShadow:YES];
4362 [close_ setStretchBackground:YES];
4363 [close_ setEnabled:YES];
4364 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4365 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4366 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4367 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4371 - (void) positionViews {
4372 CGRect bounds = [[self view] bounds];
4373 CGSize prgsize = [UIProgressBar defaultSize];
4376 (bounds.size.width - prgsize.width) / 2,
4377 bounds.size.height - prgsize.height - 20
4380 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4382 [progress_ setFrame:prgrect];
4383 [status_ setFrame:CGRectMake(
4385 bounds.size.height - prgsize.height - 50,
4386 bounds.size.width - 20,
4389 [output_ setFrame:CGRectMake(
4392 bounds.size.width - 20,
4393 bounds.size.height - 62
4395 [close_ setFrame:CGRectMake(
4396 (bounds.size.width - closewidth) / 2,
4397 bounds.size.height - prgsize.height - 50,
4403 - (void) viewWillAppear:(BOOL)animated {
4404 [super viewDidAppear:animated];
4405 [[self navigationItem] setHidesBackButton:YES];
4406 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4408 [self positionViews];
4411 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4412 [self positionViews];
4415 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4416 NSString *context([alert context]);
4418 if ([context isEqualToString:@"conffile"]) {
4419 FILE *input = [database_ input];
4420 if (button == [alert cancelButtonIndex])
4421 fprintf(input, "N\n");
4422 else if (button == [alert firstOtherButtonIndex])
4423 fprintf(input, "Y\n");
4428 - (void) closeButtonPushed {
4431 UpdateExternalStatus(0);
4435 [self dismissModalViewControllerAnimated:YES];
4439 [delegate_ terminateWithSuccess];
4440 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4441 [delegate_ suspendWithAnimation:YES];
4443 [delegate_ suspend];*/
4447 system("launchctl stop com.apple.SpringBoard");
4451 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4460 - (void) _retachThread {
4461 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4463 [[self view] addSubview:close_];
4464 [progress_ removeFromSuperview];
4465 [status_ removeFromSuperview];
4467 [database_ popErrorWithTitle:title_];
4468 [delegate_ progressControllerIsComplete:self];
4472 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4475 MMap mmap(file, MMap::ReadOnly);
4477 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4478 if (!(notifyconf_ == sha1.Result()))
4485 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4488 MMap mmap(file, MMap::ReadOnly);
4490 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4491 if (!(springlist_ == sha1.Result()))
4497 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4498 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4499 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4500 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4501 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4504 system("su -c /usr/bin/uicache mobile");
4506 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4508 [delegate_ setStatusBarShowsProgress:NO];
4511 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4512 [[data target] performSelector:[data selector] withObject:[data object]];
4513 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4516 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4517 UpdateExternalStatus(1);
4524 title_ = [title retain];
4526 [[self navigationItem] setTitle:title_];
4528 [status_ setText:nil];
4529 [output_ setText:@""];
4530 [progress_ setProgress:0];
4532 [close_ removeFromSuperview];
4533 [[self view] addSubview:progress_];
4534 [[self view] addSubview:status_];
4536 [delegate_ setStatusBarShowsProgress:YES];
4541 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4544 MMap mmap(file, MMap::ReadOnly);
4546 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4547 notifyconf_ = sha1.Result();
4553 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4556 MMap mmap(file, MMap::ReadOnly);
4558 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4559 springlist_ = sha1.Result();
4564 detachNewThreadSelector:@selector(_detachNewThreadData:)
4566 withObject:[[[ProgressData alloc]
4567 initWithSelector:selector
4574 - (void) repairWithSelector:(SEL)selector {
4576 detachNewThreadSelector:selector
4579 title:UCLocalize("REPAIRING")
4583 - (void) setConfigurationData:(NSString *)data {
4585 performSelectorOnMainThread:@selector(_setConfigurationData:)
4591 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4592 CYActionSheet *sheet([[[CYActionSheet alloc]
4594 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4595 defaultButtonIndex:0
4598 [sheet setMessage:error];
4599 [sheet yieldToPopupAlertAnimated:YES];
4603 - (void) setProgressTitle:(NSString *)title {
4605 performSelectorOnMainThread:@selector(_setProgressTitle:)
4611 - (void) setProgressPercent:(float)percent {
4613 performSelectorOnMainThread:@selector(_setProgressPercent:)
4614 withObject:[NSNumber numberWithFloat:percent]
4619 - (void) startProgress {
4622 - (void) addProgressOutput:(NSString *)output {
4624 performSelectorOnMainThread:@selector(_addProgressOutput:)
4630 - (bool) isCancelling:(size_t)received {
4634 - (void) _setConfigurationData:(NSString *)data {
4635 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4637 if (!conffile_r(data)) {
4638 lprintf("E:invalid conffile\n");
4642 NSString *ofile = conffile_r[1];
4643 //NSString *nfile = conffile_r[2];
4645 UIAlertView *alert = [[[UIAlertView alloc]
4646 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4647 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4649 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4650 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4651 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4655 [alert setContext:@"conffile"];
4659 - (void) _setProgressTitle:(NSString *)title {
4660 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4661 for (size_t i(0), e([words count]); i != e; ++i) {
4662 NSString *word([words objectAtIndex:i]);
4663 if (Package *package = [database_ packageWithName:word])
4664 [words replaceObjectAtIndex:i withObject:[package name]];
4667 [status_ setText:[words componentsJoinedByString:@" "]];
4670 - (void) _setProgressPercent:(NSNumber *)percent {
4671 [progress_ setProgress:[percent floatValue]];
4674 - (void) _addProgressOutput:(NSString *)output {
4675 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4676 CGSize size = [output_ contentSize];
4677 CGPoint offset = [output_ contentOffset];
4678 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4679 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4680 [output_ scrollRectToVisible:rect animated:YES];
4684 - (BOOL) isRunning {
4691 /* Cell Content View {{{ */
4692 @protocol ContentDelegate
4693 - (void) drawContentRect:(CGRect)rect;
4696 @interface ContentView : UIView {
4697 _transient id<ContentDelegate> delegate_;
4702 @implementation ContentView
4704 - (id) initWithFrame:(CGRect)frame {
4705 if ((self = [super initWithFrame:frame]) != nil) {
4706 [self setNeedsDisplayOnBoundsChange:YES];
4710 - (void) setDelegate:(id<ContentDelegate>)delegate {
4711 delegate_ = delegate;
4714 - (void) drawRect:(CGRect)rect {
4715 [super drawRect:rect];
4716 [delegate_ drawContentRect:rect];
4721 /* Cydia TableView Cell {{{ */
4722 @interface CYTableViewCell : UITableViewCell {
4723 ContentView *content_;
4729 @implementation CYTableViewCell
4736 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4737 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4739 if (view == content_) {
4740 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4741 highlighted_ = highlighted;
4744 [super _updateHighlightColorsForView:view highlighted:highlighted];
4747 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4748 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4749 highlighted_ = selected;
4751 [super setSelected:selected animated:animated];
4752 [content_ setNeedsDisplay];
4757 /* Package Cell {{{ */
4758 @interface PackageCell : CYTableViewCell <
4763 NSString *description_;
4771 - (PackageCell *) init;
4772 - (void) setPackage:(Package *)package;
4774 + (int) heightForPackage:(Package *)package;
4775 - (void) drawContentRect:(CGRect)rect;
4779 @implementation PackageCell
4781 - (void) clearPackage {
4792 if (description_ != nil) {
4793 [description_ release];
4797 if (source_ != nil) {
4802 if (badge_ != nil) {
4807 if (placard_ != nil) {
4817 [self clearPackage];
4821 - (PackageCell *) init {
4822 CGRect frame(CGRectMake(0, 0, 320, 74));
4823 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4824 UIView *content([self contentView]);
4825 CGRect bounds([content bounds]);
4827 content_ = [[ContentView alloc] initWithFrame:bounds];
4828 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4829 [content addSubview:content_];
4831 [content_ setDelegate:self];
4832 [content_ setOpaque:YES];
4836 - (void) _setBackgroundColor {
4838 if (NSString *mode = [package_ mode]) {
4839 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4840 color = remove ? RemovingColor_ : InstallingColor_;
4842 color = [UIColor whiteColor];
4844 [content_ setBackgroundColor:color];
4845 [self setNeedsDisplay];
4848 - (void) setPackage:(Package *)package {
4849 [self clearPackage];
4852 Source *source = [package source];
4854 icon_ = [[package icon] retain];
4855 name_ = [[package name] retain];
4858 description_ = [package longDescription];
4859 if (description_ == nil)
4860 description_ = [package shortDescription];
4861 if (description_ != nil)
4862 description_ = [description_ retain];
4864 commercial_ = [package isCommercial];
4866 package_ = [package retain];
4868 NSString *label = nil;
4869 bool trusted = false;
4871 if (source != nil) {
4872 label = [source label];
4873 trusted = [source trusted];
4874 } else if ([[package id] isEqualToString:@"firmware"])
4875 label = UCLocalize("APPLE");
4877 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4879 NSString *from(label);
4881 NSString *section = [package simpleSection];
4882 if (section != nil && ![section isEqualToString:label]) {
4883 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4884 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4887 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4888 source_ = [from retain];
4890 if (NSString *purpose = [package primaryPurpose])
4891 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4892 badge_ = [badge_ retain];
4894 if ([package installed] != nil)
4895 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4896 placard_ = [placard_ retain];
4898 [self _setBackgroundColor];
4899 [content_ setNeedsDisplay];
4902 - (void) drawContentRect:(CGRect)rect {
4903 bool highlighted(highlighted_);
4904 float width([self bounds].size.width);
4907 CGContextRef context(UIGraphicsGetCurrentContext());
4908 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4909 CGContextFillRect(context, rect);
4914 rect.size = [icon_ size];
4916 rect.size.width /= 2;
4917 rect.size.height /= 2;
4919 rect.origin.x = 25 - rect.size.width / 2;
4920 rect.origin.y = 25 - rect.size.height / 2;
4922 [icon_ drawInRect:rect];
4925 if (badge_ != nil) {
4927 rect.size = [badge_ size];
4929 rect.size.width /= 2;
4930 rect.size.height /= 2;
4932 rect.origin.x = 36 - rect.size.width / 2;
4933 rect.origin.y = 36 - rect.size.height / 2;
4935 [badge_ drawInRect:rect];
4942 UISetColor(commercial_ ? Purple_ : Black_);
4943 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4944 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4947 UISetColor(commercial_ ? Purplish_ : Gray_);
4948 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4950 if (placard_ != nil)
4951 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4954 + (int) heightForPackage:(Package *)package {
4960 /* Section Cell {{{ */
4961 @interface SectionCell : CYTableViewCell <
4973 - (void) setSection:(Section *)section editing:(BOOL)editing;
4977 @implementation SectionCell
4979 - (void) clearSection {
4980 if (basic_ != nil) {
4985 if (section_ != nil) {
4995 if (count_ != nil) {
5002 [self clearSection];
5008 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5009 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5010 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5011 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5012 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5014 UIView *content([self contentView]);
5015 CGRect bounds([content bounds]);
5017 content_ = [[ContentView alloc] initWithFrame:bounds];
5018 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5019 [content addSubview:content_];
5020 [content_ setBackgroundColor:[UIColor whiteColor]];
5022 [content_ setDelegate:self];
5026 - (void) onSwitch:(id)sender {
5027 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5028 if (metadata == nil) {
5029 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5030 [Sections_ setObject:metadata forKey:basic_];
5033 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5037 - (void) setSection:(Section *)section editing:(BOOL)editing {
5038 if (editing != editing_) {
5040 [switch_ removeFromSuperview];
5042 [self addSubview:switch_];
5046 [self clearSection];
5048 if (section == nil) {
5049 name_ = [UCLocalize("ALL_PACKAGES") retain];
5052 basic_ = [section name];
5054 basic_ = [basic_ retain];
5056 section_ = [section localized];
5057 if (section_ != nil)
5058 section_ = [section_ retain];
5060 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5061 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5064 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5067 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5068 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5070 [content_ setNeedsDisplay];
5073 - (void) setFrame:(CGRect)frame {
5074 [super setFrame:frame];
5076 CGRect rect([switch_ frame]);
5077 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5080 - (void) drawContentRect:(CGRect)rect {
5081 bool highlighted(highlighted_);
5083 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5088 float width(rect.size.width);
5094 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5096 CGSize size = [count_ sizeWithFont:Font14_];
5100 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5106 /* File Table {{{ */
5107 @interface FileTable : CYViewController <
5108 UITableViewDataSource,
5111 _transient Database *database_;
5114 NSMutableArray *files_;
5118 - (id) initWithDatabase:(Database *)database;
5119 - (void) setPackage:(Package *)package;
5123 @implementation FileTable
5126 if (package_ != nil)
5135 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5136 return files_ == nil ? 0 : [files_ count];
5139 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5143 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5144 static NSString *reuseIdentifier = @"Cell";
5146 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5148 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5149 [cell setFont:[UIFont systemFontOfSize:16]];
5151 [cell setText:[files_ objectAtIndex:indexPath.row]];
5152 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5157 - (id) initWithDatabase:(Database *)database {
5158 if ((self = [super init]) != nil) {
5159 database_ = database;
5161 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5163 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5165 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5166 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5167 [list_ setRowHeight:24.0f];
5168 [[self view] addSubview:list_];
5170 [list_ setDataSource:self];
5171 [list_ setDelegate:self];
5175 - (void) setPackage:(Package *)package {
5176 if (package_ != nil) {
5177 [package_ autorelease];
5186 [files_ removeAllObjects];
5188 if (package != nil) {
5189 package_ = [package retain];
5190 name_ = [[package id] retain];
5192 if (NSArray *files = [package files])
5193 [files_ addObjectsFromArray:files];
5195 if ([files_ count] != 0) {
5196 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5197 [files_ removeObjectAtIndex:0];
5198 [files_ sortUsingSelector:@selector(compareByPath:)];
5200 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5201 [stack addObject:@"/"];
5203 for (int i(0), e([files_ count]); i != e; ++i) {
5204 NSString *file = [files_ objectAtIndex:i];
5205 while (![file hasPrefix:[stack lastObject]])
5206 [stack removeLastObject];
5207 NSString *directory = [stack lastObject];
5208 [stack addObject:[file stringByAppendingString:@"/"]];
5209 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5210 ([stack count] - 2) * 3, "",
5211 [file substringFromIndex:[directory length]]
5220 - (void) reloadData {
5221 [self setPackage:[database_ packageWithName:name_]];
5226 /* Package Controller {{{ */
5227 @interface PackageController : CYBrowserController <
5228 UIActionSheetDelegate
5230 _transient Database *database_;
5234 NSMutableArray *buttons_;
5235 UIBarButtonItem *button_;
5238 - (id) initWithDatabase:(Database *)database;
5239 - (void) setPackage:(Package *)package;
5243 @implementation PackageController
5246 if (package_ != nil)
5260 if ([self retainCount] == 1)
5261 [delegate_ setPackageController:self];
5265 /* XXX: this is not safe at all... localization of /fail/ */
5266 - (void) _clickButtonWithName:(NSString *)name {
5267 if ([name isEqualToString:UCLocalize("CLEAR")])
5268 [delegate_ clearPackage:package_];
5269 else if ([name isEqualToString:UCLocalize("INSTALL")])
5270 [delegate_ installPackage:package_];
5271 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5272 [delegate_ installPackage:package_];
5273 else if ([name isEqualToString:UCLocalize("REMOVE")])
5274 [delegate_ removePackage:package_];
5275 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5276 [delegate_ installPackage:package_];
5277 else _assert(false);
5280 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5281 NSString *context([sheet context]);
5283 if ([context isEqualToString:@"modify"]) {
5284 if (button != [sheet cancelButtonIndex]) {
5285 NSString *buttonName = [buttons_ objectAtIndex:button];
5286 [self _clickButtonWithName:buttonName];
5289 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5293 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5294 [super webView:view didClearWindowObject:window forFrame:frame];
5295 [window setValue:package_ forKey:@"package"];
5298 - (bool) _allowJavaScriptPanel {
5303 - (void) _customButtonClicked {
5304 int count([buttons_ count]);
5309 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5311 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5312 [buttons addObjectsFromArray:buttons_];
5314 UIActionSheet *sheet = [[[UIActionSheet alloc]
5317 cancelButtonTitle:nil
5318 destructiveButtonTitle:nil
5319 otherButtonTitles:nil
5322 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5324 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5325 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5327 [sheet setContext:@"modify"];
5329 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5333 // We don't want to allow non-commercial packages to do custom things to the install button,
5334 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5335 - (void) customButtonClicked {
5337 [super customButtonClicked];
5339 [self _customButtonClicked];
5342 - (void) reloadButtonClicked {
5343 // Don't reload a package view by clicking the button.
5346 - (void) applyLoadingTitle {
5347 // Don't show "Loading" as the title. Ever.
5350 - (UIBarButtonItem *) rightButton {
5355 - (id) initWithDatabase:(Database *)database {
5356 if ((self = [super init]) != nil) {
5357 database_ = database;
5358 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5359 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5363 - (void) setPackage:(Package *)package {
5364 if (package_ != nil) {
5365 [package_ autorelease];
5374 [buttons_ removeAllObjects];
5376 if (package != nil) {
5379 package_ = [package retain];
5380 name_ = [[package id] retain];
5381 commercial_ = [package isCommercial];
5383 if ([package_ mode] != nil)
5384 [buttons_ addObject:UCLocalize("CLEAR")];
5385 if ([package_ source] == nil);
5386 else if ([package_ upgradableAndEssential:NO])
5387 [buttons_ addObject:UCLocalize("UPGRADE")];
5388 else if ([package_ uninstalled])
5389 [buttons_ addObject:UCLocalize("INSTALL")];
5391 [buttons_ addObject:UCLocalize("REINSTALL")];
5392 if (![package_ uninstalled])
5393 [buttons_ addObject:UCLocalize("REMOVE")];
5400 switch ([buttons_ count]) {
5401 case 0: title = nil; break;
5402 case 1: title = [buttons_ objectAtIndex:0]; break;
5403 default: title = UCLocalize("MODIFY"); break;
5406 button_ = [[UIBarButtonItem alloc]
5408 style:UIBarButtonItemStylePlain
5410 action:@selector(customButtonClicked)
5416 - (bool) isLoading {
5417 return commercial_ ? [super isLoading] : false;
5420 - (void) reloadData {
5421 [self setPackage:[database_ packageWithName:name_]];
5426 /* Package Table {{{ */
5427 @interface PackageTable : UIView <
5428 UITableViewDataSource,
5431 _transient Database *database_;
5433 NSMutableArray *packages_;
5434 NSMutableArray *sections_;
5436 NSMutableArray *index_;
5437 NSMutableDictionary *indices_;
5438 // XXX: this target_ seems to be delegate_. :(
5439 _transient id target_;
5441 // XXX: why do we even have this delegate_?
5442 _transient id delegate_;
5445 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5447 - (void) setDelegate:(id)delegate;
5449 - (void) reloadData;
5450 - (void) resetCursor;
5452 - (UITableView *) list;
5454 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5456 - (void) deselectWithAnimation:(BOOL)animated;
5460 @implementation PackageTable
5463 [packages_ release];
5464 [sections_ release];
5472 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5473 NSInteger count([sections_ count]);
5474 return count == 0 ? 1 : count;
5477 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5478 if ([sections_ count] == 0)
5480 return [[sections_ objectAtIndex:section] name];
5483 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5484 if ([sections_ count] == 0)
5486 return [[sections_ objectAtIndex:section] count];
5489 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5490 @synchronized (database_) {
5491 if ([database_ era] != era_)
5494 Section *section([sections_ objectAtIndex:[path section]]);
5495 NSInteger row([path row]);
5496 Package *package([packages_ objectAtIndex:([section row] + row)]);
5497 return [[package retain] autorelease];
5500 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5501 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5503 cell = [[[PackageCell alloc] init] autorelease];
5504 [cell setPackage:[self packageAtIndexPath:path]];
5508 - (void) deselectWithAnimation:(BOOL)animated {
5509 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5512 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5513 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5516 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5517 Package *package([self packageAtIndexPath:path]);
5518 package = [database_ packageWithName:[package id]];
5519 [target_ performSelector:action_ withObject:package];
5523 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5524 return [packages_ count] > 20 ? index_ : nil;
5527 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5531 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5532 if ((self = [super initWithFrame:frame]) != nil) {
5533 database_ = database;
5538 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5539 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5541 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5542 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5544 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5545 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5546 [list_ setRowHeight:73.0f];
5547 [self addSubview:list_];
5549 [list_ setDataSource:self];
5550 [list_ setDelegate:self];
5554 - (void) setDelegate:(id)delegate {
5555 delegate_ = delegate;
5558 - (bool) hasPackage:(Package *)package {
5562 - (void) reloadData {
5563 era_ = [database_ era];
5564 NSArray *packages = [database_ packages];
5566 [packages_ removeAllObjects];
5567 [sections_ removeAllObjects];
5569 _profile(PackageTable$reloadData$Filter)
5570 for (Package *package in packages)
5571 if ([self hasPackage:package])
5572 [packages_ addObject:package];
5575 [index_ removeAllObjects];
5576 [indices_ removeAllObjects];
5578 Section *section = nil;
5580 _profile(PackageTable$reloadData$Section)
5581 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5585 _profile(PackageTable$reloadData$Section$Package)
5586 package = [packages_ objectAtIndex:offset];
5587 index = [package index];
5590 if (section == nil || [section index] != index) {
5591 _profile(PackageTable$reloadData$Section$Allocate)
5592 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5595 [index_ addObject:[section name]];
5596 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5598 _profile(PackageTable$reloadData$Section$Add)
5599 [sections_ addObject:section];
5603 [section addToCount];
5607 _profile(PackageTable$reloadData$List)
5612 - (void) resetCursor {
5613 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5616 - (UITableView *) list {
5620 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5621 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5626 /* Filtered Package Table {{{ */
5627 @interface FilteredPackageTable : PackageTable {
5633 - (void) setObject:(id)object;
5634 - (void) setObject:(id)object forFilter:(SEL)filter;
5636 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5640 @implementation FilteredPackageTable
5648 - (void) setFilter:(SEL)filter {
5651 /* XXX: this is an unsafe optimization of doomy hell */
5652 Method method(class_getInstanceMethod([Package class], filter));
5653 _assert(method != NULL);
5654 imp_ = method_getImplementation(method);
5655 _assert(imp_ != NULL);
5658 - (void) setObject:(id)object {
5664 object_ = [object retain];
5667 - (void) setObject:(id)object forFilter:(SEL)filter {
5668 [self setFilter:filter];
5669 [self setObject:object];
5672 - (bool) hasPackage:(Package *)package {
5673 _profile(FilteredPackageTable$hasPackage)
5674 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5678 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5679 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5680 [self setFilter:filter];
5681 object_ = [object retain];
5689 /* Filtered Package Controller {{{ */
5690 @interface FilteredPackageController : CYViewController {
5691 _transient Database *database_;
5692 FilteredPackageTable *packages_;
5696 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5700 @implementation FilteredPackageController
5703 [packages_ release];
5709 - (void) viewDidAppear:(BOOL)animated {
5710 [super viewDidAppear:animated];
5711 [packages_ deselectWithAnimation:animated];
5714 - (void) didSelectPackage:(Package *)package {
5715 PackageController *view([delegate_ packageController]);
5716 [view setPackage:package];
5717 [view setDelegate:delegate_];
5718 [[self navigationController] pushViewController:view animated:YES];
5721 - (NSString *) title { return title_; }
5723 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5724 if ((self = [super init]) != nil) {
5725 database_ = database;
5726 title_ = [title copy];
5727 [[self navigationItem] setTitle:title_];
5729 packages_ = [[FilteredPackageTable alloc]
5730 initWithFrame:[[self view] bounds]
5733 action:@selector(didSelectPackage:)
5738 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5739 [[self view] addSubview:packages_];
5743 - (void) reloadData {
5744 [packages_ reloadData];
5747 - (void) setDelegate:(id)delegate {
5748 [super setDelegate:delegate];
5749 [packages_ setDelegate:delegate];
5756 /* Add Source Controller {{{ */
5757 @interface AddSourceController : CYViewController {
5758 _transient Database *database_;
5761 - (id) initWithDatabase:(Database *)database;
5765 @implementation AddSourceController
5767 - (id) initWithDatabase:(Database *)database {
5768 if ((self = [super init]) != nil) {
5769 database_ = database;
5775 /* Source Cell {{{ */
5776 @interface SourceCell : CYTableViewCell <
5781 NSString *description_;
5785 - (void) setSource:(Source *)source;
5789 @implementation SourceCell
5791 - (void) clearSource {
5794 [description_ release];
5803 - (void) setSource:(Source *)source {
5807 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5809 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5810 icon_ = [icon_ retain];
5812 origin_ = [[source name] retain];
5813 label_ = [[source uri] retain];
5814 description_ = [[source description] retain];
5816 [content_ setNeedsDisplay];
5824 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5825 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5826 UIView *content([self contentView]);
5827 CGRect bounds([content bounds]);
5829 content_ = [[ContentView alloc] initWithFrame:bounds];
5830 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5831 [content_ setBackgroundColor:[UIColor whiteColor]];
5832 [content addSubview:content_];
5834 [content_ setDelegate:self];
5835 [content_ setOpaque:YES];
5839 - (void) drawContentRect:(CGRect)rect {
5840 bool highlighted(highlighted_);
5841 float width(rect.size.width);
5844 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5851 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5855 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5859 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5864 /* Source Table {{{ */
5865 @interface SourceTable : CYViewController <
5866 UITableViewDataSource,
5869 _transient Database *database_;
5871 NSMutableArray *sources_;
5875 UIProgressHUD *hud_;
5878 //NSURLConnection *installer_;
5879 NSURLConnection *trivial_;
5880 NSURLConnection *trivial_bz2_;
5881 NSURLConnection *trivial_gz_;
5882 //NSURLConnection *automatic_;
5887 - (id) initWithDatabase:(Database *)database;
5889 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5893 @implementation SourceTable
5895 - (void) _releaseConnection:(NSURLConnection *)connection {
5896 if (connection != nil) {
5897 [connection cancel];
5898 //[connection setDelegate:nil];
5899 [connection release];
5911 //[self _releaseConnection:installer_];
5912 [self _releaseConnection:trivial_];
5913 [self _releaseConnection:trivial_gz_];
5914 [self _releaseConnection:trivial_bz2_];
5915 //[self _releaseConnection:automatic_];
5922 - (void) viewDidAppear:(BOOL)animated {
5923 [super viewDidAppear:animated];
5924 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5927 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5928 return offset_ == 0 ? 1 : 2;
5931 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5932 switch (section + (offset_ == 0 ? 1 : 0)) {
5933 case 0: return UCLocalize("ENTERED_BY_USER");
5934 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5940 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5941 int count = [sources_ count];
5943 case 0: return (offset_ == 0 ? count : offset_);
5944 case 1: return count - offset_;
5950 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5952 switch (indexPath.section) {
5953 case 0: idx = indexPath.row; break;
5954 case 1: idx = indexPath.row + offset_; break;
5958 return [sources_ objectAtIndex:idx];
5961 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5962 Source *source = [self sourceAtIndexPath:indexPath];
5963 return [source description] == nil ? 56 : 73;
5966 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5967 static NSString *cellIdentifier = @"SourceCell";
5969 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5970 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5971 [cell setSource:[self sourceAtIndexPath:indexPath]];
5976 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5977 return UITableViewCellAccessoryDisclosureIndicator;
5980 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5981 Source *source = [self sourceAtIndexPath:indexPath];
5983 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5984 initWithDatabase:database_
5985 title:[source label]
5986 filter:@selector(isVisibleInSource:)
5990 [packages setDelegate:delegate_];
5992 [[self navigationController] pushViewController:packages animated:YES];
5995 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5996 Source *source = [self sourceAtIndexPath:indexPath];
5997 return [source record] != nil;
6000 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
6001 Source *source = [self sourceAtIndexPath:indexPath];
6002 [Sources_ removeObjectForKey:[source key]];
6003 [delegate_ syncData];
6007 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
6010 @"./", @"Distribution",
6011 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
6013 [delegate_ syncData];
6016 - (NSString *) getWarning {
6017 NSString *href(href_);
6018 NSRange colon([href rangeOfString:@"://"]);
6019 if (colon.location != NSNotFound)
6020 href = [href substringFromIndex:(colon.location + 3)];
6021 href = [href stringByAddingPercentEscapes];
6022 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
6023 href = [href stringByCachingURLWithCurrentCDN];
6025 NSURL *url([NSURL URLWithString:href]);
6027 NSStringEncoding encoding;
6028 NSError *error(nil);
6030 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
6031 return [warning length] == 0 ? nil : warning;
6035 - (void) _endConnection:(NSURLConnection *)connection {
6036 // XXX: the memory management in this method is horribly awkward
6038 NSURLConnection **field = NULL;
6039 if (connection == trivial_)
6041 else if (connection == trivial_bz2_)
6042 field = &trivial_bz2_;
6043 else if (connection == trivial_gz_)
6044 field = &trivial_gz_;
6045 _assert(field != NULL);
6046 [connection release];
6051 trivial_bz2_ == nil &&
6057 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6060 UIAlertView *alert = [[[UIAlertView alloc]
6061 initWithTitle:UCLocalize("SOURCE_WARNING")
6064 cancelButtonTitle:UCLocalize("CANCEL")
6065 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6068 [alert setContext:@"warning"];
6069 [alert setNumberOfRows:1];
6073 } else if (error_ != nil) {
6074 UIAlertView *alert = [[[UIAlertView alloc]
6075 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6076 message:[error_ localizedDescription]
6078 cancelButtonTitle:UCLocalize("OK")
6079 otherButtonTitles:nil
6082 [alert setContext:@"urlerror"];
6085 UIAlertView *alert = [[[UIAlertView alloc]
6086 initWithTitle:UCLocalize("NOT_REPOSITORY")
6087 message:UCLocalize("NOT_REPOSITORY_EX")
6089 cancelButtonTitle:UCLocalize("OK")
6090 otherButtonTitles:nil
6093 [alert setContext:@"trivial"];
6097 [delegate_ setStatusBarShowsProgress:NO];
6098 [delegate_ removeProgressHUD:hud_];
6108 if (error_ != nil) {
6115 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6116 switch ([response statusCode]) {
6122 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6123 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6125 error_ = [error retain];
6126 [self _endConnection:connection];
6129 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6130 [self _endConnection:connection];
6133 - (NSString *) title { return UCLocalize("SOURCES"); }
6135 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6136 NSMutableURLRequest *request = [NSMutableURLRequest
6137 requestWithURL:[NSURL URLWithString:href]
6138 cachePolicy:NSURLRequestUseProtocolCachePolicy
6139 timeoutInterval:120.0
6142 [request setHTTPMethod:method];
6144 if (Machine_ != NULL)
6145 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6146 if (UniqueID_ != nil)
6147 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6149 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6151 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6154 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6155 NSString *context([alert context]);
6157 if ([context isEqualToString:@"source"]) {
6160 NSString *href = [[alert textField] text];
6162 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6164 if (![href hasSuffix:@"/"])
6165 href_ = [href stringByAppendingString:@"/"];
6168 href_ = [href_ retain];
6170 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6171 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6172 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6173 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6177 // XXX: this is stupid
6178 hud_ = [[delegate_ addProgressHUD] retain];
6179 [hud_ setText:UCLocalize("VERIFYING_URL")];
6188 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6189 } else if ([context isEqualToString:@"trivial"])
6190 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6191 else if ([context isEqualToString:@"urlerror"])
6192 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6193 else if ([context isEqualToString:@"warning"]) {
6208 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6212 - (id) initWithDatabase:(Database *)database {
6213 if ((self = [super init]) != nil) {
6214 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6215 [self updateButtonsForEditingStatus:NO animated:NO];
6217 database_ = database;
6218 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6220 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6221 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6222 [[self view] addSubview:list_];
6224 [list_ setDataSource:self];
6225 [list_ setDelegate:self];
6231 - (void) reloadData {
6233 if (!list.ReadMainList())
6236 [sources_ removeAllObjects];
6237 [sources_ addObjectsFromArray:[database_ sources]];
6239 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6242 int count([sources_ count]);
6244 for (int i = 0; i != count; i++) {
6245 if ([[sources_ objectAtIndex:i] record] == nil)
6250 [list_ setEditing:NO];
6251 [self updateButtonsForEditingStatus:NO animated:NO];
6255 - (void) addButtonClicked {
6256 /*[book_ pushPage:[[[AddSourceController alloc]
6261 UIAlertView *alert = [[[UIAlertView alloc]
6262 initWithTitle:UCLocalize("ENTER_APT_URL")
6265 cancelButtonTitle:UCLocalize("CANCEL")
6266 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6269 [alert setContext:@"source"];
6270 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6272 [alert setNumberOfRows:1];
6273 [alert addTextFieldWithValue:@"http://" label:@""];
6275 UITextInputTraits *traits = [[alert textField] textInputTraits];
6276 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6277 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6278 [traits setKeyboardType:UIKeyboardTypeURL];
6279 // XXX: UIReturnKeyDone
6280 [traits setReturnKeyType:UIReturnKeyNext];
6285 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6286 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6287 initWithTitle:UCLocalize("ADD")
6288 style:UIBarButtonItemStylePlain
6290 action:@selector(addButtonClicked)
6291 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6293 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6294 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6295 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6297 action:@selector(editButtonClicked)
6298 ] autorelease] animated:animated];
6300 if (IsWildcat_ && !editing)
6301 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6302 initWithTitle:UCLocalize("SETTINGS")
6303 style:UIBarButtonItemStylePlain
6305 action:@selector(settingsButtonClicked)
6309 - (void) settingsButtonClicked {
6310 [delegate_ showSettings];
6313 - (void) editButtonClicked {
6314 [list_ setEditing:![list_ isEditing] animated:YES];
6316 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6322 /* Installed Controller {{{ */
6323 @interface InstalledController : FilteredPackageController {
6327 - (id) initWithDatabase:(Database *)database;
6329 - (void) updateRoleButton;
6330 - (void) queueStatusDidChange;
6334 @implementation InstalledController
6340 - (NSString *) title { return UCLocalize("INSTALLED"); }
6342 - (id) initWithDatabase:(Database *)database {
6343 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6344 [self updateRoleButton];
6345 [self queueStatusDidChange];
6350 - (void) queueButtonClicked {
6355 - (void) queueStatusDidChange {
6359 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6360 initWithTitle:UCLocalize("QUEUE")
6361 style:UIBarButtonItemStyleDone
6363 action:@selector(queueButtonClicked)
6366 [[self navigationItem] setLeftBarButtonItem:nil];
6372 - (void) reloadData {
6373 [packages_ reloadData];
6376 - (void) updateRoleButton {
6377 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6378 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6379 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6380 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6382 action:@selector(roleButtonClicked)
6386 - (void) roleButtonClicked {
6387 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6388 [packages_ reloadData];
6391 [self updateRoleButton];
6394 - (void) setDelegate:(id)delegate {
6395 [super setDelegate:delegate];
6396 [packages_ setDelegate:delegate];
6402 /* Home Controller {{{ */
6403 @interface HomeController : CYBrowserController {
6408 @implementation HomeController
6410 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6411 [super _setMoreHeaders:request];
6414 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6415 if (UniqueID_ != nil)
6416 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6418 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6421 - (void) aboutButtonClicked {
6422 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6424 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6425 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6426 [alert setCancelButtonIndex:0];
6429 @"Copyright (C) 2008-2010\n"
6430 "Jay Freeman (saurik)\n"
6431 "saurik@saurik.com\n"
6432 "http://www.saurik.com/"
6438 - (void) viewWillAppear:(BOOL)animated {
6439 [super viewWillAppear:animated];
6440 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6443 - (void) viewWillDisappear:(BOOL)animated {
6444 [super viewWillDisappear:animated];
6445 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6449 if ((self = [super init]) != nil) {
6450 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6451 initWithTitle:UCLocalize("ABOUT")
6452 style:UIBarButtonItemStylePlain
6454 action:@selector(aboutButtonClicked)
6461 /* Manage Controller {{{ */
6462 @interface ManageController : CYBrowserController {
6465 - (void) queueStatusDidChange;
6468 @implementation ManageController
6471 if ((self = [super init]) != nil) {
6472 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6474 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6475 initWithTitle:UCLocalize("SETTINGS")
6476 style:UIBarButtonItemStylePlain
6478 action:@selector(settingsButtonClicked)
6481 [self queueStatusDidChange];
6485 - (void) settingsButtonClicked {
6486 [delegate_ showSettings];
6490 - (void) queueButtonClicked {
6494 - (void) applyLoadingTitle {
6495 // No "Loading" title.
6498 - (void) applyRightButton {
6503 - (void) queueStatusDidChange {
6505 if (!IsWildcat_ && Queuing_) {
6506 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6507 initWithTitle:UCLocalize("QUEUE")
6508 style:UIBarButtonItemStyleDone
6510 action:@selector(queueButtonClicked)
6513 [[self navigationItem] setRightBarButtonItem:nil];
6518 - (bool) isLoading {
6525 /* Refresh Bar {{{ */
6526 @interface RefreshBar : UINavigationBar {
6527 UIProgressIndicator *indicator_;
6528 UITextLabel *prompt_;
6529 UIProgressBar *progress_;
6530 UINavigationButton *cancel_;
6535 @implementation RefreshBar
6538 [indicator_ release];
6540 [progress_ release];
6545 - (void) positionViews {
6546 CGRect frame = [cancel_ frame];
6547 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6548 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6549 [cancel_ setFrame:frame];
6551 CGSize prgsize = {75, 100};
6553 [self frame].size.width - prgsize.width - 10,
6554 ([self frame].size.height - prgsize.height) / 2
6556 [progress_ setFrame:prgrect];
6558 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6559 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6560 CGRect indrect = {{indoffset, indoffset}, indsize};
6561 [indicator_ setFrame:indrect];
6563 CGSize prmsize = {215, indsize.height + 4};
6565 indoffset * 2 + indsize.width,
6566 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6568 [prompt_ setFrame:prmrect];
6571 - (void)setFrame:(CGRect)frame {
6572 [super setFrame:frame];
6574 [self positionViews];
6577 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6578 if ((self = [super initWithFrame:frame])) {
6579 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6581 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6582 [self setBarStyle:UIBarStyleBlack];
6584 UIBarStyle barstyle([self _barStyle:NO]);
6585 bool ugly(barstyle == UIBarStyleDefault);
6587 UIProgressIndicatorStyle style = ugly ?
6588 UIProgressIndicatorStyleMediumBrown :
6589 UIProgressIndicatorStyleMediumWhite;
6591 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6592 [indicator_ setStyle:style];
6593 [indicator_ startAnimation];
6594 [self addSubview:indicator_];
6596 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6597 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6598 [prompt_ setBackgroundColor:[UIColor clearColor]];
6599 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6600 [self addSubview:prompt_];
6602 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6603 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6604 [progress_ setStyle:0];
6605 [self addSubview:progress_];
6607 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6608 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6609 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6610 [cancel_ setBarStyle:barstyle];
6612 [self positionViews];
6617 [cancel_ removeFromSuperview];
6621 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6622 [progress_ setProgress:0];
6623 [self addSubview:cancel_];
6627 [cancel_ removeFromSuperview];
6630 - (void) setPrompt:(NSString *)prompt {
6631 [prompt_ setText:prompt];
6634 - (void) setProgress:(float)progress {
6635 [progress_ setProgress:progress];
6641 @class CYNavigationController;
6643 /* Cydia Tab Bar Controller {{{ */
6644 @interface CYTabBarController : UITabBarController <
6647 _transient Database *database_;
6648 RefreshBar *refreshbar_;
6652 // XXX: ok, "updatedelegate_"?...
6653 _transient NSObject<CydiaDelegate> *updatedelegate_;
6658 - (void) dropBar:(BOOL)animated;
6659 - (void) beginUpdate;
6660 - (void) raiseBar:(BOOL)animated;
6665 @implementation CYTabBarController
6667 /* XXX: some logic should probably go here related to
6668 freeing the view controllers on tab change */
6670 - (void) reloadData {
6671 size_t count([[self viewControllers] count]);
6672 for (size_t i(0); i != count; ++i) {
6673 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6678 - (id) initWithDatabase:(Database *)database {
6679 if ((self = [super init]) != nil) {
6680 database_ = database;
6682 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6683 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6685 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6689 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6690 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
6693 - (void) setUpdate:(NSDate *)date {
6697 - (void) beginUpdate {
6698 [refreshbar_ start];
6701 [updatedelegate_ retainNetworkActivityIndicator];
6705 detachNewThreadSelector:@selector(performUpdate)
6711 - (void) performUpdate { _pooled
6713 status.setDelegate(self);
6714 [database_ updateWithStatus:status];
6717 performSelectorOnMainThread:@selector(completeUpdate)
6723 - (void) stopUpdateWithSelector:(SEL)selector {
6725 [updatedelegate_ releaseNetworkActivityIndicator];
6727 [self raiseBar:YES];
6730 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6733 - (void) completeUpdate {
6736 [self stopUpdateWithSelector:@selector(reloadData)];
6739 - (void) cancelUpdate {
6740 [self stopUpdateWithSelector:@selector(updateData)];
6743 - (void) cancelPressed {
6744 [self cancelUpdate];
6751 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6752 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6755 - (void) startProgress {
6758 - (void) setProgressTitle:(NSString *)title {
6760 performSelectorOnMainThread:@selector(_setProgressTitle:)
6766 - (bool) isCancelling:(size_t)received {
6770 - (void) setProgressPercent:(float)percent {
6772 performSelectorOnMainThread:@selector(_setProgressPercent:)
6773 withObject:[NSNumber numberWithFloat:percent]
6778 - (void) addProgressOutput:(NSString *)output {
6780 performSelectorOnMainThread:@selector(_addProgressOutput:)
6786 - (void) _setProgressTitle:(NSString *)title {
6787 [refreshbar_ setPrompt:title];
6790 - (void) _setProgressPercent:(NSNumber *)percent {
6791 [refreshbar_ setProgress:[percent floatValue]];
6794 - (void) _addProgressOutput:(NSString *)output {
6797 - (void) setUpdateDelegate:(id)delegate {
6798 updatedelegate_ = delegate;
6801 - (CGFloat) statusBarHeight {
6802 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6803 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6805 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6809 - (UIView *) transitionView {
6810 if ([self respondsToSelector:@selector(_transitionView)])
6811 return [self _transitionView];
6813 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6816 - (void) dropBar:(BOOL)animated {
6821 UIView *transition([self transitionView]);
6822 [[self view] addSubview:refreshbar_];
6824 CGRect barframe([refreshbar_ frame]);
6826 if (false) // XXX: _UIApplicationLinkedOnOrAfter(4)
6827 barframe.origin.y = [self statusBarHeight];
6829 barframe.origin.y = 0;
6831 [refreshbar_ setFrame:barframe];
6834 [UIView beginAnimations:nil context:NULL];
6836 CGRect viewframe = [transition frame];
6837 viewframe.origin.y += barframe.size.height;
6838 viewframe.size.height -= barframe.size.height;
6839 [transition setFrame:viewframe];
6842 [UIView commitAnimations];
6844 // Ensure bar has the proper width for our view, it might have changed
6845 barframe.size.width = viewframe.size.width;
6846 [refreshbar_ setFrame:barframe];
6848 // XXX: fix Apple's layout bug
6849 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6852 - (void) raiseBar:(BOOL)animated {
6857 UIView *transition([self transitionView]);
6858 [refreshbar_ removeFromSuperview];
6860 CGRect barframe([refreshbar_ frame]);
6863 [UIView beginAnimations:nil context:NULL];
6865 CGRect viewframe = [transition frame];
6866 viewframe.origin.y -= barframe.size.height;
6867 viewframe.size.height += barframe.size.height;
6868 [transition setFrame:viewframe];
6871 [UIView commitAnimations];
6873 // XXX: fix Apple's layout bug
6874 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6878 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6879 // XXX: fix Apple's layout bug
6880 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6884 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6885 bool dropped(dropped_);
6890 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6895 // XXX: fix Apple's layout bug
6896 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6899 - (void) statusBarFrameChanged:(NSNotification *)notification {
6907 [refreshbar_ release];
6908 [[NSNotificationCenter defaultCenter] removeObserver:self];
6915 /* Cydia Navigation Controller {{{ */
6916 @interface CYNavigationController : UINavigationController {
6917 _transient Database *database_;
6918 _transient id<UINavigationControllerDelegate> delegate_;
6921 - (id) initWithDatabase:(Database *)database;
6922 - (void) reloadData;
6927 @implementation CYNavigationController
6929 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6930 // Inherit autorotation settings for modal parents.
6931 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6932 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6934 return [super shouldAutorotateToInterfaceOrientation:orientation];
6942 - (void) reloadData {
6943 size_t count([[self viewControllers] count]);
6944 for (size_t i(0); i != count; ++i) {
6945 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6950 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6951 delegate_ = delegate;
6954 - (id) initWithDatabase:(Database *)database {
6955 if ((self = [super init]) != nil) {
6956 database_ = database;
6962 /* Cydia:// Protocol {{{ */
6963 @interface CydiaURLProtocol : NSURLProtocol {
6968 @implementation CydiaURLProtocol
6970 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6971 NSURL *url([request URL]);
6974 NSString *scheme([[url scheme] lowercaseString]);
6975 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6980 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6984 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6985 id<NSURLProtocolClient> client([self client]);
6987 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6989 NSData *data(UIImagePNGRepresentation(icon));
6991 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6992 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6993 [client URLProtocol:self didLoadData:data];
6994 [client URLProtocolDidFinishLoading:self];
6998 - (void) startLoading {
6999 id<NSURLProtocolClient> client([self client]);
7000 NSURLRequest *request([self request]);
7002 NSURL *url([request URL]);
7003 NSString *href([url absoluteString]);
7005 NSString *path([href substringFromIndex:8]);
7006 NSRange slash([path rangeOfString:@"/"]);
7009 if (slash.location == NSNotFound) {
7013 command = [path substringToIndex:slash.location];
7014 path = [path substringFromIndex:(slash.location + 1)];
7017 Database *database([Database sharedInstance]);
7019 if ([command isEqualToString:@"package-icon"]) {
7022 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7023 Package *package([database packageWithName:path]);
7026 UIImage *icon([package icon]);
7027 [self _returnPNGWithImage:icon forRequest:request];
7028 } else if ([command isEqualToString:@"source-icon"]) {
7031 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7032 NSString *source(Simplify(path));
7033 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7035 icon = [UIImage applicationImageNamed:@"unknown.png"];
7036 [self _returnPNGWithImage:icon forRequest:request];
7037 } else if ([command isEqualToString:@"uikit-image"]) {
7040 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7041 UIImage *icon(_UIImageWithName(path));
7042 [self _returnPNGWithImage:icon forRequest:request];
7043 } else if ([command isEqualToString:@"section-icon"]) {
7046 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7047 NSString *section(Simplify(path));
7048 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7050 icon = [UIImage applicationImageNamed:@"unknown.png"];
7051 [self _returnPNGWithImage:icon forRequest:request];
7053 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7057 - (void) stopLoading {
7063 /* Sections Controller {{{ */
7064 @interface SectionsController : CYViewController <
7065 UITableViewDataSource,
7068 _transient Database *database_;
7069 NSMutableArray *sections_;
7070 NSMutableArray *filtered_;
7076 - (id) initWithDatabase:(Database *)database;
7077 - (void) reloadData;
7080 - (void) editButtonClicked;
7084 @implementation SectionsController
7087 [list_ setDataSource:nil];
7088 [list_ setDelegate:nil];
7090 [sections_ release];
7091 [filtered_ release];
7093 [accessory_ release];
7097 - (void) viewDidAppear:(BOOL)animated {
7098 [super viewDidAppear:animated];
7099 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7102 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7103 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7107 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7108 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7111 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7115 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7116 static NSString *reuseIdentifier = @"SectionCell";
7118 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7120 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7122 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7127 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7131 Section *section = [self sectionAtIndexPath:indexPath];
7132 NSString *name = [section name];
7135 if ([indexPath row] == 0) {
7138 title = UCLocalize("ALL_PACKAGES");
7141 name = [NSString stringWithString:name];
7142 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7145 title = UCLocalize("NO_SECTION");
7149 FilteredPackageController *table = [[[FilteredPackageController alloc]
7150 initWithDatabase:database_
7152 filter:@selector(isVisibleInSection:)
7156 [table setDelegate:delegate_];
7158 [[self navigationController] pushViewController:table animated:YES];
7161 - (NSString *) title { return UCLocalize("SECTIONS"); }
7163 - (id) initWithDatabase:(Database *)database {
7164 if ((self = [super init]) != nil) {
7165 database_ = database;
7167 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7169 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7170 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7172 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7173 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7174 [list_ setRowHeight:45.0f];
7175 [[self view] addSubview:list_];
7177 [list_ setDataSource:self];
7178 [list_ setDelegate:self];
7184 - (void) reloadData {
7185 NSArray *packages = [database_ packages];
7187 [sections_ removeAllObjects];
7188 [filtered_ removeAllObjects];
7190 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7193 for (Package *package in packages) {
7194 NSString *name([package section]);
7195 NSString *key(name == nil ? @"" : name);
7199 _profile(SectionsView$reloadData$Section)
7200 section = [sections objectForKey:key];
7201 if (section == nil) {
7202 _profile(SectionsView$reloadData$Section$Allocate)
7203 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
7204 [sections setObject:section forKey:key];
7209 [section addToCount];
7211 _profile(SectionsView$reloadData$Filter)
7212 if (![package valid] || ![package visible])
7220 [sections_ addObjectsFromArray:[sections allValues]];
7222 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7224 for (Section *section in sections_) {
7225 size_t count([section row]);
7229 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7230 [section setCount:count];
7231 [filtered_ addObject:section];
7234 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7235 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
7236 style:UIBarButtonItemStylePlain
7238 action:@selector(editButtonClicked)
7239 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7245 - (void) resetView {
7247 [self editButtonClicked];
7250 - (void) editButtonClicked {
7251 if ((editing_ = !editing_))
7254 [delegate_ updateData];
7256 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7257 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
7258 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
7261 - (UIView *) accessoryView {
7267 /* Changes Controller {{{ */
7268 @interface ChangesController : CYViewController <
7269 UITableViewDataSource,
7272 _transient Database *database_;
7274 CFMutableArrayRef packages_;
7275 NSMutableArray *sections_;
7278 BOOL hasSentFirstLoad_;
7281 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
7282 - (void) reloadData;
7286 @implementation ChangesController
7289 [list_ setDelegate:nil];
7290 [list_ setDataSource:nil];
7292 CFRelease(packages_);
7294 [sections_ release];
7299 - (void) viewDidAppear:(BOOL)animated {
7300 [super viewDidAppear:animated];
7301 if (!hasSentFirstLoad_) {
7302 hasSentFirstLoad_ = YES;
7303 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7305 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7309 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7310 NSInteger count([sections_ count]);
7311 return count == 0 ? 1 : count;
7314 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7315 if ([sections_ count] == 0)
7317 return [[sections_ objectAtIndex:section] name];
7320 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7321 if ([sections_ count] == 0)
7323 return [[sections_ objectAtIndex:section] count];
7326 - (Package *) packageAtIndex:(NSUInteger)index {
7327 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7330 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7331 @synchronized (database_) {
7332 if ([database_ era] != era_)
7335 Section *section([sections_ objectAtIndex:[path section]]);
7336 NSInteger row([path row]);
7337 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7340 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7341 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7343 cell = [[[PackageCell alloc] init] autorelease];
7344 [cell setPackage:[self packageAtIndexPath:path]];
7348 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7349 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7352 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7353 Package *package([self packageAtIndexPath:path]);
7354 PackageController *view([delegate_ packageController]);
7355 [view setDelegate:delegate_];
7356 [view setPackage:package];
7357 [[self navigationController] pushViewController:view animated:YES];
7361 - (void) refreshButtonClicked {
7362 [delegate_ beginUpdate];
7363 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7366 - (void) upgradeButtonClicked {
7367 [delegate_ distUpgrade];
7370 - (NSString *) title { return UCLocalize("CHANGES"); }
7372 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7373 if ((self = [super init]) != nil) {
7374 database_ = database;
7375 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7377 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7379 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7381 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7382 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7383 [list_ setRowHeight:73.0f];
7384 [[self view] addSubview:list_];
7386 [list_ setDataSource:self];
7387 [list_ setDelegate:self];
7389 delegate_ = delegate;
7393 - (void) _reloadPackages:(NSArray *)packages {
7395 for (Package *package in packages)
7396 if ([package upgradableAndEssential:YES] || [package visible])
7397 CFArrayAppendValue(packages_, package);
7400 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7404 - (void) reloadData {
7405 era_ = [database_ era];
7406 NSArray *packages = [database_ packages];
7408 CFArrayRemoveAllValues(packages_);
7410 [sections_ removeAllObjects];
7413 UIProgressHUD *hud([delegate_ addProgressHUD]);
7414 [hud setText:UCLocalize("LOADING")];
7415 //NSLog(@"HUD:%@::%@", delegate_, hud);
7416 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7417 [delegate_ removeProgressHUD:hud];
7419 [self _reloadPackages:packages];
7422 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7423 Section *ignored = nil;
7424 Section *section = nil;
7428 bool unseens = false;
7430 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7432 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7433 Package *package = [self packageAtIndex:offset];
7435 BOOL uae = [package upgradableAndEssential:YES];
7439 time_t seen([package seen]);
7441 if (section == nil || last != seen) {
7445 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7448 _profile(ChangesController$reloadData$Allocate)
7449 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7450 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7451 [sections_ addObject:section];
7455 [section addToCount];
7456 } else if ([package ignored]) {
7457 if (ignored == nil) {
7458 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7460 [ignored addToCount];
7463 [upgradable addToCount];
7468 CFRelease(formatter);
7471 Section *last = [sections_ lastObject];
7472 size_t count = [last count];
7473 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7474 [sections_ removeLastObject];
7477 if ([ignored count] != 0)
7478 [sections_ insertObject:ignored atIndex:0];
7480 [sections_ insertObject:upgradable atIndex:0];
7485 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7486 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7487 style:UIBarButtonItemStylePlain
7489 action:@selector(upgradeButtonClicked)
7492 if (![delegate_ updating])
7493 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7494 initWithTitle:UCLocalize("REFRESH")
7495 style:UIBarButtonItemStylePlain
7497 action:@selector(refreshButtonClicked)
7503 /* Search Controller {{{ */
7504 @interface SearchController : FilteredPackageController <
7507 UISearchBar *search_;
7510 - (id) initWithDatabase:(Database *)database;
7511 - (void) reloadData;
7515 @implementation SearchController
7522 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7523 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7524 [search_ resignFirstResponder];
7528 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7529 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7533 - (NSString *) title { return nil; }
7535 - (id) initWithDatabase:(Database *)database {
7536 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7539 - (void)viewDidAppear:(BOOL)animated {
7540 [super viewDidAppear:animated];
7542 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7543 [search_ layoutSubviews];
7544 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7546 UITextField *textField;
7547 if ([search_ respondsToSelector:@selector(searchField)])
7548 textField = [search_ searchField];
7550 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7552 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7553 [search_ setDelegate:self];
7554 [textField setEnablesReturnKeyAutomatically:NO];
7555 [[self navigationItem] setTitleView:textField];
7559 - (void) _reloadData {
7562 - (void) reloadData {
7563 _profile(SearchController$reloadData)
7564 [packages_ reloadData];
7567 [packages_ resetCursor];
7570 - (void) didSelectPackage:(Package *)package {
7571 [search_ resignFirstResponder];
7572 [super didSelectPackage:package];
7577 /* Settings Controller {{{ */
7578 @interface SettingsController : CYViewController <
7579 UITableViewDataSource,
7582 _transient Database *database_;
7585 UITableView *table_;
7586 UISwitch *subscribedSwitch_;
7587 UISwitch *ignoredSwitch_;
7588 UITableViewCell *subscribedCell_;
7589 UITableViewCell *ignoredCell_;
7592 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7596 @implementation SettingsController
7600 if (package_ != nil)
7603 [subscribedSwitch_ release];
7604 [ignoredSwitch_ release];
7605 [subscribedCell_ release];
7606 [ignoredCell_ release];
7611 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7612 if (package_ == nil)
7618 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7619 if (package_ == nil)
7625 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7626 return UCLocalize("SHOW_ALL_CHANGES_EX");
7629 - (void) onSubscribed:(id)control {
7630 bool value([control isOn]);
7631 if (package_ == nil)
7633 if ([package_ setSubscribed:value])
7634 [delegate_ updateData];
7637 - (void) onIgnored:(id)control {
7638 // TODO: set Held state - possibly call out to dpkg, etc.
7641 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7642 if (package_ == nil)
7645 switch ([indexPath row]) {
7646 case 0: return subscribedCell_;
7647 case 1: return ignoredCell_;
7655 - (NSString *) title { return UCLocalize("SETTINGS"); }
7657 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7658 if ((self = [super init])) {
7659 database_ = database;
7660 name_ = [package retain];
7662 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7664 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7665 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7666 [[self view] addSubview:table_];
7668 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7669 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7670 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7672 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7673 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7674 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7676 subscribedCell_ = [[UITableViewCell alloc] init];
7677 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7678 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7679 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7681 ignoredCell_ = [[UITableViewCell alloc] init];
7682 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7683 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7684 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7686 [table_ setDataSource:self];
7687 [table_ setDelegate:self];
7692 - (void) reloadData {
7693 if (package_ != nil)
7694 [package_ autorelease];
7695 package_ = [database_ packageWithName:name_];
7696 if (package_ != nil) {
7698 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7699 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7702 [table_ reloadData];
7707 /* Signature Controller {{{ */
7708 @interface SignatureController : CYBrowserController {
7709 _transient Database *database_;
7713 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7717 @implementation SignatureController
7724 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7726 [super webView:view didClearWindowObject:window forFrame:frame];
7729 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7730 if ((self = [super init]) != nil) {
7731 database_ = database;
7732 package_ = [package retain];
7737 - (void) reloadData {
7738 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7744 /* Role Controller {{{ */
7745 @interface RoleController : CYViewController <
7746 UITableViewDataSource,
7749 _transient Database *database_;
7750 // XXX: ok, "roledelegate_"?...
7751 _transient id roledelegate_;
7752 UITableView *table_;
7753 UISegmentedControl *segment_;
7757 - (void) showDoneButton;
7758 - (void) resizeSegmentedControl;
7762 @implementation RoleController
7766 [container_ release];
7771 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7772 if ((self = [super init])) {
7773 database_ = database;
7774 roledelegate_ = delegate;
7776 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7778 NSArray *items = [NSArray arrayWithObjects:
7780 UCLocalize("HACKER"),
7781 UCLocalize("DEVELOPER"),
7783 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7784 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7785 [container_ addSubview:segment_];
7788 if ([Role_ isEqualToString:@"User"]) index = 0;
7789 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7790 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7792 [segment_ setSelectedSegmentIndex:index];
7793 [self showDoneButton];
7796 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7797 [self resizeSegmentedControl];
7799 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7800 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7801 [table_ setDelegate:self];
7802 [table_ setDataSource:self];
7803 [[self view] addSubview:table_];
7804 [table_ reloadData];
7808 - (void) resizeSegmentedControl {
7809 CGFloat width = [[self view] frame].size.width;
7810 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7813 - (void) viewWillAppear:(BOOL)animated {
7814 [super viewWillAppear:animated];
7816 [self resizeSegmentedControl];
7819 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7820 [self resizeSegmentedControl];
7823 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7824 [self resizeSegmentedControl];
7828 NSString *role(nil);
7830 switch ([segment_ selectedSegmentIndex]) {
7831 case 0: role = @"User"; break;
7832 case 1: role = @"Hacker"; break;
7833 case 2: role = @"Developer"; break;
7838 if (![role isEqualToString:Role_]) {
7839 bool rolling(Role_ == nil);
7842 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7846 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7850 [roledelegate_ loadData];
7852 [roledelegate_ updateData];
7856 - (void) segmentChanged:(UISegmentedControl *)control {
7857 [self showDoneButton];
7860 - (void) saveAndClose {
7863 [[self navigationItem] setRightBarButtonItem:nil];
7864 [[self navigationController] dismissModalViewControllerAnimated:YES];
7867 - (void) doneButtonClicked {
7868 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7869 [spinner startAnimating];
7870 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7871 [[self navigationItem] setRightBarButtonItem:spinItem];
7873 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7876 - (void) showDoneButton {
7877 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7878 initWithTitle:UCLocalize("DONE")
7879 style:UIBarButtonItemStyleDone
7881 action:@selector(doneButtonClicked)
7882 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7885 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7886 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7890 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7894 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7895 return nil; // This method is required by the protocol.
7898 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7900 return UCLocalize("ROLE_EX");
7902 return [NSString stringWithFormat:
7903 @"%@: %@\n%@: %@\n%@: %@",
7904 UCLocalize("USER"), UCLocalize("USER_EX"),
7905 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7906 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7911 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7912 return section == 3 ? 44.0f : 0;
7915 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7916 return section == 3 ? container_ : nil;
7921 /* Stash Controller {{{ */
7922 @interface CYStashController : CYViewController {
7923 // XXX: just delete these things
7924 _transient UIActivityIndicatorView *spinner_;
7925 _transient UILabel *status_;
7926 _transient UILabel *caption_;
7930 @implementation CYStashController
7932 if ((self = [super init])) {
7933 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7935 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7936 CGRect spinrect = [spinner_ frame];
7937 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7938 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7939 [spinner_ setFrame:spinrect];
7940 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7941 [[self view] addSubview:spinner_];
7942 [spinner_ startAnimating];
7945 captrect.size.width = [[self view] frame].size.width;
7946 captrect.size.height = 40.0f;
7947 captrect.origin.x = 0;
7948 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7949 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7950 [caption_ setText:@"Initializing Filesystem"];
7951 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7952 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7953 [caption_ setTextColor:[UIColor whiteColor]];
7954 [caption_ setBackgroundColor:[UIColor clearColor]];
7955 [caption_ setShadowColor:[UIColor blackColor]];
7956 [caption_ setTextAlignment:UITextAlignmentCenter];
7957 [[self view] addSubview:caption_];
7960 statusrect.size.width = [[self view] frame].size.width;
7961 statusrect.size.height = 30.0f;
7962 statusrect.origin.x = 0;
7963 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7964 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7965 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7966 [status_ setText:@"(Cydia will exit when complete.)"];
7967 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7968 [status_ setTextColor:[UIColor whiteColor]];
7969 [status_ setBackgroundColor:[UIColor clearColor]];
7970 [status_ setShadowColor:[UIColor blackColor]];
7971 [status_ setTextAlignment:UITextAlignmentCenter];
7972 [[self view] addSubview:status_];
7976 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7977 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7992 @interface Cydia : UIApplication <
7993 ConfirmationControllerDelegate,
7994 ProgressControllerDelegate,
7996 UINavigationControllerDelegate,
7997 UITabBarControllerDelegate
7999 // XXX: evaluate all fields for _transient
8002 CYTabBarController *tabbar_;
8004 NSMutableArray *essential_;
8005 NSMutableArray *broken_;
8007 Database *database_;
8015 SectionsController *sections_;
8016 ChangesController *changes_;
8017 ManageController *manage_;
8018 SearchController *search_;
8019 SourceTable *sources_;
8020 InstalledController *installed_;
8023 CYStashController *stash_;
8028 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
8029 - (void) setPage:(CYViewController *)page;
8032 // XXX: I hate prototypes
8033 - (id) queueBadgeController;
8037 static _finline void _setHomePage(Cydia *self) {
8038 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
8041 @implementation Cydia
8043 - (void) beginUpdate {
8044 [tabbar_ beginUpdate];
8048 return [tabbar_ updating];
8051 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8056 if ([broken_ count] != 0) {
8057 int count = [broken_ count];
8059 UIAlertView *alert = [[[UIAlertView alloc]
8060 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8061 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8063 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8064 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8067 [alert setContext:@"fixhalf"];
8069 } else if (!Ignored_ && [essential_ count] != 0) {
8070 int count = [essential_ count];
8072 UIAlertView *alert = [[[UIAlertView alloc]
8073 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8074 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8076 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8077 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8080 [alert setContext:@"upgrade"];
8085 - (void) _saveConfig {
8091 NSString *error(nil);
8093 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8095 NSError *error(nil);
8096 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8097 NSLog(@"failure to save metadata data: %@", error);
8102 NSLog(@"failure to serialize metadata: %@", error);
8107 - (void) _updateData {
8110 /* XXX: this is just stupid */
8111 if (tag_ != 1 && sections_ != nil)
8112 [sections_ reloadData];
8113 if (tag_ != 2 && changes_ != nil)
8114 [changes_ reloadData];
8115 if (tag_ != 4 && search_ != nil)
8116 [search_ reloadData];
8118 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8120 [queueDelegate_ queueStatusDidChange];
8121 [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8124 - (int)indexOfTabWithTag:(int)tag {
8126 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8127 if ([[controller tabBarItem] tag] == tag)
8135 - (void) _refreshIfPossible {
8136 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8138 bool recently = false;
8139 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8140 if (update != nil) {
8141 NSTimeInterval interval([update timeIntervalSinceNow]);
8142 if (interval <= 0 && interval > -(15*60))
8146 // Don't automatic refresh if:
8147 // - We already refreshed recently.
8148 // - We already auto-refreshed this launch.
8149 // - Auto-refresh is disabled.
8150 if (recently || loaded_ || ManualRefresh) {
8151 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8153 // If we are cancelling due to ManualRefresh or a recent refresh
8154 // we need to make sure it knows it's already loaded.
8158 // We are going to load, so remember that.
8162 SCNetworkReachabilityFlags flags; {
8163 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8164 SCNetworkReachabilityGetFlags(reachability, &flags);
8165 CFRelease(reachability);
8168 // XXX: this elaborate mess is what Apple is using to determine this? :(
8169 // XXX: do we care if the user has to intervene? maybe that's ok?
8171 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8172 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8173 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8174 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8175 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8176 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8180 // If we can reach the server, auto-refresh!
8182 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8187 - (void) refreshIfPossible {
8188 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8191 - (void) _reloadData {
8192 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8193 [hud setText:UCLocalize("RELOADING_DATA")];
8195 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8198 [self removeProgressHUD:hud];
8202 [essential_ removeAllObjects];
8203 [broken_ removeAllObjects];
8205 NSArray *packages([database_ packages]);
8206 for (Package *package in packages) {
8208 [broken_ addObject:package];
8209 if ([package upgradableAndEssential:NO]) {
8210 if ([package essential])
8211 [essential_ addObject:package];
8216 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8218 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8219 [changesItem setBadgeValue:badge];
8220 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8222 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8223 [self setApplicationBadge:badge];
8225 [self setApplicationBadgeString:badge];
8227 [changesItem setBadgeValue:nil];
8228 [changesItem setAnimatedBadge:NO];
8230 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8231 [self removeApplicationBadge];
8232 else // XXX: maybe use setApplicationBadgeString also?
8233 [self setApplicationIconBadgeNumber:0];
8238 [self refreshIfPossible];
8241 - (void) updateData {
8250 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8251 _assert(file != NULL);
8253 for (NSString *key in [Sources_ allKeys]) {
8254 NSDictionary *source([Sources_ objectForKey:key]);
8256 fprintf(file, "%s %s %s\n",
8257 [[source objectForKey:@"Type"] UTF8String],
8258 [[source objectForKey:@"URI"] UTF8String],
8259 [[source objectForKey:@"Distribution"] UTF8String]
8267 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8268 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8270 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8271 [tabbar_ presentModalViewController:navigation animated:YES];
8274 detachNewThreadSelector:@selector(update_)
8277 title:UCLocalize("UPDATING_SOURCES")
8281 - (void) reloadData {
8282 @synchronized (self) {
8288 pkgProblemResolver *resolver = [database_ resolver];
8290 resolver->InstallProtect();
8291 if (!resolver->Resolve(true))
8295 - (CGRect) popUpBounds {
8296 return [[tabbar_ view] bounds];
8300 if (![database_ prepare])
8303 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8304 [page setDelegate:self];
8305 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8306 [confirm_ setDelegate:self];
8309 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8310 [tabbar_ presentModalViewController:confirm_ animated:YES];
8316 @synchronized (self) {
8321 - (void) clearPackage:(Package *)package {
8322 @synchronized (self) {
8329 - (void) installPackages:(NSArray *)packages {
8330 @synchronized (self) {
8331 for (Package *package in packages)
8338 - (void) installPackage:(Package *)package {
8339 @synchronized (self) {
8346 - (void) removePackage:(Package *)package {
8347 @synchronized (self) {
8354 - (void) distUpgrade {
8355 @synchronized (self) {
8356 if (![database_ upgrade])
8363 @synchronized (self) {
8368 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8371 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8373 if (navigation != nil) {
8374 [navigation pushViewController:progress animated:YES];
8376 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8378 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8379 [tabbar_ presentModalViewController:navigation animated:YES];
8383 detachNewThreadSelector:@selector(perform)
8386 title:UCLocalize("RUNNING")
8392 - (void) progressControllerIsComplete:(ProgressController *)progress {
8397 - (void) setPage:(CYViewController *)page {
8398 [page setDelegate:self];
8400 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8401 [navController setViewControllers:[NSArray arrayWithObject:page]];
8402 for (CYNavigationController *page in [tabbar_ viewControllers])
8403 if (page != navController)
8404 [page setViewControllers:nil];
8407 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8408 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8409 [browser loadURL:url];
8413 - (SectionsController *) sectionsController {
8414 if (sections_ == nil)
8415 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8419 - (ChangesController *) changesController {
8420 if (changes_ == nil)
8421 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8425 - (ManageController *) manageController {
8426 if (manage_ == nil) {
8427 manage_ = (ManageController *) [[self
8428 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8429 withClass:[ManageController class]
8432 queueDelegate_ = manage_;
8437 - (SearchController *) searchController {
8439 search_ = [[SearchController alloc] initWithDatabase:database_];
8443 - (SourceTable *) sourcesController {
8444 if (sources_ == nil)
8445 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8449 - (InstalledController *) installedController {
8450 if (installed_ == nil) {
8451 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8453 queueDelegate_ = installed_;
8458 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8459 int tag = [[viewController tabBarItem] tag];
8461 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8463 } else if (tag_ == 1) {
8464 [[self sectionsController] resetView];
8468 case kCydiaTag: _setHomePage(self); break;
8470 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8471 case kChangesTag: [self setPage:[self changesController]]; break;
8472 case kManageTag: [self setPage:[self manageController]]; break;
8473 case kInstalledTag: [self setPage:[self installedController]]; break;
8474 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8475 case kSearchTag: [self setPage:[self searchController]]; break;
8483 - (void) showSettings {
8484 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8485 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8487 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8488 [tabbar_ presentModalViewController:nav animated:YES];
8491 - (void) retainNetworkActivityIndicator {
8492 if (activity_++ == 0)
8493 [self setNetworkActivityIndicatorVisible:YES];
8496 - (void) releaseNetworkActivityIndicator {
8497 if (--activity_ == 0)
8498 [self setNetworkActivityIndicatorVisible:NO];
8501 - (void) setPackageController:(PackageController *)view {
8503 [view setPackage:nil];
8507 - (PackageController *) _packageController {
8508 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8511 - (PackageController *) packageController {
8512 return [self _packageController];
8515 // Returns the navigation controller for the queuing badge.
8516 - (id) queueBadgeController {
8517 int index = [self indexOfTabWithTag:kManageTag];
8519 index = [self indexOfTabWithTag:kInstalledTag];
8521 return [[tabbar_ viewControllers] objectAtIndex:index];
8524 - (void) cancelAndClear:(bool)clear {
8525 @synchronized (self) {
8537 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8538 NSString *context([alert context]);
8540 if ([context isEqualToString:@"fixhalf"]) {
8541 if (button == [alert firstOtherButtonIndex]) {
8542 @synchronized (self) {
8543 for (Package *broken in broken_) {
8546 NSString *id = [broken id];
8547 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8548 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8549 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8550 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8556 } else if (button == [alert cancelButtonIndex]) {
8557 [broken_ removeAllObjects];
8561 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8562 } else if ([context isEqualToString:@"upgrade"]) {
8563 if (button == [alert firstOtherButtonIndex]) {
8564 @synchronized (self) {
8565 for (Package *essential in essential_)
8566 [essential install];
8571 } else if (button == [alert firstOtherButtonIndex] + 1) {
8573 } else if (button == [alert cancelButtonIndex]) {
8577 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8581 - (void) system:(NSString *)command { _pooled
8582 system([command UTF8String]);
8585 - (void) applicationWillSuspend {
8587 [super applicationWillSuspend];
8590 - (BOOL) isSafeToSuspend {
8591 // Use external process status API internally.
8592 // This is probably a really bad idea.
8593 // XXX: what is the point of this? does this solve anything at all?
8594 uint64_t status = 0;
8596 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8597 notify_get_state(notify_token, &status);
8598 notify_cancel(notify_token);
8601 return locked_ == 0 && status == 0;
8604 - (void) applicationSuspend:(__GSEvent *)event {
8605 if ([self isSafeToSuspend])
8606 [super applicationSuspend:event];
8609 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8610 if ([self isSafeToSuspend])
8611 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8614 - (void) _setSuspended:(BOOL)value {
8615 if ([self isSafeToSuspend])
8616 [super _setSuspended:value];
8619 - (UIProgressHUD *) addProgressHUD {
8620 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8621 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8623 [window_ setUserInteractionEnabled:NO];
8626 UIViewController *target = tabbar_;
8627 while ([target modalViewController] != nil) target = [target modalViewController];
8628 [[target view] addSubview:hud];
8634 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8636 [hud removeFromSuperview];
8637 [window_ setUserInteractionEnabled:YES];
8641 - (CYViewController *) pageForPackage:(NSString *)name {
8642 if (Package *package = [database_ packageWithName:name]) {
8643 PackageController *view([self packageController]);
8644 [view setPackage:package];
8647 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8648 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8649 return [self _pageForURL:url withClass:[CYBrowserController class]];
8653 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8657 NSString *href([url absoluteString]);
8658 if ([href hasPrefix:@"apptapp://package/"])
8659 return [self pageForPackage:[href substringFromIndex:18]];
8661 NSString *scheme([[url scheme] lowercaseString]);
8662 if (![scheme isEqualToString:@"cydia"])
8664 NSString *path([url absoluteString]);
8665 if ([path length] < 8)
8667 path = [path substringFromIndex:8];
8668 if (![path hasPrefix:@"/"])
8669 path = [@"/" stringByAppendingString:path];
8671 if ([path isEqualToString:@"/add-source"])
8672 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8673 else if ([path isEqualToString:@"/storage"])
8674 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8675 else if ([path isEqualToString:@"/sources"])
8676 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8677 else if ([path isEqualToString:@"/packages"])
8678 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8679 else if ([path hasPrefix:@"/url/"])
8680 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8681 else if ([path hasPrefix:@"/launch/"])
8682 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8683 else if ([path hasPrefix:@"/package-settings/"])
8684 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8685 else if ([path hasPrefix:@"/package-signature/"])
8686 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8687 else if ([path hasPrefix:@"/package/"])
8688 return [self pageForPackage:[path substringFromIndex:9]];
8689 else if ([path hasPrefix:@"/files/"]) {
8690 NSString *name = [path substringFromIndex:7];
8692 if (Package *package = [database_ packageWithName:name]) {
8693 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8694 [files setPackage:package];
8702 - (BOOL) openCydiaURL:(NSURL *)url {
8703 CYViewController *page = nil;
8706 NSLog(@"open url: %@", url);
8708 if ((page = [self pageForURL:url hasTag:&tag])) {
8709 [self setPage:page];
8711 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8717 - (void) applicationOpenURL:(NSURL *)url {
8718 [super applicationOpenURL:url];
8719 NSLog(@"first: %@", url);
8720 if (!loaded_) starturl_ = [url retain];
8721 else [self openCydiaURL:url];
8724 - (void) applicationWillResignActive:(UIApplication *)application {
8725 // Stop refreshing if you get a phone call or lock the device.
8726 if ([tabbar_ updating])
8727 [tabbar_ cancelUpdate];
8729 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8730 [super applicationWillResignActive:application];
8733 - (void) addStashController {
8735 stash_ = [[CYStashController alloc] init];
8736 [window_ addSubview:[stash_ view]];
8739 - (void) removeStashController {
8740 [[stash_ view] removeFromSuperview];
8746 [self setIdleTimerDisabled:YES];
8748 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8749 [self setStatusBarShowsProgress:YES];
8750 UpdateExternalStatus(1);
8752 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8754 UpdateExternalStatus(0);
8755 [self setStatusBarShowsProgress:NO];
8757 [self removeStashController];
8759 if (ExecFork() == 0) {
8760 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8761 perror("launchctl stop");
8765 - (void) setupTabBarController {
8766 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8767 [tabbar_ setDelegate:self];
8769 NSMutableArray *items([NSMutableArray arrayWithObjects:
8770 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8771 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8772 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8773 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8777 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8778 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8780 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8783 NSMutableArray *controllers([NSMutableArray array]);
8785 for (UITabBarItem *item in items) {
8786 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8787 [controller setTabBarItem:item];
8788 [controllers addObject:controller];
8791 [tabbar_ setViewControllers:controllers];
8794 - (void) applicationDidFinishLaunching:(id)unused {
8798 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
8799 initWithMemoryCapacity:524288
8800 diskCapacity:10485760
8801 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
8804 [CYBrowserController _initialize];
8806 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8808 Font12_ = [[UIFont systemFontOfSize:12] retain];
8809 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8810 Font14_ = [[UIFont systemFontOfSize:14] retain];
8811 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8812 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8816 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8817 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8819 UIScreen *screen([UIScreen mainScreen]);
8821 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8822 [window_ orderFront:self];
8823 [window_ makeKey:self];
8824 [window_ setHidden:NO];
8827 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8828 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8829 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8830 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8831 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8832 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8833 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8834 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8835 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8838 [self addStashController];
8839 // XXX: this would be much cleaner as a yieldToSelector:
8840 // that way the removeStashController could happen right here inline
8841 // we also could no longer require the useless stash_ field anymore
8842 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8846 database_ = [Database sharedInstance];
8848 [self setupTabBarController];
8849 [tabbar_ setUpdateDelegate:self];
8850 [window_ addSubview:[tabbar_ view]];
8852 // Show pinstripes while loading data.
8853 [[tabbar_ view] setBackgroundColor:[UIColor pinStripeColor]];
8855 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8862 [self showSettings];
8866 [window_ setUserInteractionEnabled:NO];
8868 UIView *container = [[[UIView alloc] init] autorelease];
8869 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8871 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8872 [spinner startAnimating];
8873 [container addSubview:spinner];
8875 UILabel *label = [[[UILabel alloc] init] autorelease];
8876 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8877 [label setBackgroundColor:[UIColor clearColor]];
8878 [label setTextColor:[UIColor blackColor]];
8879 [label setShadowColor:[UIColor whiteColor]];
8880 [label setShadowOffset:CGSizeMake(0, 1)];
8881 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8882 [container addSubview:label];
8884 CGSize viewsize = [[tabbar_ view] frame].size;
8885 CGSize spinnersize = [spinner bounds].size;
8886 CGSize textsize = [[label text] sizeWithFont:[label font]];
8887 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8889 CGRect containrect = {
8890 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8891 CGSizeMake(bothwidth, spinnersize.height)
8894 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8902 [container setFrame:containrect];
8903 [spinner setFrame:spinrect];
8904 [label setFrame:textrect];
8905 [[tabbar_ view] addSubview:container];
8910 // Show the initial page
8911 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
8912 [tabbar_ setSelectedIndex:0];
8916 [starturl_ release];
8919 [window_ setUserInteractionEnabled:YES];
8921 // XXX: does this actually slow anything down?
8922 [[tabbar_ view] setBackgroundColor:[UIColor clearColor]];
8923 [container removeFromSuperview];
8926 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8927 if (item != nil && IsWildcat_) {
8928 [sheet showFromBarButtonItem:item animated:YES];
8930 [sheet showInView:window_];
8937 id Alloc_(id self, SEL selector) {
8938 id object = alloc_(self, selector);
8939 lprintf("[%s]A-%p\n", self->isa->name, object);
8944 id Dealloc_(id self, SEL selector) {
8945 id object = dealloc_(self, selector);
8946 lprintf("[%s]D-%p\n", self->isa->name, object);
8950 Class $WebDefaultUIKitDelegate;
8952 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8953 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8954 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8955 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8958 static NSNumber *shouldPlayKeyboardSounds;
8962 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8964 case 1104: // Keyboard Button Clicked
8965 case 1105: // Keyboard Delete Repeated
8966 if (shouldPlayKeyboardSounds == nil) {
8967 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8968 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8971 if (![shouldPlayKeyboardSounds boolValue])
8975 _UIHardware$_playSystemSound$(self, _cmd, sound);
8979 int main(int argc, char *argv[]) { _pooled
8982 if (Class $UIDevice = objc_getClass("UIDevice")) {
8983 UIDevice *device([$UIDevice currentDevice]);
8984 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8988 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8990 /* Library Hacks {{{ */
8991 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8993 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8994 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8995 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8996 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8997 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9000 $UIHardware = objc_getClass("UIHardware");
9001 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9002 if (UIHardware$_playSystemSound$ != NULL) {
9003 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9004 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9007 /* Set Locale {{{ */
9008 Locale_ = CFLocaleCopyCurrent();
9009 Languages_ = [NSLocale preferredLanguages];
9010 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9011 //NSLog(@"%@", [Languages_ description]);
9014 if (Languages_ == nil || [Languages_ count] == 0)
9015 // XXX: consider just setting to C and then falling through?
9018 lang = [[Languages_ objectAtIndex:0] UTF8String];
9019 setenv("LANG", lang, true);
9022 //std::setlocale(LC_ALL, lang);
9023 NSLog(@"Setting Language: %s", lang);
9026 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9028 /* Parse Arguments {{{ */
9029 bool substrate(false);
9035 for (int argi(1); argi != argc; ++argi)
9036 if (strcmp(argv[argi], "--") == 0) {
9038 argv[argi] = argv[0];
9044 for (int argi(1); argi != arge; ++argi)
9045 if (strcmp(args[argi], "--substrate") == 0)
9048 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9052 App_ = [[NSBundle mainBundle] bundlePath];
9053 Home_ = NSHomeDirectory();
9059 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9060 alloc_ = alloc->method_imp;
9061 alloc->method_imp = (IMP) &Alloc_;*/
9063 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9064 dealloc_ = dealloc->method_imp;
9065 dealloc->method_imp = (IMP) &Dealloc_;*/
9067 /* System Information {{{ */
9071 size = sizeof(maxproc);
9072 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9073 perror("sysctlbyname(\"kern.maxproc\", ?)");
9074 else if (maxproc < 64) {
9076 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9077 perror("sysctlbyname(\"kern.maxproc\", #)");
9080 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9081 char *osversion = new char[size];
9082 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9083 perror("sysctlbyname(\"kern.osversion\", ?)");
9085 System_ = [NSString stringWithUTF8String:osversion];
9087 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9088 char *machine = new char[size];
9089 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9090 perror("sysctlbyname(\"hw.machine\", ?)");
9094 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9095 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9096 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9097 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9101 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9102 NSData *data((NSData *) ecid);
9103 size_t length([data length]);
9104 uint8_t bytes[length];
9105 [data getBytes:bytes];
9106 char string[length * 2 + 1];
9107 for (size_t i(0); i != length; ++i)
9108 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9109 ChipID_ = [NSString stringWithUTF8String:string];
9113 IOObjectRelease(service);
9117 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9119 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9120 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9121 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9123 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9124 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9125 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9127 if (mcc != NULL && mnc != NULL)
9128 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9135 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9136 Build_ = [system objectForKey:@"ProductBuildVersion"];
9137 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9138 Product_ = [info objectForKey:@"SafariProductVersion"];
9139 Safari_ = [info objectForKey:@"CFBundleVersion"];
9142 /* Load Database {{{ */
9144 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9146 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9148 if (Metadata_ == NULL)
9149 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9151 Settings_ = [Metadata_ objectForKey:@"Settings"];
9153 Packages_ = [Metadata_ objectForKey:@"Packages"];
9154 Sections_ = [Metadata_ objectForKey:@"Sections"];
9155 Sources_ = [Metadata_ objectForKey:@"Sources"];
9157 Token_ = [Metadata_ objectForKey:@"Token"];
9160 if (Settings_ != nil)
9161 Role_ = [Settings_ objectForKey:@"Role"];
9163 if (Sections_ == nil) {
9164 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9165 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9168 if (Sources_ == nil) {
9169 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9170 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9175 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9178 if (Packages_ != nil) {
9179 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9181 [Metadata_ removeObjectForKey:@"Packages"];
9186 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9188 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9189 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9190 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9191 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9192 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9193 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9195 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9197 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9198 unlink("/tmp/.cydia.fw");
9200 } else if (access("/User", F_OK) != 0 || version < 2) {
9203 system("/usr/libexec/cydia/firmware.sh");
9207 _assert([[NSFileManager defaultManager]
9208 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9209 withIntermediateDirectories:YES
9214 if (access("/tmp/cydia.chk", F_OK) == 0) {
9215 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9216 _assert(errno == ENOENT);
9217 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9218 _assert(errno == ENOENT);
9221 /* APT Initialization {{{ */
9222 _assert(pkgInitConfig(*_config));
9223 _assert(pkgInitSystem(*_config, _system));
9226 _config->Set("APT::Acquire::Translation", lang);
9228 // XXX: this timeout might be important :(
9229 //_config->Set("Acquire::http::Timeout", 15);
9231 _config->Set("Acquire::http::MaxParallel", 3);
9233 /* Color Choices {{{ */
9234 space_ = CGColorSpaceCreateDeviceRGB();
9236 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9237 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9238 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9239 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9240 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9241 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9242 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9243 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9244 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9246 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9247 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9249 /* UIKit Configuration {{{ */
9250 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9251 if ($GSFontSetUseLegacyFontMetrics != NULL)
9252 $GSFontSetUseLegacyFontMetrics(YES);
9254 // XXX: I have a feeling this was important
9255 //UIKeyboardDisableAutomaticAppearance();
9258 Colon_ = UCLocalize("COLON_DELIMITED");
9259 Elision_ = UCLocalize("ELISION");
9260 Error_ = UCLocalize("ERROR");
9261 Warning_ = UCLocalize("WARNING");
9264 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9266 CGColorSpaceRelease(space_);