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"
125 #include "substrate.h"
132 #define _timestamp ({ \
134 gettimeofday(&tv, NULL); \
135 tv.tv_sec * 1000000 + tv.tv_usec; \
138 typedef std::vector<class ProfileTime *> TimeList;
148 ProfileTime(const char *name) :
152 times_.push_back(this);
155 void AddTime(uint64_t time) {
162 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
174 ProfileTimer(ProfileTime &time) :
181 time_.AddTime(_timestamp - start_);
186 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
188 std::cerr << "========" << std::endl;
191 #define _profile(name) { \
192 static ProfileTime name(#name); \
193 ProfileTimer _ ## name(name);
198 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
200 #define CYPoolStart() \
201 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
203 #define CYPoolEnd() \
207 // Hash Functions/Structures {{{
208 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
216 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
218 void NSLogPoint(const char *fix, const CGPoint &point) {
219 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
222 void NSLogRect(const char *fix, const CGRect &rect) {
223 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
226 static _finline NSString *CydiaURL(NSString *path) {
228 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
229 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
230 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
231 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
232 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
233 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
236 static _finline void UpdateExternalStatus(uint64_t newStatus) {
238 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
239 notify_set_state(notify_token, newStatus);
240 notify_cancel(notify_token);
242 notify_post("com.saurik.Cydia.status");
245 /* [NSObject yieldToSelector:(withObject:)] {{{*/
246 @interface NSObject (Cydia)
247 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
248 - (id) yieldToSelector:(SEL)selector;
251 @implementation NSObject (Cydia)
256 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
257 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
258 id object([[context objectAtIndex:1] nonretainedObjectValue]);
259 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
261 /* XXX: deal with exceptions */
262 id value([self performSelector:selector withObject:object]);
264 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
265 [context removeAllObjects];
266 if ([signature methodReturnLength] != 0 && value != nil)
267 [context addObject:value];
272 performSelectorOnMainThread:@selector(doNothing)
278 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
279 volatile bool stopped(false);
281 NSMutableArray *context([NSMutableArray arrayWithObjects:
282 [NSValue valueWithPointer:selector],
283 [NSValue valueWithNonretainedObject:object],
284 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
287 NSThread *thread([[[NSThread alloc]
289 selector:@selector(_yieldToContext:)
295 NSRunLoop *loop([NSRunLoop currentRunLoop]);
296 NSDate *future([NSDate distantFuture]);
298 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
300 return [context count] == 0 ? nil : [context objectAtIndex:0];
303 - (id) yieldToSelector:(SEL)selector {
304 return [self yieldToSelector:selector withObject:nil];
310 /* Cydia Action Sheet {{{ */
311 @interface CYActionSheet : UIAlertView {
315 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
318 @implementation CYActionSheet
320 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
321 if ((self = [super init])) {
322 [self setTitle:title];
323 [self setDelegate:self];
324 for (NSString *button in buttons) [self addButtonWithTitle:button];
325 [self setCancelButtonIndex:index];
329 - (void) _updateFrameForDisplay {
330 [super _updateFrameForDisplay];
331 if ([self cancelButtonIndex] == -1) {
332 NSArray *buttons = [self buttons];
333 if ([buttons count]) {
334 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
335 for (UIThreePartButton *button in buttons)
336 [button setBackground:background forState:0];
341 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
342 button_ = buttonIndex + 1;
346 [self dismissWithClickedButtonIndex:-1 animated:YES];
349 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
350 [self setRunsModal:YES];
359 /* NSForcedOrderingSearch doesn't work on the iPhone */
360 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
361 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
362 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
364 /* Information Dictionaries {{{ */
365 @interface NSMutableArray (Cydia)
366 - (void) addInfoDictionary:(NSDictionary *)info;
369 @implementation NSMutableArray (Cydia)
371 - (void) addInfoDictionary:(NSDictionary *)info {
372 [self addObject:info];
377 @interface NSMutableDictionary (Cydia)
378 - (void) addInfoDictionary:(NSDictionary *)info;
381 @implementation NSMutableDictionary (Cydia)
383 - (void) addInfoDictionary:(NSDictionary *)info {
384 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
390 #define lprintf(args...) fprintf(stderr, args)
393 #define TraceLogging (1 && !ForRelease)
394 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
395 #define ProfileTimes (0 && !ForRelease)
396 #define ForSaurik (0 && !ForRelease)
397 #define LogBrowser (0 && !ForRelease)
398 #define TrackResize (0 && !ForRelease)
399 #define ManualRefresh (1 && !ForRelease)
400 #define ShowInternals (0 && !ForRelease)
401 #define IgnoreInstall (0 && !ForRelease)
402 #define AlwaysReload (0 && !ForRelease)
406 #define _trace(args...)
411 #define _profile(name) {
414 #define PrintTimes() do {} while (false)
418 typedef uint32_t (*SKRadixFunction)(id, void *);
420 @interface NSMutableArray (Radix)
421 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
429 @implementation NSMutableArray (Radix)
431 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
432 size_t count([self count]);
433 struct RadixItem_ *swap(new RadixItem_[count * 2]);
435 for (size_t i(0); i != count; ++i) {
436 RadixItem_ &item(swap[i]);
439 id object([self objectAtIndex:i]);
440 item.key = function(object, argument);
443 struct RadixItem_ *lhs(swap), *rhs(swap + count);
445 static const size_t width = 32;
446 static const size_t bits = 11;
447 static const size_t slots = 1 << bits;
448 static const size_t passes = (width + (bits - 1)) / bits;
450 size_t *hist(new size_t[slots]);
452 for (size_t pass(0); pass != passes; ++pass) {
453 memset(hist, 0, sizeof(size_t) * slots);
455 for (size_t i(0); i != count; ++i) {
456 uint32_t key(lhs[i].key);
458 key &= _not(uint32_t) >> width - bits;
463 for (size_t i(0); i != slots; ++i) {
464 size_t local(offset);
469 for (size_t i(0); i != count; ++i) {
470 uint32_t key(lhs[i].key);
472 key &= _not(uint32_t) >> width - bits;
473 rhs[hist[key]++] = lhs[i];
476 RadixItem_ *tmp(lhs);
483 const void **values(new const void *[count]);
484 for (size_t i(0); i != count; ++i)
485 values[i] = [self objectAtIndex:lhs[i].index];
486 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
494 /* Insertion Sort {{{ */
496 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
497 const char *ptr = (const char *)list;
499 CFIndex half = count / 2;
500 const char *probe = ptr + elementSize * half;
501 CFComparisonResult cr = comparator(element, probe, context);
502 if (0 == cr) return (probe - (const char *)list) / elementSize;
503 ptr = (cr < 0) ? ptr : probe + elementSize;
504 count = (cr < 0) ? half : (half + (count & 1) - 1);
506 return (ptr - (const char *)list) / elementSize;
509 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
510 const char *ptr = (const char *)list;
512 CFIndex half = count / 2;
513 const char *probe = ptr + elementSize * half;
514 CFComparisonResult cr = comparator(element, probe, context);
515 if (0 == cr) return (probe - (const char *)list) / elementSize;
516 ptr = (cr < 0) ? ptr : probe + elementSize;
517 count = (cr < 0) ? half : (half + (count & 1) - 1);
519 return (ptr - (const char *)list) / elementSize;
522 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
523 if (range.length == 0)
525 const void **values(new const void *[range.length]);
526 CFArrayGetValues(array, range, values);
528 #if HistogramInsertionSort > 0
529 uint32_t total(0), *offsets(new uint32_t[range.length]);
532 for (CFIndex index(1); index != range.length; ++index) {
533 const void *value(values[index]);
534 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
535 CFIndex correct(index);
536 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
537 #if HistogramInsertionSort > 1
538 NSLog(@"%@ < %@", value, values[correct - 1]);
543 if (correct != index) {
544 size_t offset(index - correct);
545 #if HistogramInsertionSort
549 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
551 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
552 values[correct] = value;
556 CFArrayReplaceValues(array, range, values, range.length);
559 #if HistogramInsertionSort > 0
560 for (CFIndex index(0); index != range.length; ++index)
561 if (offsets[index] != 0)
562 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
563 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
570 /* Apple Bug Fixes {{{ */
571 @implementation UIWebDocumentView (Cydia)
573 - (void) _setScrollerOffset:(CGPoint)offset {
574 UIScroller *scroller([self _scroller]);
576 CGSize size([scroller contentSize]);
577 CGSize bounds([scroller bounds].size);
580 max.x = size.width - bounds.width;
581 max.y = size.height - bounds.height;
589 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
590 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
592 [scroller setOffset:offset];
598 @implementation WebScriptObject (NSFastEnumeration)
600 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
601 size_t length([self count] - state->state);
604 else if (length > count)
606 for (size_t i(0); i != length; ++i)
607 objects[i] = [self objectAtIndex:state->state++];
608 state->itemsPtr = objects;
609 state->mutationsPtr = (unsigned long *) self;
615 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
616 size_t length([self length] - state->state);
619 else if (length > count)
621 for (size_t i(0); i != length; ++i)
622 objects[i] = [self item:state->state++];
623 state->itemsPtr = objects;
624 state->mutationsPtr = (unsigned long *) self;
628 /* Cydia NSString Additions {{{ */
629 @interface NSString (Cydia)
630 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
631 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
632 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
633 - (NSComparisonResult) compareByPath:(NSString *)other;
634 - (NSString *) stringByCachingURLWithCurrentCDN;
635 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
638 @implementation NSString (Cydia)
640 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
641 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
644 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
645 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
646 memcpy(data, bytes, length);
647 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
650 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
651 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
654 - (NSComparisonResult) compareByPath:(NSString *)other {
655 NSString *prefix = [self commonPrefixWithString:other options:0];
656 size_t length = [prefix length];
658 NSRange lrange = NSMakeRange(length, [self length] - length);
659 NSRange rrange = NSMakeRange(length, [other length] - length);
661 lrange = [self rangeOfString:@"/" options:0 range:lrange];
662 rrange = [other rangeOfString:@"/" options:0 range:rrange];
664 NSComparisonResult value;
666 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
667 value = NSOrderedSame;
668 else if (lrange.location == NSNotFound)
669 value = NSOrderedAscending;
670 else if (rrange.location == NSNotFound)
671 value = NSOrderedDescending;
673 value = NSOrderedSame;
675 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
676 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
677 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
678 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
680 NSComparisonResult result = [lpath compare:rpath];
681 return result == NSOrderedSame ? value : result;
684 - (NSString *) stringByCachingURLWithCurrentCDN {
686 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
687 withString:@"://cache.cydia.saurik.com/"
691 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
692 return [(id)CFURLCreateStringByAddingPercentEscapes(
697 kCFStringEncodingUTF8
704 /* C++ NSString Wrapper Cache {{{ */
705 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
706 return size == 0 ? NULL :
707 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
708 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
711 static _finline CFStringRef CYStringCreate(const char *data) {
712 return CYStringCreate(data, strlen(data));
721 _finline void clear_() {
722 if (cache_ != NULL) {
729 _finline bool empty() const {
733 _finline size_t size() const {
737 _finline char *data() const {
741 _finline void clear() {
746 _finline CYString() :
753 _finline ~CYString() {
757 void operator =(const CYString &rhs) {
761 if (rhs.cache_ == nil)
764 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
767 void copy(apr_pool_t *pool) {
768 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
769 memcpy(temp, data_, size_);
774 void set(apr_pool_t *pool, const char *data, size_t size) {
780 data_ = const_cast<char *>(data);
788 _finline void set(apr_pool_t *pool, const char *data) {
789 set(pool, data, data == NULL ? 0 : strlen(data));
792 _finline void set(apr_pool_t *pool, const std::string &rhs) {
793 set(pool, rhs.data(), rhs.size());
796 bool operator ==(const CYString &rhs) const {
797 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
800 _finline operator CFStringRef() {
802 cache_ = CYStringCreate(data_, size_);
806 _finline operator id() {
807 return (NSString *) static_cast<CFStringRef>(*this);
810 _finline operator const char *() {
811 return reinterpret_cast<const char *>(data_);
815 /* C++ NSString Algorithm Adapters {{{ */
817 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
820 struct NSStringMapHash :
821 std::unary_function<NSString *, size_t>
823 _finline size_t operator ()(NSString *value) const {
824 return CFStringHashNSString((CFStringRef) value);
828 struct NSStringMapLess :
829 std::binary_function<NSString *, NSString *, bool>
831 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
832 return [lhs compare:rhs] == NSOrderedAscending;
836 struct NSStringMapEqual :
837 std::binary_function<NSString *, NSString *, bool>
839 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
840 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
841 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
842 //[lhs isEqualToString:rhs];
847 /* Perl-Compatible RegEx {{{ */
857 Pcre(const char *regex) :
862 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
865 lprintf("%d:%s\n", offset, error);
869 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
870 matches_ = new int[(capture_ + 1) * 3];
878 NSString *operator [](size_t match) {
879 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
882 bool operator ()(NSString *data) {
883 // XXX: length is for characters, not for bytes
884 return operator ()([data UTF8String], [data length]);
887 bool operator ()(const char *data, size_t size) {
889 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
893 /* Mime Addresses {{{ */
894 @interface Address : NSObject {
900 - (NSString *) address;
902 - (void) setAddress:(NSString *)address;
904 + (Address *) addressWithString:(NSString *)string;
905 - (Address *) initWithString:(NSString *)string;
908 @implementation Address
917 - (NSString *) name {
921 - (NSString *) address {
925 - (void) setAddress:(NSString *)address {
927 [address_ autorelease];
931 address_ = [address retain];
934 + (Address *) addressWithString:(NSString *)string {
935 return [[[Address alloc] initWithString:string] autorelease];
938 + (NSArray *) _attributeKeys {
939 return [NSArray arrayWithObjects:@"address", @"name", nil];
942 - (NSArray *) attributeKeys {
943 return [[self class] _attributeKeys];
946 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
947 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
950 - (Address *) initWithString:(NSString *)string {
951 if ((self = [super init]) != nil) {
952 const char *data = [string UTF8String];
953 size_t size = [string length];
955 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
957 if (address_r(data, size)) {
958 name_ = [address_r[1] retain];
959 address_ = [address_r[2] retain];
961 name_ = [string retain];
969 /* CoreGraphics Primitives {{{ */
974 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
975 CGFloat color[] = {red, green, blue, alpha};
976 return CGColorCreate(space, color);
985 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
986 color_(Create_(space, red, green, blue, alpha))
988 Set(space, red, green, blue, alpha);
993 CGColorRelease(color_);
1000 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1002 color_ = Create_(space, red, green, blue, alpha);
1005 operator CGColorRef() {
1011 /* Random Global Variables {{{ */
1012 static const int PulseInterval_ = 50000;
1013 static const int ButtonBarWidth_ = 60;
1014 static const int ButtonBarHeight_ = 48;
1015 static const float KeyboardTime_ = 0.3f;
1018 static NSArray *Finishes_;
1020 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1021 #define NotifyConfig_ "/etc/notify.conf"
1023 static bool Queuing_;
1025 static CYColor Blue_;
1026 static CYColor Blueish_;
1027 static CYColor Black_;
1028 static CYColor Off_;
1029 static CYColor White_;
1030 static CYColor Gray_;
1031 static CYColor Green_;
1032 static CYColor Purple_;
1033 static CYColor Purplish_;
1035 static UIColor *InstallingColor_;
1036 static UIColor *RemovingColor_;
1038 static NSString *App_;
1039 static NSString *Home_;
1041 static BOOL Advanced_;
1042 static BOOL Ignored_;
1044 static UIFont *Font12_;
1045 static UIFont *Font12Bold_;
1046 static UIFont *Font14_;
1047 static UIFont *Font18Bold_;
1048 static UIFont *Font22Bold_;
1050 static const char *Machine_ = NULL;
1051 static NSString *System_ = nil;
1052 static NSString *SerialNumber_ = nil;
1053 static NSString *ChipID_ = nil;
1054 static NSString *Token_ = nil;
1055 static NSString *UniqueID_ = nil;
1056 static NSString *PLMN_ = nil;
1057 static NSString *Build_ = nil;
1058 static NSString *Product_ = nil;
1059 static NSString *Safari_ = nil;
1061 static CFLocaleRef Locale_;
1062 static NSArray *Languages_;
1063 static CGColorSpaceRef space_;
1065 static NSDictionary *SectionMap_;
1066 static NSMutableDictionary *Metadata_;
1067 static _transient NSMutableDictionary *Settings_;
1068 static _transient NSString *Role_;
1069 static _transient NSMutableDictionary *Packages_;
1070 static _transient NSMutableDictionary *Sections_;
1071 static _transient NSMutableDictionary *Sources_;
1072 static bool Changed_;
1075 static bool IsWildcat_;
1078 /* Display Helpers {{{ */
1079 inline float Interpolate(float begin, float end, float fraction) {
1080 return (end - begin) * fraction + begin;
1083 /* XXX: localize this! */
1084 NSString *SizeString(double size) {
1085 bool negative = size < 0;
1090 while (size > 1024) {
1095 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1097 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1100 static _finline const char *StripVersion_(const char *version) {
1101 const char *colon(strchr(version, ':'));
1102 return colon == NULL ? version : colon + 1;
1105 NSString *LocalizeSection(NSString *section) {
1106 static Pcre title_r("^(.*?) \\((.*)\\)$");
1107 if (title_r(section)) {
1108 NSString *parent(title_r[1]);
1109 NSString *child(title_r[2]);
1111 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1112 LocalizeSection(parent),
1113 LocalizeSection(child)
1117 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1120 NSString *Simplify(NSString *title) {
1121 const char *data = [title UTF8String];
1122 size_t size = [title length];
1124 static Pcre square_r("^\\[(.*)\\]$");
1125 if (square_r(data, size))
1126 return Simplify(square_r[1]);
1128 static Pcre paren_r("^\\((.*)\\)$");
1129 if (paren_r(data, size))
1130 return Simplify(paren_r[1]);
1132 static Pcre title_r("^(.*?) \\((.*)\\)$");
1133 if (title_r(data, size))
1134 return Simplify(title_r[1]);
1140 NSString *GetLastUpdate() {
1141 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1144 return UCLocalize("NEVER_OR_UNKNOWN");
1146 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1147 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1149 CFRelease(formatter);
1151 return [(NSString *) formatted autorelease];
1154 bool isSectionVisible(NSString *section) {
1155 NSDictionary *metadata([Sections_ objectForKey:section]);
1156 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1157 return hidden == nil || ![hidden boolValue];
1162 /* Delegate Prototypes {{{ */
1166 @interface NSObject (ProgressDelegate)
1169 @protocol ProgressDelegate
1170 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1171 - (void) setProgressTitle:(NSString *)title;
1172 - (void) setProgressPercent:(float)percent;
1173 - (void) startProgress;
1174 - (void) addProgressOutput:(NSString *)output;
1175 - (bool) isCancelling:(size_t)received;
1178 @protocol ConfigurationDelegate
1179 - (void) repairWithSelector:(SEL)selector;
1180 - (void) setConfigurationData:(NSString *)data;
1183 @class PackageController;
1185 @protocol CydiaDelegate
1186 - (void) setPackageController:(PackageController *)view;
1187 - (void) clearPackage:(Package *)package;
1188 - (void) installPackage:(Package *)package;
1189 - (void) installPackages:(NSArray *)packages;
1190 - (void) removePackage:(Package *)package;
1191 - (void) beginUpdate;
1193 - (void) distUpgrade;
1195 - (void) updateData;
1197 - (void) showSettings;
1198 - (UIProgressHUD *) addProgressHUD;
1199 - (BOOL) hudIsShowing;
1200 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1201 - (CYViewController *) pageForPackage:(NSString *)name;
1202 - (PackageController *) packageController;
1203 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1207 /* Status Delegation {{{ */
1209 public pkgAcquireStatus
1212 _transient NSObject<ProgressDelegate> *delegate_;
1220 void setDelegate(id delegate) {
1221 delegate_ = delegate;
1224 NSObject<ProgressDelegate> *getDelegate() const {
1228 virtual bool MediaChange(std::string media, std::string drive) {
1232 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1235 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1236 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1237 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1240 virtual void Done(pkgAcquire::ItemDesc &item) {
1243 virtual void Fail(pkgAcquire::ItemDesc &item) {
1245 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1246 item.Owner->Status == pkgAcquire::Item::StatDone
1250 std::string &error(item.Owner->ErrorText);
1254 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1255 NSArray *fields([description componentsSeparatedByString:@" "]);
1256 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1258 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1259 withObject:[NSArray arrayWithObjects:
1260 [NSString stringWithUTF8String:error.c_str()],
1267 virtual bool Pulse(pkgAcquire *Owner) {
1268 bool value = pkgAcquireStatus::Pulse(Owner);
1271 double(CurrentBytes + CurrentItems) /
1272 double(TotalBytes + TotalItems)
1275 [delegate_ setProgressPercent:percent];
1276 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1279 virtual void Start() {
1280 [delegate_ startProgress];
1283 virtual void Stop() {
1287 /* Progress Delegation {{{ */
1292 _transient id<ProgressDelegate> delegate_;
1296 virtual void Update() {
1297 /*if (abs(Percent - percent_) > 2)
1298 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1302 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1303 [delegate_ setProgressPercent:(Percent / 100)];*/
1313 void setDelegate(id delegate) {
1314 delegate_ = delegate;
1317 id getDelegate() const {
1321 virtual void Done() {
1323 //[delegate_ setProgressPercent:1];
1328 /* Database Interface {{{ */
1329 typedef std::map< unsigned long, _H<Source> > SourceMap;
1331 @interface Database : NSObject {
1337 pkgCacheFile cache_;
1338 pkgDepCache::Policy *policy_;
1339 pkgRecords *records_;
1340 pkgProblemResolver *resolver_;
1341 pkgAcquire *fetcher_;
1343 SPtr<pkgPackageManager> manager_;
1344 pkgSourceList *list_;
1347 CFMutableArrayRef packages_;
1349 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1358 + (Database *) sharedInstance;
1361 - (void) _readCydia:(NSNumber *)fd;
1362 - (void) _readStatus:(NSNumber *)fd;
1363 - (void) _readOutput:(NSNumber *)fd;
1367 - (Package *) packageWithName:(NSString *)name;
1369 - (pkgCacheFile &) cache;
1370 - (pkgDepCache::Policy *) policy;
1371 - (pkgRecords *) records;
1372 - (pkgProblemResolver *) resolver;
1373 - (pkgAcquire &) fetcher;
1374 - (pkgSourceList &) list;
1375 - (NSArray *) packages;
1376 - (NSArray *) sources;
1377 - (void) reloadData;
1385 - (void) updateWithStatus:(Status &)status;
1387 - (void) setDelegate:(id)delegate;
1388 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1391 /* Delegate Helpers {{{ */
1392 @implementation NSObject (ProgressDelegate)
1394 - (void) _setProgressErrorPackage:(NSArray *)args {
1395 [self performSelector:@selector(setProgressError:forPackage:)
1396 withObject:[args objectAtIndex:0]
1397 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1401 - (void) _setProgressErrorTitle:(NSArray *)args {
1402 [self performSelector:@selector(setProgressError:withTitle:)
1403 withObject:[args objectAtIndex:0]
1404 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1408 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1409 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1410 withObject:[NSArray arrayWithObjects:error, title, nil]
1415 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1416 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1418 [self performSelector:@selector(setProgressError:withTitle:)
1420 withObject:(package == nil ? id : [package name])
1427 // Cytore Definitions {{{
1428 struct PackageValue :
1431 Cytore::Offset<PackageValue> next_;
1433 uint32_t index_ : 23;
1434 uint32_t subscribed_ : 1;
1450 Cytore::Offset<PackageValue> packages_[1 << 16];
1453 static Cytore::File<MetaValue> MetaFile_;
1455 // Cytore Helper Functions {{{
1456 static PackageValue *PackageFind(const char *name, size_t length) {
1457 SplitHash nhash = { hashlittle(name, length) };
1459 PackageValue *metadata;
1461 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1462 offset: if (offset->IsNull()) {
1463 *offset = MetaFile_.New<PackageValue>(length + 1);
1464 metadata = &MetaFile_.Get(*offset);
1466 memcpy(metadata->name_, name, length + 1);
1467 metadata->nhash_ = nhash.u16[1];
1469 metadata = &MetaFile_.Get(*offset);
1471 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1472 offset = &metadata->next_;
1480 static void PackageImport(const void *key, const void *value, void *context) {
1482 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1483 NSLog(@"failed to import package %@", key);
1487 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1488 NSDictionary *package((NSDictionary *) value);
1490 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1491 if ([subscribed boolValue])
1492 metadata->subscribed_ = true;
1494 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1495 time_t time([date timeIntervalSince1970]);
1496 if (metadata->first_ > time || metadata->first_ == 0)
1497 metadata->first_ = time;
1500 if (NSDate *date = [package objectForKey:@"LastSeen"]) {
1501 time_t time([date timeIntervalSince1970]);
1502 if (metadata->last_ < time || metadata->last_ == 0) {
1503 metadata->last_ = time;
1506 } else if (metadata->last_ == 0) last: {
1507 NSString *version([package objectForKey:@"LastVersion"]);
1508 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1509 size_t length(strlen(buffer));
1510 uint16_t vhash(hashlittle(buffer, length));
1512 size_t capped(std::min<size_t>(8, length));
1513 char *latest(buffer + length - capped);
1515 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1516 metadata->vhash_ = vhash;
1522 /* Source Class {{{ */
1523 @interface Source : NSObject {
1524 CYString depiction_;
1525 CYString description_;
1531 CYString distribution_;
1536 NSString *authority_;
1538 CYString defaultIcon_;
1540 NSDictionary *record_;
1544 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1546 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1548 - (NSString *) depictionForPackage:(NSString *)package;
1549 - (NSString *) supportForPackage:(NSString *)package;
1551 - (NSDictionary *) record;
1555 - (NSString *) distribution;
1556 - (NSString *) type;
1558 - (NSString *) host;
1560 - (NSString *) name;
1561 - (NSString *) description;
1562 - (NSString *) label;
1563 - (NSString *) origin;
1564 - (NSString *) version;
1566 - (NSString *) defaultIcon;
1570 @implementation Source
1574 distribution_.clear();
1577 description_.clear();
1583 defaultIcon_.clear();
1585 if (record_ != nil) {
1595 if (authority_ != nil) {
1596 [authority_ release];
1602 // XXX: this is a very inefficient way to call these deconstructors
1607 + (NSArray *) _attributeKeys {
1608 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1611 - (NSArray *) attributeKeys {
1612 return [[self class] _attributeKeys];
1615 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1616 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1619 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1622 trusted_ = index->IsTrusted();
1624 uri_.set(pool, index->GetURI());
1625 distribution_.set(pool, index->GetDist());
1626 type_.set(pool, index->GetType());
1628 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1629 if (dindex != NULL) {
1631 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1634 pkgTagFile tags(&fd);
1636 pkgTagSection section;
1643 {"default-icon", &defaultIcon_},
1644 {"depiction", &depiction_},
1645 {"description", &description_},
1647 {"origin", &origin_},
1648 {"support", &support_},
1649 {"version", &version_},
1652 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1653 const char *start, *end;
1655 if (section.Find(names[i].name_, start, end)) {
1656 CYString &value(*names[i].value_);
1657 value.set(pool, start, end - start);
1663 record_ = [Sources_ objectForKey:[self key]];
1665 record_ = [record_ retain];
1667 NSURL *url([NSURL URLWithString:uri_]);
1671 host_ = [[host_ lowercaseString] retain];
1676 authority_ = [url path];
1678 if (authority_ != nil)
1679 authority_ = [authority_ retain];
1682 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1683 if ((self = [super init]) != nil) {
1684 [self setMetaIndex:index inPool:pool];
1688 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1689 NSDictionary *lhr = [self record];
1690 NSDictionary *rhr = [source record];
1693 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1695 NSString *lhs = [self name];
1696 NSString *rhs = [source name];
1698 if ([lhs length] != 0 && [rhs length] != 0) {
1699 unichar lhc = [lhs characterAtIndex:0];
1700 unichar rhc = [rhs characterAtIndex:0];
1702 if (isalpha(lhc) && !isalpha(rhc))
1703 return NSOrderedAscending;
1704 else if (!isalpha(lhc) && isalpha(rhc))
1705 return NSOrderedDescending;
1708 return [lhs compare:rhs options:LaxCompareOptions_];
1711 - (NSString *) depictionForPackage:(NSString *)package {
1712 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1715 - (NSString *) supportForPackage:(NSString *)package {
1716 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1719 - (NSDictionary *) record {
1727 - (NSString *) uri {
1731 - (NSString *) distribution {
1732 return distribution_;
1735 - (NSString *) type {
1739 - (NSString *) key {
1740 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1743 - (NSString *) host {
1747 - (NSString *) name {
1748 return origin_.empty() ? authority_ : origin_;
1751 - (NSString *) description {
1752 return description_;
1755 - (NSString *) label {
1756 return label_.empty() ? authority_ : label_;
1759 - (NSString *) origin {
1763 - (NSString *) version {
1767 - (NSString *) defaultIcon {
1768 return defaultIcon_;
1773 /* Relationship Class {{{ */
1774 @interface Relationship : NSObject {
1779 - (NSString *) type;
1781 - (NSString *) name;
1785 @implementation Relationship
1793 - (NSString *) type {
1801 - (NSString *) name {
1808 /* Package Class {{{ */
1809 struct ParsedPackage {
1814 CYString depiction_;
1824 @interface Package : NSObject {
1826 uint32_t essential_ : 1;
1827 uint32_t obsolete_ : 1;
1828 uint32_t ignored_ : 1;
1832 _transient Database *database_;
1834 pkgCache::VerIterator version_;
1835 pkgCache::PkgIterator iterator_;
1836 pkgCache::VerFileIterator file_;
1842 CYString installed_;
1845 _transient NSString *section$_;
1849 PackageValue *metadata_;
1850 ParsedPackage *parsed_;
1852 NSMutableArray *tags_;
1856 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1857 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1859 - (pkgCache::PkgIterator) iterator;
1862 - (NSString *) section;
1863 - (NSString *) simpleSection;
1865 - (NSString *) longSection;
1866 - (NSString *) shortSection;
1870 - (Address *) maintainer;
1872 - (NSString *) longDescription;
1873 - (NSString *) shortDescription;
1876 - (PackageValue *) metadata;
1879 - (bool) subscribed;
1880 - (bool) setSubscribed:(bool)subscribed;
1884 - (NSString *) latest;
1885 - (NSString *) installed;
1886 - (BOOL) uninstalled;
1889 - (BOOL) upgradableAndEssential:(BOOL)essential;
1892 - (BOOL) unfiltered;
1896 - (BOOL) halfConfigured;
1897 - (BOOL) halfInstalled;
1899 - (NSString *) mode;
1902 - (NSString *) name;
1904 - (NSString *) homepage;
1905 - (NSString *) depiction;
1906 - (Address *) author;
1908 - (NSString *) support;
1910 - (NSArray *) files;
1911 - (NSArray *) warnings;
1912 - (NSArray *) applications;
1914 - (Source *) source;
1915 - (NSString *) role;
1917 - (BOOL) matches:(NSString *)text;
1919 - (bool) hasSupportingRole;
1920 - (BOOL) hasTag:(NSString *)tag;
1921 - (NSString *) primaryPurpose;
1922 - (NSArray *) purposes;
1923 - (bool) isCommercial;
1925 - (void) setIndex:(size_t)index;
1927 - (CYString &) cyname;
1929 - (uint32_t) compareBySection:(NSArray *)sections;
1934 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1935 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1936 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1937 - (bool) isVisibleInSection:(NSString *)section;
1938 - (bool) isVisibleInSource:(Source *)source;
1942 uint32_t PackageChangesRadix(Package *self, void *) {
1947 uint32_t timestamp : 30;
1948 uint32_t ignored : 1;
1949 uint32_t upgradable : 1;
1953 bool upgradable([self upgradableAndEssential:YES]);
1954 value.bits.upgradable = upgradable ? 1 : 0;
1957 value.bits.timestamp = 0;
1958 value.bits.ignored = [self ignored] ? 0 : 1;
1959 value.bits.upgradable = 1;
1961 value.bits.timestamp = [self seen] >> 2;
1962 value.bits.ignored = 0;
1963 value.bits.upgradable = 0;
1966 return _not(uint32_t) - value.key;
1969 uint32_t PackagePrefixRadix(Package *self, void *context) {
1970 size_t offset(reinterpret_cast<size_t>(context));
1971 CYString &name([self cyname]);
1973 size_t size(name.size());
1976 char *text(name.data());
1979 if (!isdigit(text[0]))
1983 while (size != digits && isdigit(text[digits]))
1991 if (offset == 0 && zeros != 0) {
1992 memset(data, '0', zeros);
1993 memcpy(data + zeros, text, 4 - zeros);
1995 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1996 if (size <= offset - zeros)
1999 text += offset - zeros;
2000 size -= offset - zeros;
2003 memcpy(data, text, 4);
2005 memcpy(data, text, size);
2006 memset(data + size, 0, 4 - size);
2009 for (size_t i(0); i != 4; ++i)
2010 if (isalpha(data[i]))
2018 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2020 /* XXX: ntohl may be more honest */
2021 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2024 CYString &(*PackageName)(Package *self, SEL sel);
2026 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2027 _profile(PackageNameCompare)
2028 CYString &lhi(PackageName(lhs, @selector(cyname)));
2029 CYString &rhi(PackageName(rhs, @selector(cyname)));
2030 CFStringRef lhn(lhi), rhn(rhi);
2033 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2034 else if (rhn == NULL)
2035 return NSOrderedDescending;
2037 _profile(PackageNameCompare$NumbersLast)
2038 if (!lhi.empty() && !rhi.empty()) {
2039 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2040 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2041 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2042 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2043 return lha ? NSOrderedAscending : NSOrderedDescending;
2047 CFIndex length = CFStringGetLength(lhn);
2049 _profile(PackageNameCompare$Compare)
2050 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2055 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2056 return PackageNameCompare(*lhs, *rhs, context);
2059 struct PackageNameOrdering :
2060 std::binary_function<Package *, Package *, bool>
2062 _finline bool operator ()(Package *lhs, Package *rhs) const {
2063 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2067 @implementation Package
2069 - (NSString *) description {
2070 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2074 if (parsed_ != NULL)
2088 + (NSString *) webScriptNameForSelector:(SEL)selector {
2089 if (selector == @selector(hasTag:))
2095 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2096 return [self webScriptNameForSelector:selector] == nil;
2099 + (NSArray *) _attributeKeys {
2100 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];
2103 - (NSArray *) attributeKeys {
2104 return [[self class] _attributeKeys];
2107 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2108 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2112 if (parsed_ != NULL)
2114 @synchronized (database_) {
2115 if ([database_ era] != era_ || file_.end())
2118 ParsedPackage *parsed(new ParsedPackage);
2121 _profile(Package$parse)
2122 pkgRecords::Parser *parser;
2124 _profile(Package$parse$Lookup)
2125 parser = &[database_ records]->Lookup(file_);
2130 _profile(Package$parse$Find)
2135 {"icon", &parsed->icon_},
2136 {"depiction", &parsed->depiction_},
2137 {"homepage", &parsed->homepage_},
2138 {"website", &website},
2139 {"bugs", &parsed->bugs_},
2140 {"support", &parsed->support_},
2141 {"sponsor", &parsed->sponsor_},
2142 {"author", &parsed->author_},
2145 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2146 const char *start, *end;
2148 if (parser->Find(names[i].name_, start, end)) {
2149 CYString &value(*names[i].value_);
2150 _profile(Package$parse$Value)
2151 value.set(pool_, start, end - start);
2157 _profile(Package$parse$Tagline)
2158 const char *start, *end;
2159 if (parser->ShortDesc(start, end)) {
2160 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2163 while (stop != start && stop[-1] == '\r')
2165 parsed->tagline_.set(pool_, start, stop - start);
2169 _profile(Package$parse$Retain)
2170 if (parsed->homepage_.empty())
2171 parsed->homepage_ = website;
2172 if (parsed->homepage_ == parsed->depiction_)
2173 parsed->homepage_.clear();
2178 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2179 if ((self = [super init]) != nil) {
2180 _profile(Package$initWithVersion)
2183 database_ = database;
2184 era_ = [database era];
2188 pkgCache::PkgIterator iterator(version.ParentPkg());
2189 iterator_ = iterator;
2191 _profile(Package$initWithVersion$Version)
2192 if (!version_.end())
2193 file_ = version_.FileList();
2195 pkgCache &cache([database_ cache]);
2196 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2200 _profile(Package$initWithVersion$Cache)
2201 id_.set(NULL, iterator.Name());
2202 name_.set(NULL, iterator.Display());
2204 latest_.set(NULL, StripVersion_(version_.VerStr()));
2206 pkgCache::VerIterator current(iterator.CurrentVer());
2208 installed_.set(NULL, StripVersion_(current.VerStr()));
2211 _profile(Package$initWithVersion$Lower)
2212 // XXX: do not use tolower() as this is not locale-specific? :(
2213 char *data(id_.data());
2214 for (size_t i(0), e(id_.size()); i != e; ++i)
2215 if ((data[i] & 0x20) == 0) {
2224 _profile(Package$initWithVersion$Tags)
2225 pkgCache::TagIterator tag(iterator.TagList());
2227 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2229 const char *name(tag.Name());
2230 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2232 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2233 role_ = (NSString *) CYStringCreate(name + 6);
2235 if (strncmp(name, "cydia::", 7) == 0) {
2236 if (strcmp(name + 7, "essential") == 0)
2238 else if (strcmp(name + 7, "obsolete") == 0)
2243 } while (!tag.end());
2247 _profile(Package$initWithVersion$Metadata)
2248 PackageValue *metadata(PackageFind(id_.data(), id_.size()));
2249 metadata_ = metadata;
2251 const char *latest(version_.VerStr());
2252 size_t length(strlen(latest));
2254 uint16_t vhash(hashlittle(latest, length));
2256 size_t capped(std::min<size_t>(8, length));
2257 latest = latest + length - capped;
2259 if (metadata->first_ == 0)
2260 metadata->first_ = now_;
2262 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2263 metadata->last_ = now_;
2264 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2265 metadata->vhash_ = vhash;
2266 } else if (metadata->last_ == 0)
2267 metadata->last_ = metadata->first_;
2270 _profile(Package$initWithVersion$Section)
2271 section_.set(NULL, iterator.Section());
2274 _profile(Package$initWithVersion$Flags)
2275 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2276 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2281 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2282 pkgCache::VerIterator version;
2284 _profile(Package$packageWithIterator$GetCandidateVer)
2285 version = [database policy]->GetCandidateVer(iterator);
2293 _profile(Package$packageWithIterator$Allocate)
2294 package = [Package allocWithZone:zone];
2297 _profile(Package$packageWithIterator$Initialize)
2299 initWithVersion:version
2306 _profile(Package$packageWithIterator$Autorelease)
2307 package = [package autorelease];
2313 - (pkgCache::PkgIterator) iterator {
2317 - (NSString *) section {
2318 if (section$_ == nil) {
2319 if (section_.empty())
2322 _profile(Package$section)
2323 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2324 NSString *name(section_);
2325 section$_ = [SectionMap_ objectForKey:name] ?: name;
2330 - (NSString *) simpleSection {
2331 if (NSString *section = [self section])
2332 return Simplify(section);
2337 - (NSString *) longSection {
2338 return LocalizeSection([self section]);
2341 - (NSString *) shortSection {
2342 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2345 - (NSString *) uri {
2348 pkgIndexFile *index;
2349 pkgCache::PkgFileIterator file(file_.File());
2350 if (![database_ list].FindIndex(file, index))
2352 return [NSString stringWithUTF8String:iterator_->Path];
2353 //return [NSString stringWithUTF8String:file.Site()];
2354 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2358 - (Address *) maintainer {
2359 @synchronized (database_) {
2360 if ([database_ era] != era_ || file_.end())
2363 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2364 const std::string &maintainer(parser->Maintainer());
2365 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2369 @synchronized (database_) {
2370 if ([database_ era] != era_ || version_.end())
2373 return version_->InstalledSize;
2376 - (NSString *) longDescription {
2377 @synchronized (database_) {
2378 if ([database_ era] != era_ || file_.end())
2381 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2382 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2384 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2385 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2386 if ([lines count] < 2)
2389 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2390 for (size_t i(1), e([lines count]); i != e; ++i) {
2391 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2392 [trimmed addObject:trim];
2395 return [trimmed componentsJoinedByString:@"\n"];
2398 - (NSString *) shortDescription {
2399 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2403 _profile(Package$index)
2404 CFStringRef name((CFStringRef) [self name]);
2405 if (CFStringGetLength(name) == 0)
2407 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2408 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2410 return toupper(character);
2414 - (PackageValue *) metadata {
2419 PackageValue *metadata([self metadata]);
2420 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2423 - (bool) subscribed {
2424 return [self metadata]->subscribed_;
2427 - (bool) setSubscribed:(bool)subscribed {
2428 PackageValue *metadata([self metadata]);
2429 if (metadata->subscribed_ == subscribed)
2431 metadata->subscribed_ = subscribed;
2439 - (NSString *) latest {
2443 - (NSString *) installed {
2447 - (BOOL) uninstalled {
2448 return installed_.empty();
2452 return !version_.end();
2455 - (BOOL) upgradableAndEssential:(BOOL)essential {
2456 _profile(Package$upgradableAndEssential)
2457 pkgCache::VerIterator current(iterator_.CurrentVer());
2459 return essential && essential_;
2461 return !version_.end() && version_ != current;
2465 - (BOOL) essential {
2470 return [database_ cache][iterator_].InstBroken();
2473 - (BOOL) unfiltered {
2474 _profile(Package$unfiltered$obsolete)
2479 _profile(Package$unfiltered$hasSupportingRole)
2480 if (![self hasSupportingRole])
2488 if (![self unfiltered])
2491 NSString *section([self section]);
2493 _profile(Package$visible$isSectionVisible)
2494 if (section != nil && !isSectionVisible(section))
2502 unsigned char current(iterator_->CurrentState);
2503 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2506 - (BOOL) halfConfigured {
2507 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2510 - (BOOL) halfInstalled {
2511 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2515 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2516 return state.Mode != pkgDepCache::ModeKeep;
2519 - (NSString *) mode {
2520 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2522 switch (state.Mode) {
2523 case pkgDepCache::ModeDelete:
2524 if ((state.iFlags & pkgDepCache::Purge) != 0)
2528 case pkgDepCache::ModeKeep:
2529 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2530 return @"REINSTALL";
2531 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2535 case pkgDepCache::ModeInstall:
2536 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2537 return @"REINSTALL";
2538 else*/ switch (state.Status) {
2540 return @"DOWNGRADE";
2546 return @"NEW_INSTALL";
2557 - (NSString *) name {
2558 return name_.empty() ? id_ : name_;
2561 - (UIImage *) icon {
2562 NSString *section = [self simpleSection];
2565 if (parsed_ != NULL)
2566 if (NSString *href = parsed_->icon_)
2567 if ([href hasPrefix:@"file:///"])
2568 // XXX: correct escaping
2569 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2570 if (icon == nil) if (section != nil)
2571 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2572 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2573 if ([dicon hasPrefix:@"file:///"])
2574 // XXX: correct escaping
2575 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2577 icon = [UIImage applicationImageNamed:@"unknown.png"];
2581 - (NSString *) homepage {
2582 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2585 - (NSString *) depiction {
2586 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2589 - (Address *) sponsor {
2590 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2593 - (Address *) author {
2594 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2597 - (NSString *) support {
2598 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2601 - (NSArray *) files {
2602 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2603 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2606 fin.open([path UTF8String]);
2611 while (std::getline(fin, line))
2612 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2617 - (NSArray *) warnings {
2618 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2619 const char *name(iterator_.Name());
2621 size_t length(strlen(name));
2622 if (length < 2) invalid:
2623 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2624 else for (size_t i(0); i != length; ++i)
2626 /* XXX: technically this is not allowed */
2627 (name[i] < 'A' || name[i] > 'Z') &&
2628 (name[i] < 'a' || name[i] > 'z') &&
2629 (name[i] < '0' || name[i] > '9') &&
2630 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2633 if (strcmp(name, "cydia") != 0) {
2636 bool _private = false;
2639 bool repository = [[self section] isEqualToString:@"Repositories"];
2641 if (NSArray *files = [self files])
2642 for (NSString *file in files)
2643 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2645 else if (!user && [file isEqualToString:@"/User"])
2647 else if (!_private && [file isEqualToString:@"/private"])
2649 else if (!stash && [file isEqualToString:@"/var/stash"])
2652 /* XXX: this is not sensitive enough. only some folders are valid. */
2653 if (cydia && !repository)
2654 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2656 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2658 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2660 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2663 return [warnings count] == 0 ? nil : warnings;
2666 - (NSArray *) applications {
2667 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2669 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2671 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2672 if (NSArray *files = [self files])
2673 for (NSString *file in files)
2674 if (application_r(file)) {
2675 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2676 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2677 if ([id isEqualToString:me])
2680 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2682 display = application_r[1];
2684 NSString *bundle([file stringByDeletingLastPathComponent]);
2685 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2686 if (icon == nil || [icon length] == 0)
2688 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2690 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2691 [applications addObject:application];
2693 [application addObject:id];
2694 [application addObject:display];
2695 [application addObject:url];
2698 return [applications count] == 0 ? nil : applications;
2701 - (Source *) source {
2702 if (source_ == nil) {
2703 @synchronized (database_) {
2704 if ([database_ era] != era_ || file_.end())
2705 source_ = (Source *) [NSNull null];
2707 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2711 return source_ == (Source *) [NSNull null] ? nil : source_;
2714 - (NSString *) role {
2718 - (BOOL) matches:(NSString *)text {
2724 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2725 if (range.location != NSNotFound)
2728 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2729 if (range.location != NSNotFound)
2732 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2733 if (range.location != NSNotFound)
2739 - (bool) hasSupportingRole {
2742 if ([role_ isEqualToString:@"enduser"])
2744 if ([Role_ isEqualToString:@"User"])
2746 if ([role_ isEqualToString:@"hacker"])
2748 if ([Role_ isEqualToString:@"Hacker"])
2750 if ([role_ isEqualToString:@"developer"])
2752 if ([Role_ isEqualToString:@"Developer"])
2757 - (BOOL) hasTag:(NSString *)tag {
2758 return tags_ == nil ? NO : [tags_ containsObject:tag];
2761 - (NSString *) primaryPurpose {
2762 for (NSString *tag in tags_)
2763 if ([tag hasPrefix:@"purpose::"])
2764 return [tag substringFromIndex:9];
2768 - (NSArray *) purposes {
2769 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2770 for (NSString *tag in tags_)
2771 if ([tag hasPrefix:@"purpose::"])
2772 [purposes addObject:[tag substringFromIndex:9]];
2773 return [purposes count] == 0 ? nil : purposes;
2776 - (bool) isCommercial {
2777 return [self hasTag:@"cydia::commercial"];
2780 - (void) setIndex:(size_t)index {
2781 if (metadata_->index_ != index)
2782 metadata_->index_ = index;
2785 - (CYString &) cyname {
2786 return name_.empty() ? id_ : name_;
2789 - (uint32_t) compareBySection:(NSArray *)sections {
2790 NSString *section([self section]);
2791 for (size_t i(0), e([sections count]); i != e; ++i) {
2792 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2796 return _not(uint32_t);
2800 @synchronized (database_) {
2801 pkgProblemResolver *resolver = [database_ resolver];
2802 resolver->Clear(iterator_);
2804 pkgCacheFile &cache([database_ cache]);
2805 cache->SetReInstall(iterator_, false);
2806 cache->MarkKeep(iterator_, false);
2810 @synchronized (database_) {
2811 pkgProblemResolver *resolver = [database_ resolver];
2812 resolver->Clear(iterator_);
2813 resolver->Protect(iterator_);
2815 pkgCacheFile &cache([database_ cache]);
2816 cache->SetReInstall(iterator_, false);
2817 cache->MarkInstall(iterator_, false);
2819 pkgDepCache::StateCache &state((*cache)[iterator_]);
2820 if (!state.Install())
2821 cache->SetReInstall(iterator_, true);
2825 @synchronized (database_) {
2826 pkgProblemResolver *resolver = [database_ resolver];
2827 resolver->Clear(iterator_);
2828 resolver->Remove(iterator_);
2829 resolver->Protect(iterator_);
2831 pkgCacheFile &cache([database_ cache]);
2832 cache->SetReInstall(iterator_, false);
2833 cache->MarkDelete(iterator_, true);
2836 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2837 _profile(Package$isUnfilteredAndSearchedForBy)
2840 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2841 value &= [self unfiltered];
2844 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2845 value &= [self matches:search];
2852 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2853 if ([search length] == 0)
2856 _profile(Package$isUnfilteredAndSelectedForBy)
2859 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2860 value &= [self unfiltered];
2863 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2864 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2871 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2872 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2875 - (bool) isVisibleInSection:(NSString *)name {
2876 NSString *section([self section]);
2880 section == nil && [name length] == 0 ||
2881 [name isEqualToString:section]
2882 ) && [self visible];
2885 - (bool) isVisibleInSource:(Source *)source {
2886 return [self source] == source && [self visible];
2891 /* Section Class {{{ */
2892 @interface Section : NSObject {
2897 NSString *localized_;
2900 - (NSComparisonResult) compareByLocalized:(Section *)section;
2901 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2902 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2903 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2904 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2905 - (NSString *) name;
2912 - (void) addToCount;
2914 - (void) setCount:(size_t)count;
2915 - (NSString *) localized;
2919 @implementation Section
2923 if (localized_ != nil)
2924 [localized_ release];
2928 - (NSComparisonResult) compareByLocalized:(Section *)section {
2929 NSString *lhs(localized_);
2930 NSString *rhs([section localized]);
2932 /*if ([lhs length] != 0 && [rhs length] != 0) {
2933 unichar lhc = [lhs characterAtIndex:0];
2934 unichar rhc = [rhs characterAtIndex:0];
2936 if (isalpha(lhc) && !isalpha(rhc))
2937 return NSOrderedAscending;
2938 else if (!isalpha(lhc) && isalpha(rhc))
2939 return NSOrderedDescending;
2942 return [lhs compare:rhs options:LaxCompareOptions_];
2945 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2946 if ((self = [self initWithName:name localize:NO]) != nil) {
2947 if (localized != nil)
2948 localized_ = [localized retain];
2952 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2953 return [self initWithName:name row:0 localize:localize];
2956 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2957 if ((self = [super init]) != nil) {
2958 name_ = [name retain];
2962 localized_ = [LocalizeSection(name_) retain];
2966 /* XXX: localize the index thingees */
2967 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2968 if ((self = [super init]) != nil) {
2969 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2975 - (NSString *) name {
2995 - (void) addToCount {
2999 - (void) setCount:(size_t)count {
3003 - (NSString *) localized {
3010 static NSString *Colon_;
3011 static NSString *Elision_;
3012 static NSString *Error_;
3013 static NSString *Warning_;
3015 /* Database Implementation {{{ */
3016 @implementation Database
3018 + (Database *) sharedInstance {
3019 static Database *instance;
3020 if (instance == nil)
3021 instance = [[Database alloc] init];
3029 - (void) releasePackages {
3030 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3031 CFArrayRemoveAllValues(packages_);
3035 // XXX: actually implement this thing
3037 [self releasePackages];
3038 apr_pool_destroy(pool_);
3039 NSRecycleZone(zone_);
3043 - (void) _readCydia:(NSNumber *)fd { _pooled
3044 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3045 std::istream is(&ib);
3048 static Pcre finish_r("^finish:([^:]*)$");
3050 while (std::getline(is, line)) {
3051 const char *data(line.c_str());
3052 size_t size = line.size();
3053 lprintf("C:%s\n", data);
3055 if (finish_r(data, size)) {
3056 NSString *finish = finish_r[1];
3057 int index = [Finishes_ indexOfObject:finish];
3058 if (index != INT_MAX && index > Finish_)
3066 - (void) _readStatus:(NSNumber *)fd { _pooled
3067 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3068 std::istream is(&ib);
3071 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3072 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3074 while (std::getline(is, line)) {
3075 const char *data(line.c_str());
3076 size_t size(line.size());
3077 lprintf("S:%s\n", data);
3079 if (conffile_r(data, size)) {
3080 [delegate_ setConfigurationData:conffile_r[1]];
3081 } else if (strncmp(data, "status: ", 8) == 0) {
3082 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3083 [delegate_ setProgressTitle:string];
3084 } else if (pmstatus_r(data, size)) {
3085 std::string type([pmstatus_r[1] UTF8String]);
3086 NSString *id = pmstatus_r[2];
3088 float percent([pmstatus_r[3] floatValue]);
3089 [delegate_ setProgressPercent:(percent / 100)];
3091 NSString *string = pmstatus_r[4];
3093 if (type == "pmerror")
3094 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3095 withObject:[NSArray arrayWithObjects:string, id, nil]
3098 else if (type == "pmstatus") {
3099 [delegate_ setProgressTitle:string];
3100 } else if (type == "pmconffile")
3101 [delegate_ setConfigurationData:string];
3103 lprintf("E:unknown pmstatus\n");
3105 lprintf("E:unknown status\n");
3111 - (void) _readOutput:(NSNumber *)fd { _pooled
3112 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3113 std::istream is(&ib);
3116 while (std::getline(is, line)) {
3117 lprintf("O:%s\n", line.c_str());
3118 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3128 - (Package *) packageWithName:(NSString *)name {
3129 @synchronized (self) {
3130 if (static_cast<pkgDepCache *>(cache_) == NULL)
3132 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3133 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3137 if ((self = [super init]) != nil) {
3144 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3145 apr_pool_create(&pool_, NULL);
3147 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3151 _assert(pipe(fds) != -1);
3154 _config->Set("APT::Keep-Fds::", cydiafd_);
3155 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3158 detachNewThreadSelector:@selector(_readCydia:)
3160 withObject:[NSNumber numberWithInt:fds[0]]
3163 _assert(pipe(fds) != -1);
3167 detachNewThreadSelector:@selector(_readStatus:)
3169 withObject:[NSNumber numberWithInt:fds[0]]
3172 _assert(pipe(fds) != -1);
3173 _assert(dup2(fds[0], 0) != -1);
3174 _assert(close(fds[0]) != -1);
3176 input_ = fdopen(fds[1], "a");
3178 _assert(pipe(fds) != -1);
3179 _assert(dup2(fds[1], 1) != -1);
3180 _assert(close(fds[1]) != -1);
3183 detachNewThreadSelector:@selector(_readOutput:)
3185 withObject:[NSNumber numberWithInt:fds[0]]
3190 - (pkgCacheFile &) cache {
3194 - (pkgDepCache::Policy *) policy {
3198 - (pkgRecords *) records {
3202 - (pkgProblemResolver *) resolver {
3206 - (pkgAcquire &) fetcher {
3210 - (pkgSourceList &) list {
3214 - (NSArray *) packages {
3215 return (NSArray *) packages_;
3218 - (NSArray *) sources {
3219 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3220 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3221 [sources addObject:i->second];
3225 - (NSArray *) issues {
3226 if (cache_->BrokenCount() == 0)
3229 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3231 for (Package *package in [self packages]) {
3232 if (![package broken])
3234 pkgCache::PkgIterator pkg([package iterator]);
3236 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3237 [entry addObject:[package name]];
3238 [issues addObject:entry];
3240 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3244 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3245 pkgCache::DepIterator start;
3246 pkgCache::DepIterator end;
3247 dep.GlobOr(start, end); // ++dep
3249 if (!cache_->IsImportantDep(end))
3251 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3254 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3255 [entry addObject:failure];
3256 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3258 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3259 if (Package *package = [self packageWithName:name])
3260 name = [package name];
3261 [failure addObject:name];
3263 pkgCache::PkgIterator target(start.TargetPkg());
3264 if (target->ProvidesList != 0)
3265 [failure addObject:@"?"];
3267 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3269 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3270 else if (!cache_[target].CandidateVerIter(cache_).end())
3271 [failure addObject:@"-"];
3272 else if (target->ProvidesList == 0)
3273 [failure addObject:@"!"];
3275 [failure addObject:@"%"];
3279 if (start.TargetVer() != 0)
3280 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3291 - (bool) popErrorWithTitle:(NSString *)title {
3293 std::string message;
3295 while (!_error->empty()) {
3297 bool warning(!_error->PopMessage(error));
3301 size_t size(error.size());
3302 if (size == 0 || error[size - 1] != '\n')
3304 error.resize(size - 1);
3306 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3308 if (!message.empty())
3313 if (fatal && !message.empty())
3314 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3319 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3320 return [self popErrorWithTitle:title] || !success;
3323 - (void) reloadData { CYPoolStart() {
3324 @synchronized (self) {
3327 [self releasePackages];
3348 apr_pool_clear(pool_);
3349 NSRecycleZone(zone_);
3351 int chk(creat("/tmp/cydia.chk", 0644));
3355 NSString *title(UCLocalize("DATABASE"));
3358 if (!cache_.Open(progress_, true)) { pop:
3360 bool warning(!_error->PopMessage(error));
3361 lprintf("cache_.Open():[%s]\n", error.c_str());
3363 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3364 [delegate_ repairWithSelector:@selector(configure)];
3365 else if (error == "The package lists or status file could not be parsed or opened.")
3366 [delegate_ repairWithSelector:@selector(update)];
3367 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3368 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3369 // else if (error == "The list of sources could not be read.")
3371 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3380 unlink("/tmp/cydia.chk");
3382 now_ = [[NSDate date] timeIntervalSince1970];
3384 policy_ = new pkgDepCache::Policy();
3385 records_ = new pkgRecords(cache_);
3386 resolver_ = new pkgProblemResolver(cache_);
3387 fetcher_ = new pkgAcquire(&status_);
3390 list_ = new pkgSourceList();
3391 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3394 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3395 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3399 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3402 if (cache_->BrokenCount() != 0) {
3403 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3406 if (cache_->BrokenCount() != 0) {
3407 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3411 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3415 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3416 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3417 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3418 // XXX: this could be more intelligent
3419 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3420 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3422 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3427 /*std::vector<Package *> packages;
3428 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3429 [packages_ release];
3434 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3435 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3436 //packages.push_back(package);
3437 CFArrayAppendValue(packages_, [package retain]);
3441 /*if (packages.empty())
3442 packages_ = [[NSArray alloc] init];
3444 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3447 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3448 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3449 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3457 /*if (!packages.empty())
3458 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3459 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3461 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3463 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3465 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3469 size_t count(CFArrayGetCount(packages_));
3470 for (size_t index(0); index != count; ++index)
3471 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3475 } } CYPoolEnd() _trace(); }
3478 @synchronized (self) {
3480 resolver_ = new pkgProblemResolver(cache_);
3482 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3483 if (!cache_[iterator].Keep()) {
3484 cache_->MarkKeep(iterator, false);
3485 cache_->SetReInstall(iterator, false);
3490 - (void) configure {
3491 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3492 system([dpkg UTF8String]);
3496 // XXX: I don't remember this condition
3501 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3503 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3505 if ([self popErrorWithTitle:title])
3509 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3512 public pkgArchiveCleaner
3515 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3520 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3527 fetcher_->Shutdown();
3529 pkgRecords records(cache_);
3531 lock_ = new FileFd();
3532 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3534 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3536 if ([self popErrorWithTitle:title])
3540 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3543 manager_ = (_system->CreatePM(cache_));
3544 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3551 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3553 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3555 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3557 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3558 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3561 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3566 bool failed = false;
3567 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3568 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3570 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3573 std::string uri = (*item)->DescURI();
3574 std::string error = (*item)->ErrorText;
3576 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3579 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3580 withObject:[NSArray arrayWithObjects:
3581 [NSString stringWithUTF8String:error.c_str()],
3593 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3595 if (_error->PendingError()) {
3600 if (result == pkgPackageManager::Failed) {
3605 if (result != pkgPackageManager::Completed) {
3610 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3612 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3614 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3615 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3618 if (![before isEqualToArray:after])
3623 NSString *title(UCLocalize("UPGRADE"));
3624 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3630 [self updateWithStatus:status_];
3633 - (void) updateWithStatus:(Status &)status {
3634 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3635 NSString *title(UCLocalize("REFRESHING_DATA"));
3638 if (!list.ReadMainList())
3639 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3642 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3643 if ([self popErrorWithTitle:title])
3646 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3647 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3648 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3650 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3654 - (void) setDelegate:(id)delegate {
3655 delegate_ = delegate;
3656 status_.setDelegate(delegate);
3657 progress_.setDelegate(delegate);
3660 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3661 SourceMap::const_iterator i(sources_.find(file->ID));
3662 return i == sources_.end() ? nil : i->second;
3668 /* Confirmation Controller {{{ */
3669 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3670 if (!iterator.end())
3671 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3672 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3674 pkgCache::PkgIterator package(dep.TargetPkg());
3677 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3685 /* Web Scripting {{{ */
3686 @interface CydiaObject : NSObject {
3688 _transient id delegate_;
3691 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3694 @implementation CydiaObject
3697 [indirect_ release];
3701 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3702 if ((self = [super init]) != nil) {
3703 indirect_ = [indirect retain];
3707 - (void) setDelegate:(id)delegate {
3708 delegate_ = delegate;
3711 + (NSArray *) _attributeKeys {
3712 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3715 - (NSArray *) attributeKeys {
3716 return [[self class] _attributeKeys];
3719 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3720 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3723 - (NSString *) device {
3724 return [[UIDevice currentDevice] uniqueIdentifier];
3727 #if 0 // XXX: implement!
3728 - (NSString *) mac {
3729 if (![indirect_ promptForSensitive:@"Mac Address"])
3733 - (NSString *) serial {
3734 if (![indirect_ promptForSensitive:@"Serial #"])
3738 - (NSString *) firewire {
3739 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3743 - (NSString *) imei {
3744 if (![indirect_ promptForSensitive:@"IMEI"])
3749 + (NSString *) webScriptNameForSelector:(SEL)selector {
3750 if (selector == @selector(close))
3752 else if (selector == @selector(getInstalledPackages))
3753 return @"getInstalledPackages";
3754 else if (selector == @selector(getPackageById:))
3755 return @"getPackageById";
3756 else if (selector == @selector(installPackages:))
3757 return @"installPackages";
3758 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3759 return @"setButtonImage";
3760 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3761 return @"setButtonTitle";
3762 else if (selector == @selector(setPopupHook:))
3763 return @"setPopupHook";
3764 else if (selector == @selector(setSpecial:))
3765 return @"setSpecial";
3766 else if (selector == @selector(setToken:))
3768 else if (selector == @selector(setViewportWidth:))
3769 return @"setViewportWidth";
3770 else if (selector == @selector(supports:))
3772 else if (selector == @selector(stringWithFormat:arguments:))
3774 else if (selector == @selector(localizedStringForKey:value:table:))
3776 else if (selector == @selector(du:))
3778 else if (selector == @selector(statfs:))
3784 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3785 return [self webScriptNameForSelector:selector] == nil;
3788 - (BOOL) supports:(NSString *)feature {
3789 return [feature isEqualToString:@"window.open"];
3792 - (NSArray *) getInstalledPackages {
3793 NSArray *packages([[Database sharedInstance] packages]);
3794 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3795 for (Package *package in packages)
3796 if ([package installed] != nil)
3797 [installed addObject:package];
3801 - (Package *) getPackageById:(NSString *)id {
3802 Package *package([[Database sharedInstance] packageWithName:id]);
3807 - (NSArray *) statfs:(NSString *)path {
3810 if (path == nil || statfs([path UTF8String], &stat) == -1)
3813 return [NSArray arrayWithObjects:
3814 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3815 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3816 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3820 - (NSNumber *) du:(NSString *)path {
3821 NSNumber *value(nil);
3824 _assert(pipe(fds) != -1);
3826 pid_t pid(ExecFork());
3828 _assert(dup2(fds[1], 1) != -1);
3829 _assert(close(fds[0]) != -1);
3830 _assert(close(fds[1]) != -1);
3831 /* XXX: this should probably not use du */
3832 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3837 _assert(close(fds[1]) != -1);
3839 if (FILE *du = fdopen(fds[0], "r")) {
3841 while (fgets(line, sizeof(line), du) != NULL) {
3842 size_t length(strlen(line));
3843 while (length != 0 && line[length - 1] == '\n')
3844 line[--length] = '\0';
3845 if (char *tab = strchr(line, '\t')) {
3847 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3852 } else _assert(close(fds[0]));
3856 if (waitpid(pid, &status, 0) == -1)
3859 else _assert(false);
3868 - (void) installPackages:(NSArray *)packages {
3869 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3872 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3873 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3876 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3877 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3880 - (void) setSpecial:(id)function {
3881 [indirect_ setSpecial:function];
3884 - (void) setToken:(NSString *)token {
3887 Token_ = [token retain];
3889 [Metadata_ setObject:Token_ forKey:@"Token"];
3893 - (void) setPopupHook:(id)function {
3894 [indirect_ setPopupHook:function];
3897 - (void) setViewportWidth:(float)width {
3898 [indirect_ setViewportWidth:width];
3901 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3902 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3903 unsigned count([arguments count]);
3905 for (unsigned i(0); i != count; ++i)
3906 values[i] = [arguments objectAtIndex:i];
3907 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3910 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3911 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3913 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3915 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3921 /* Cydia Browser Controller {{{ */
3922 @interface CYBrowserController : BrowserController {
3923 CydiaObject *cydia_;
3928 @implementation CYBrowserController
3935 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3938 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3939 [super webView:view didClearWindowObject:window forFrame:frame];
3941 WebDataSource *source([frame dataSource]);
3942 NSURLResponse *response([source response]);
3943 NSURL *url([response URL]);
3944 NSString *scheme([url scheme]);
3946 NSHTTPURLResponse *http;
3947 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3948 http = (NSHTTPURLResponse *) response;
3952 NSDictionary *headers([http allHeaderFields]);
3953 NSString *host([url host]);
3954 [self setHeaders:headers forHost:host];
3957 [host isEqualToString:@"cydia.saurik.com"] ||
3958 [host hasSuffix:@".cydia.saurik.com"] ||
3959 [scheme isEqualToString:@"file"]
3961 [window setValue:cydia_ forKey:@"cydia"];
3964 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3965 if (System_ != NULL)
3966 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3967 if (Machine_ != NULL)
3968 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3970 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3972 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3975 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3976 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3977 [self _setMoreHeaders:copy];
3981 - (void) setDelegate:(id)delegate {
3982 [super setDelegate:delegate];
3983 [cydia_ setDelegate:delegate];
3987 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3988 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3990 WebView *webview([[webview_ _documentView] webView]);
3992 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3994 NSString *application = package == nil ? @"Cydia" : [NSString
3995 stringWithFormat:@"Cydia/%@",
4000 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4002 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4003 if (Product_ != nil)
4004 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4006 [webview setApplicationNameForUserAgent:application];
4013 /* Confirmation {{{ */
4014 @protocol ConfirmationControllerDelegate
4015 - (void) cancelAndClear:(bool)clear;
4016 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4020 @interface ConfirmationController : CYBrowserController {
4021 _transient Database *database_;
4022 UIAlertView *essential_;
4029 - (id) initWithDatabase:(Database *)database;
4033 @implementation ConfirmationController
4040 if (essential_ != nil)
4041 [essential_ release];
4045 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4046 NSString *context([alert context]);
4048 if ([context isEqualToString:@"remove"]) {
4049 if (button == [alert cancelButtonIndex]) {
4050 [self dismissModalViewControllerAnimated:YES];
4051 } else if (button == [alert firstOtherButtonIndex]) {
4054 [delegate_ confirmWithNavigationController:[self navigationController]];
4057 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4058 } else if ([context isEqualToString:@"unable"]) {
4059 [self dismissModalViewControllerAnimated:YES];
4060 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4062 [super alertView:alert clickedButtonAtIndex:button];
4066 - (void) _doContinue {
4067 [self dismissModalViewControllerAnimated:YES];
4068 [delegate_ cancelAndClear:NO];
4071 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4072 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4076 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4077 [super webView:view didClearWindowObject:window forFrame:frame];
4078 [window setValue:changes_ forKey:@"changes"];
4079 [window setValue:issues_ forKey:@"issues"];
4080 [window setValue:sizes_ forKey:@"sizes"];
4081 [window setValue:self forKey:@"queue"];
4084 - (id) initWithDatabase:(Database *)database {
4085 if ((self = [super init]) != nil) {
4086 database_ = database;
4088 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4090 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4091 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4092 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4093 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4094 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4098 pkgDepCache::Policy *policy([database_ policy]);
4100 pkgCacheFile &cache([database_ cache]);
4101 NSArray *packages = [database_ packages];
4102 for (Package *package in packages) {
4103 pkgCache::PkgIterator iterator = [package iterator];
4104 pkgDepCache::StateCache &state(cache[iterator]);
4106 NSString *name([package name]);
4108 if (state.NewInstall())
4109 [installing addObject:name];
4110 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4111 [reinstalling addObject:name];
4112 else if (state.Upgrade())
4113 [upgrading addObject:name];
4114 else if (state.Downgrade())
4115 [downgrading addObject:name];
4116 else if (state.Delete()) {
4117 if ([package essential])
4119 [removing addObject:name];
4122 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4123 substrate_ |= DepSubstrate(iterator.CurrentVer());
4128 else if (Advanced_) {
4129 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4131 essential_ = [[UIAlertView alloc]
4132 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4133 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4135 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4136 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4139 [essential_ setContext:@"remove"];
4141 essential_ = [[UIAlertView alloc]
4142 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4143 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4145 cancelButtonTitle:UCLocalize("OKAY")
4146 otherButtonTitles:nil
4149 [essential_ setContext:@"unable"];
4152 changes_ = [[NSArray alloc] initWithObjects:
4160 issues_ = [database_ issues];
4162 issues_ = [issues_ retain];
4164 sizes_ = [[NSArray alloc] initWithObjects:
4165 SizeString([database_ fetcher].FetchNeeded()),
4166 SizeString([database_ fetcher].PartialPresent()),
4169 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4171 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4172 initWithTitle:UCLocalize("CANCEL")
4173 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4174 style:UIBarButtonItemStylePlain
4176 action:@selector(cancelButtonClicked)
4181 - (void) applyRightButton {
4182 #if !AlwaysReload && !IgnoreInstall
4183 if (issues_ == nil && ![self isLoading])
4184 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4185 initWithTitle:UCLocalize("CONFIRM")
4186 style:UIBarButtonItemStylePlain
4188 action:@selector(confirmButtonClicked)
4191 [super applyRightButton];
4193 [[self navigationItem] setRightBarButtonItem:nil];
4197 - (void) cancelButtonClicked {
4198 [self dismissModalViewControllerAnimated:YES];
4199 [delegate_ cancelAndClear:YES];
4203 - (void) confirmButtonClicked {
4207 if (essential_ != nil)
4212 [delegate_ confirmWithNavigationController:[self navigationController]];
4220 /* Progress Data {{{ */
4221 @interface ProgressData : NSObject {
4223 // XXX: should these really both be _transient?
4224 _transient id target_;
4225 _transient id object_;
4228 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4235 @implementation ProgressData
4237 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4238 if ((self = [super init]) != nil) {
4239 selector_ = selector;
4259 /* Progress Controller {{{ */
4260 @interface ProgressController : CYViewController <
4261 ConfigurationDelegate,
4264 _transient Database *database_;
4265 UIProgressBar *progress_;
4266 UITextView *output_;
4267 UITextLabel *status_;
4268 UIPushButton *close_;
4270 SHA1SumValue springlist_;
4271 SHA1SumValue notifyconf_;
4275 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4277 - (void) _retachThread;
4278 - (void) _detachNewThreadData:(ProgressData *)data;
4279 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4285 @protocol ProgressControllerDelegate
4286 - (void) progressControllerIsComplete:(ProgressController *)sender;
4289 @implementation ProgressController
4292 [database_ setDelegate:nil];
4293 [progress_ release];
4302 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4303 if ((self = [super init]) != nil) {
4304 database_ = database;
4305 [database_ setDelegate:self];
4306 delegate_ = delegate;
4308 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4310 progress_ = [[UIProgressBar alloc] init];
4311 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4312 [progress_ setStyle:0];
4314 status_ = [[UITextLabel alloc] init];
4315 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4316 [status_ setColor:[UIColor whiteColor]];
4317 [status_ setBackgroundColor:[UIColor clearColor]];
4318 [status_ setCentersHorizontally:YES];
4319 //[status_ setFont:font];
4321 output_ = [[UITextView alloc] init];
4323 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4324 //[output_ setTextFont:@"Courier New"];
4325 [output_ setFont:[[output_ font] fontWithSize:12]];
4326 [output_ setTextColor:[UIColor whiteColor]];
4327 [output_ setBackgroundColor:[UIColor clearColor]];
4328 [output_ setMarginTop:0];
4329 [output_ setAllowsRubberBanding:YES];
4330 [output_ setEditable:NO];
4331 [[self view] addSubview:output_];
4333 close_ = [[UIPushButton alloc] init];
4334 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4335 [close_ setAutosizesToFit:NO];
4336 [close_ setDrawsShadow:YES];
4337 [close_ setStretchBackground:YES];
4338 [close_ setEnabled:YES];
4339 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4340 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4341 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4342 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4346 - (void) positionViews {
4347 CGRect bounds = [[self view] bounds];
4348 CGSize prgsize = [UIProgressBar defaultSize];
4351 (bounds.size.width - prgsize.width) / 2,
4352 bounds.size.height - prgsize.height - 20
4355 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4357 [progress_ setFrame:prgrect];
4358 [status_ setFrame:CGRectMake(
4360 bounds.size.height - prgsize.height - 50,
4361 bounds.size.width - 20,
4364 [output_ setFrame:CGRectMake(
4367 bounds.size.width - 20,
4368 bounds.size.height - 62
4370 [close_ setFrame:CGRectMake(
4371 (bounds.size.width - closewidth) / 2,
4372 bounds.size.height - prgsize.height - 50,
4378 - (void) viewWillAppear:(BOOL)animated {
4379 [super viewDidAppear:animated];
4380 [[self navigationItem] setHidesBackButton:YES];
4381 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4383 [self positionViews];
4386 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4387 [self positionViews];
4390 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4391 NSString *context([alert context]);
4393 if ([context isEqualToString:@"conffile"]) {
4394 FILE *input = [database_ input];
4395 if (button == [alert cancelButtonIndex])
4396 fprintf(input, "N\n");
4397 else if (button == [alert firstOtherButtonIndex])
4398 fprintf(input, "Y\n");
4403 - (void) closeButtonPushed {
4406 UpdateExternalStatus(0);
4410 [self dismissModalViewControllerAnimated:YES];
4414 [delegate_ terminateWithSuccess];
4415 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4416 [delegate_ suspendWithAnimation:YES];
4418 [delegate_ suspend];*/
4422 system("launchctl stop com.apple.SpringBoard");
4426 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4435 - (void) _retachThread {
4436 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4438 [[self view] addSubview:close_];
4439 [progress_ removeFromSuperview];
4440 [status_ removeFromSuperview];
4442 [database_ popErrorWithTitle:title_];
4443 [delegate_ progressControllerIsComplete:self];
4447 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4450 MMap mmap(file, MMap::ReadOnly);
4452 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4453 if (!(notifyconf_ == sha1.Result()))
4460 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4463 MMap mmap(file, MMap::ReadOnly);
4465 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4466 if (!(springlist_ == sha1.Result()))
4472 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4473 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4474 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4475 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4476 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4479 system("su -c /usr/bin/uicache mobile");
4481 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4483 [delegate_ setStatusBarShowsProgress:NO];
4486 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4487 [[data target] performSelector:[data selector] withObject:[data object]];
4488 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4491 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4492 UpdateExternalStatus(1);
4499 title_ = [title retain];
4501 [[self navigationItem] setTitle:title_];
4503 [status_ setText:nil];
4504 [output_ setText:@""];
4505 [progress_ setProgress:0];
4507 [close_ removeFromSuperview];
4508 [[self view] addSubview:progress_];
4509 [[self view] addSubview:status_];
4511 [delegate_ setStatusBarShowsProgress:YES];
4516 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4519 MMap mmap(file, MMap::ReadOnly);
4521 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4522 notifyconf_ = sha1.Result();
4528 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4531 MMap mmap(file, MMap::ReadOnly);
4533 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4534 springlist_ = sha1.Result();
4539 detachNewThreadSelector:@selector(_detachNewThreadData:)
4541 withObject:[[[ProgressData alloc]
4542 initWithSelector:selector
4549 - (void) repairWithSelector:(SEL)selector {
4551 detachNewThreadSelector:selector
4554 title:UCLocalize("REPAIRING")
4558 - (void) setConfigurationData:(NSString *)data {
4560 performSelectorOnMainThread:@selector(_setConfigurationData:)
4566 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4567 CYActionSheet *sheet([[[CYActionSheet alloc]
4569 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4570 defaultButtonIndex:0
4573 [sheet setMessage:error];
4574 [sheet yieldToPopupAlertAnimated:YES];
4578 - (void) setProgressTitle:(NSString *)title {
4580 performSelectorOnMainThread:@selector(_setProgressTitle:)
4586 - (void) setProgressPercent:(float)percent {
4588 performSelectorOnMainThread:@selector(_setProgressPercent:)
4589 withObject:[NSNumber numberWithFloat:percent]
4594 - (void) startProgress {
4597 - (void) addProgressOutput:(NSString *)output {
4599 performSelectorOnMainThread:@selector(_addProgressOutput:)
4605 - (bool) isCancelling:(size_t)received {
4609 - (void) _setConfigurationData:(NSString *)data {
4610 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4612 if (!conffile_r(data)) {
4613 lprintf("E:invalid conffile\n");
4617 NSString *ofile = conffile_r[1];
4618 //NSString *nfile = conffile_r[2];
4620 UIAlertView *alert = [[[UIAlertView alloc]
4621 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4622 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4624 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4625 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4626 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4630 [alert setContext:@"conffile"];
4634 - (void) _setProgressTitle:(NSString *)title {
4635 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4636 for (size_t i(0), e([words count]); i != e; ++i) {
4637 NSString *word([words objectAtIndex:i]);
4638 if (Package *package = [database_ packageWithName:word])
4639 [words replaceObjectAtIndex:i withObject:[package name]];
4642 [status_ setText:[words componentsJoinedByString:@" "]];
4645 - (void) _setProgressPercent:(NSNumber *)percent {
4646 [progress_ setProgress:[percent floatValue]];
4649 - (void) _addProgressOutput:(NSString *)output {
4650 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4651 CGSize size = [output_ contentSize];
4652 CGRect rect = {{0, size.height}, {size.width, 0}};
4653 [output_ scrollRectToVisible:rect animated:YES];
4656 - (BOOL) isRunning {
4663 /* Cell Content View {{{ */
4664 @protocol ContentDelegate
4665 - (void) drawContentRect:(CGRect)rect;
4668 @interface ContentView : UIView {
4669 _transient id<ContentDelegate> delegate_;
4674 @implementation ContentView
4676 - (id) initWithFrame:(CGRect)frame {
4677 if ((self = [super initWithFrame:frame]) != nil) {
4678 [self setNeedsDisplayOnBoundsChange:YES];
4682 - (void) setDelegate:(id<ContentDelegate>)delegate {
4683 delegate_ = delegate;
4686 - (void) drawRect:(CGRect)rect {
4687 [super drawRect:rect];
4688 [delegate_ drawContentRect:rect];
4693 /* Cydia TableView Cell {{{ */
4694 @interface CYTableViewCell : UITableViewCell {
4695 ContentView *content_;
4701 @implementation CYTableViewCell
4708 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4709 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4711 if (view == content_) {
4712 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4713 highlighted_ = highlighted;
4716 [super _updateHighlightColorsForView:view highlighted:highlighted];
4719 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4720 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4721 highlighted_ = selected;
4723 [super setSelected:selected animated:animated];
4724 [content_ setNeedsDisplay];
4729 /* Package Cell {{{ */
4730 @interface PackageCell : CYTableViewCell <
4735 NSString *description_;
4743 - (PackageCell *) init;
4744 - (void) setPackage:(Package *)package;
4746 + (int) heightForPackage:(Package *)package;
4747 - (void) drawContentRect:(CGRect)rect;
4751 @implementation PackageCell
4753 - (void) clearPackage {
4764 if (description_ != nil) {
4765 [description_ release];
4769 if (source_ != nil) {
4774 if (badge_ != nil) {
4779 if (placard_ != nil) {
4789 [self clearPackage];
4793 - (PackageCell *) init {
4794 CGRect frame(CGRectMake(0, 0, 320, 74));
4795 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4796 UIView *content([self contentView]);
4797 CGRect bounds([content bounds]);
4799 content_ = [[ContentView alloc] initWithFrame:bounds];
4800 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4801 [content addSubview:content_];
4803 [content_ setDelegate:self];
4804 [content_ setOpaque:YES];
4808 - (void) _setBackgroundColor {
4810 if (NSString *mode = [package_ mode]) {
4811 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4812 color = remove ? RemovingColor_ : InstallingColor_;
4814 color = [UIColor whiteColor];
4816 [content_ setBackgroundColor:color];
4817 [self setNeedsDisplay];
4820 - (void) setPackage:(Package *)package {
4821 [self clearPackage];
4824 Source *source = [package source];
4826 icon_ = [[package icon] retain];
4827 name_ = [[package name] retain];
4830 description_ = [package longDescription];
4831 if (description_ == nil)
4832 description_ = [package shortDescription];
4833 if (description_ != nil)
4834 description_ = [description_ retain];
4836 commercial_ = [package isCommercial];
4838 package_ = [package retain];
4840 NSString *label = nil;
4841 bool trusted = false;
4843 if (source != nil) {
4844 label = [source label];
4845 trusted = [source trusted];
4846 } else if ([[package id] isEqualToString:@"firmware"])
4847 label = UCLocalize("APPLE");
4849 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4851 NSString *from(label);
4853 NSString *section = [package simpleSection];
4854 if (section != nil && ![section isEqualToString:label]) {
4855 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4856 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4859 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4860 source_ = [from retain];
4862 if (NSString *purpose = [package primaryPurpose])
4863 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4864 badge_ = [badge_ retain];
4866 if ([package installed] != nil)
4867 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4868 placard_ = [placard_ retain];
4870 [self _setBackgroundColor];
4871 [content_ setNeedsDisplay];
4874 - (void) drawContentRect:(CGRect)rect {
4875 bool highlighted(highlighted_);
4876 float width([self bounds].size.width);
4879 CGContextRef context(UIGraphicsGetCurrentContext());
4880 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4881 CGContextFillRect(context, rect);
4886 rect.size = [icon_ size];
4888 rect.size.width /= 2;
4889 rect.size.height /= 2;
4891 rect.origin.x = 25 - rect.size.width / 2;
4892 rect.origin.y = 25 - rect.size.height / 2;
4894 [icon_ drawInRect:rect];
4897 if (badge_ != nil) {
4898 CGSize size = [badge_ size];
4900 [badge_ drawAtPoint:CGPointMake(
4901 36 - size.width / 2,
4902 36 - size.height / 2
4910 UISetColor(commercial_ ? Purple_ : Black_);
4911 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4912 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4915 UISetColor(commercial_ ? Purplish_ : Gray_);
4916 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4918 if (placard_ != nil)
4919 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4922 + (int) heightForPackage:(Package *)package {
4928 /* Section Cell {{{ */
4929 @interface SectionCell : CYTableViewCell <
4941 - (void) setSection:(Section *)section editing:(BOOL)editing;
4945 @implementation SectionCell
4947 - (void) clearSection {
4948 if (basic_ != nil) {
4953 if (section_ != nil) {
4963 if (count_ != nil) {
4970 [self clearSection];
4976 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4977 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4978 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4979 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4980 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4982 UIView *content([self contentView]);
4983 CGRect bounds([content bounds]);
4985 content_ = [[ContentView alloc] initWithFrame:bounds];
4986 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4987 [content addSubview:content_];
4988 [content_ setBackgroundColor:[UIColor whiteColor]];
4990 [content_ setDelegate:self];
4994 - (void) onSwitch:(id)sender {
4995 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
4996 if (metadata == nil) {
4997 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4998 [Sections_ setObject:metadata forKey:basic_];
5001 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5005 - (void) setSection:(Section *)section editing:(BOOL)editing {
5006 if (editing != editing_) {
5008 [switch_ removeFromSuperview];
5010 [self addSubview:switch_];
5014 [self clearSection];
5016 if (section == nil) {
5017 name_ = [UCLocalize("ALL_PACKAGES") retain];
5020 basic_ = [section name];
5022 basic_ = [basic_ retain];
5024 section_ = [section localized];
5025 if (section_ != nil)
5026 section_ = [section_ retain];
5028 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5029 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5032 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5035 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5036 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5038 [content_ setNeedsDisplay];
5041 - (void) setFrame:(CGRect)frame {
5042 [super setFrame:frame];
5044 CGRect rect([switch_ frame]);
5045 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5048 - (void) drawContentRect:(CGRect)rect {
5049 bool highlighted(highlighted_);
5051 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5056 float width(rect.size.width);
5062 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5064 CGSize size = [count_ sizeWithFont:Font14_];
5068 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5074 /* File Table {{{ */
5075 @interface FileTable : CYViewController <
5076 UITableViewDataSource,
5079 _transient Database *database_;
5082 NSMutableArray *files_;
5086 - (id) initWithDatabase:(Database *)database;
5087 - (void) setPackage:(Package *)package;
5091 @implementation FileTable
5094 if (package_ != nil)
5103 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5104 return files_ == nil ? 0 : [files_ count];
5107 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5111 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5112 static NSString *reuseIdentifier = @"Cell";
5114 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5116 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5117 [cell setFont:[UIFont systemFontOfSize:16]];
5119 [cell setText:[files_ objectAtIndex:indexPath.row]];
5120 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5125 - (id) initWithDatabase:(Database *)database {
5126 if ((self = [super init]) != nil) {
5127 database_ = database;
5129 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5131 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5133 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5134 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5135 [list_ setRowHeight:24.0f];
5136 [[self view] addSubview:list_];
5138 [list_ setDataSource:self];
5139 [list_ setDelegate:self];
5143 - (void) setPackage:(Package *)package {
5144 if (package_ != nil) {
5145 [package_ autorelease];
5154 [files_ removeAllObjects];
5156 if (package != nil) {
5157 package_ = [package retain];
5158 name_ = [[package id] retain];
5160 if (NSArray *files = [package files])
5161 [files_ addObjectsFromArray:files];
5163 if ([files_ count] != 0) {
5164 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5165 [files_ removeObjectAtIndex:0];
5166 [files_ sortUsingSelector:@selector(compareByPath:)];
5168 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5169 [stack addObject:@"/"];
5171 for (int i(0), e([files_ count]); i != e; ++i) {
5172 NSString *file = [files_ objectAtIndex:i];
5173 while (![file hasPrefix:[stack lastObject]])
5174 [stack removeLastObject];
5175 NSString *directory = [stack lastObject];
5176 [stack addObject:[file stringByAppendingString:@"/"]];
5177 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5178 ([stack count] - 2) * 3, "",
5179 [file substringFromIndex:[directory length]]
5188 - (void) reloadData {
5189 [self setPackage:[database_ packageWithName:name_]];
5194 /* Package Controller {{{ */
5195 @interface PackageController : CYBrowserController <
5196 UIActionSheetDelegate
5198 _transient Database *database_;
5202 NSMutableArray *buttons_;
5203 UIBarButtonItem *button_;
5206 - (id) initWithDatabase:(Database *)database;
5207 - (void) setPackage:(Package *)package;
5211 @implementation PackageController
5214 if (package_ != nil)
5228 if ([self retainCount] == 1)
5229 [delegate_ setPackageController:self];
5233 /* XXX: this is not safe at all... localization of /fail/ */
5234 - (void) _clickButtonWithName:(NSString *)name {
5235 if ([name isEqualToString:UCLocalize("CLEAR")])
5236 [delegate_ clearPackage:package_];
5237 else if ([name isEqualToString:UCLocalize("INSTALL")])
5238 [delegate_ installPackage:package_];
5239 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5240 [delegate_ installPackage:package_];
5241 else if ([name isEqualToString:UCLocalize("REMOVE")])
5242 [delegate_ removePackage:package_];
5243 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5244 [delegate_ installPackage:package_];
5245 else _assert(false);
5248 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5249 NSString *context([sheet context]);
5251 if ([context isEqualToString:@"modify"]) {
5252 if (button != [sheet cancelButtonIndex]) {
5253 NSString *buttonName = [buttons_ objectAtIndex:button];
5254 [self _clickButtonWithName:buttonName];
5257 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5261 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5262 [super webView:view didClearWindowObject:window forFrame:frame];
5263 [window setValue:package_ forKey:@"package"];
5266 - (bool) _allowJavaScriptPanel {
5271 - (void) _customButtonClicked {
5272 int count([buttons_ count]);
5277 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5279 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5280 [buttons addObjectsFromArray:buttons_];
5282 UIActionSheet *sheet = [[[UIActionSheet alloc]
5285 cancelButtonTitle:nil
5286 destructiveButtonTitle:nil
5287 otherButtonTitles:nil
5290 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5292 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5293 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5295 [sheet setContext:@"modify"];
5297 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5301 // We don't want to allow non-commercial packages to do custom things to the install button,
5302 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5303 - (void) customButtonClicked {
5305 [super customButtonClicked];
5307 [self _customButtonClicked];
5310 - (void) reloadButtonClicked {
5311 // Don't reload a package view by clicking the button.
5314 - (void) applyLoadingTitle {
5315 // Don't show "Loading" as the title. Ever.
5318 - (UIBarButtonItem *) rightButton {
5323 - (id) initWithDatabase:(Database *)database {
5324 if ((self = [super init]) != nil) {
5325 database_ = database;
5326 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5327 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5331 - (void) setPackage:(Package *)package {
5332 if (package_ != nil) {
5333 [package_ autorelease];
5342 [buttons_ removeAllObjects];
5344 if (package != nil) {
5347 package_ = [package retain];
5348 name_ = [[package id] retain];
5349 commercial_ = [package isCommercial];
5351 if ([package_ mode] != nil)
5352 [buttons_ addObject:UCLocalize("CLEAR")];
5353 if ([package_ source] == nil);
5354 else if ([package_ upgradableAndEssential:NO])
5355 [buttons_ addObject:UCLocalize("UPGRADE")];
5356 else if ([package_ uninstalled])
5357 [buttons_ addObject:UCLocalize("INSTALL")];
5359 [buttons_ addObject:UCLocalize("REINSTALL")];
5360 if (![package_ uninstalled])
5361 [buttons_ addObject:UCLocalize("REMOVE")];
5368 switch ([buttons_ count]) {
5369 case 0: title = nil; break;
5370 case 1: title = [buttons_ objectAtIndex:0]; break;
5371 default: title = UCLocalize("MODIFY"); break;
5374 button_ = [[UIBarButtonItem alloc]
5376 style:UIBarButtonItemStylePlain
5378 action:@selector(customButtonClicked)
5384 - (bool) isLoading {
5385 return commercial_ ? [super isLoading] : false;
5388 - (void) reloadData {
5389 [self setPackage:[database_ packageWithName:name_]];
5394 /* Package Table {{{ */
5395 @interface PackageTable : UIView <
5396 UITableViewDataSource,
5399 _transient Database *database_;
5400 NSMutableArray *packages_;
5401 NSMutableArray *sections_;
5403 NSMutableArray *index_;
5404 NSMutableDictionary *indices_;
5405 // XXX: this target_ seems to be delegate_. :(
5406 _transient id target_;
5408 // XXX: why do we even have this delegate_?
5409 _transient id delegate_;
5412 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5414 - (void) setDelegate:(id)delegate;
5416 - (void) reloadData;
5417 - (void) resetCursor;
5419 - (UITableView *) list;
5421 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5423 - (void) deselectWithAnimation:(BOOL)animated;
5427 @implementation PackageTable
5430 [packages_ release];
5431 [sections_ release];
5439 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5440 NSInteger count([sections_ count]);
5441 return count == 0 ? 1 : count;
5444 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5445 if ([sections_ count] == 0)
5447 return [[sections_ objectAtIndex:section] name];
5450 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5451 if ([sections_ count] == 0)
5453 return [[sections_ objectAtIndex:section] count];
5456 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5457 Section *section([sections_ objectAtIndex:[path section]]);
5458 NSInteger row([path row]);
5459 Package *package([packages_ objectAtIndex:([section row] + row)]);
5463 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5464 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5466 cell = [[[PackageCell alloc] init] autorelease];
5467 [cell setPackage:[self packageAtIndexPath:path]];
5471 - (void) deselectWithAnimation:(BOOL)animated {
5472 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5475 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5476 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5479 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5480 Package *package([self packageAtIndexPath:path]);
5481 package = [database_ packageWithName:[package id]];
5482 [target_ performSelector:action_ withObject:package];
5486 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5487 return [packages_ count] > 20 ? index_ : nil;
5490 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5494 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5495 if ((self = [super initWithFrame:frame]) != nil) {
5496 database_ = database;
5501 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5502 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5504 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5505 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5507 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5508 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5509 [list_ setRowHeight:73.0f];
5510 [self addSubview:list_];
5512 [list_ setDataSource:self];
5513 [list_ setDelegate:self];
5517 - (void) setDelegate:(id)delegate {
5518 delegate_ = delegate;
5521 - (bool) hasPackage:(Package *)package {
5525 - (void) reloadData {
5526 NSArray *packages = [database_ packages];
5528 [packages_ removeAllObjects];
5529 [sections_ removeAllObjects];
5531 _profile(PackageTable$reloadData$Filter)
5532 for (Package *package in packages)
5533 if ([self hasPackage:package])
5534 [packages_ addObject:package];
5537 [index_ removeAllObjects];
5538 [indices_ removeAllObjects];
5540 Section *section = nil;
5542 _profile(PackageTable$reloadData$Section)
5543 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5547 _profile(PackageTable$reloadData$Section$Package)
5548 package = [packages_ objectAtIndex:offset];
5549 index = [package index];
5552 if (section == nil || [section index] != index) {
5553 _profile(PackageTable$reloadData$Section$Allocate)
5554 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5557 [index_ addObject:[section name]];
5558 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5560 _profile(PackageTable$reloadData$Section$Add)
5561 [sections_ addObject:section];
5565 [section addToCount];
5569 _profile(PackageTable$reloadData$List)
5574 - (void) resetCursor {
5575 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5578 - (UITableView *) list {
5582 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5583 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5588 /* Filtered Package Table {{{ */
5589 @interface FilteredPackageTable : PackageTable {
5595 - (void) setObject:(id)object;
5596 - (void) setObject:(id)object forFilter:(SEL)filter;
5598 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5602 @implementation FilteredPackageTable
5610 - (void) setFilter:(SEL)filter {
5613 /* XXX: this is an unsafe optimization of doomy hell */
5614 Method method(class_getInstanceMethod([Package class], filter));
5615 _assert(method != NULL);
5616 imp_ = method_getImplementation(method);
5617 _assert(imp_ != NULL);
5620 - (void) setObject:(id)object {
5626 object_ = [object retain];
5629 - (void) setObject:(id)object forFilter:(SEL)filter {
5630 [self setFilter:filter];
5631 [self setObject:object];
5634 - (bool) hasPackage:(Package *)package {
5635 _profile(FilteredPackageTable$hasPackage)
5636 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5640 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5641 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5642 [self setFilter:filter];
5643 object_ = [object retain];
5651 /* Filtered Package Controller {{{ */
5652 @interface FilteredPackageController : CYViewController {
5653 _transient Database *database_;
5654 FilteredPackageTable *packages_;
5658 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5662 @implementation FilteredPackageController
5665 [packages_ release];
5671 - (void) viewDidAppear:(BOOL)animated {
5672 [super viewDidAppear:animated];
5673 [packages_ deselectWithAnimation:animated];
5676 - (void) didSelectPackage:(Package *)package {
5677 PackageController *view([delegate_ packageController]);
5678 [view setPackage:package];
5679 [view setDelegate:delegate_];
5680 [[self navigationController] pushViewController:view animated:YES];
5683 - (NSString *) title { return title_; }
5685 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5686 if ((self = [super init]) != nil) {
5687 database_ = database;
5688 title_ = [title copy];
5689 [[self navigationItem] setTitle:title_];
5691 packages_ = [[FilteredPackageTable alloc]
5692 initWithFrame:[[self view] bounds]
5695 action:@selector(didSelectPackage:)
5700 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5701 [[self view] addSubview:packages_];
5705 - (void) reloadData {
5706 [packages_ reloadData];
5709 - (void) setDelegate:(id)delegate {
5710 [super setDelegate:delegate];
5711 [packages_ setDelegate:delegate];
5718 /* Add Source Controller {{{ */
5719 @interface AddSourceController : CYViewController {
5720 _transient Database *database_;
5723 - (id) initWithDatabase:(Database *)database;
5727 @implementation AddSourceController
5729 - (id) initWithDatabase:(Database *)database {
5730 if ((self = [super init]) != nil) {
5731 database_ = database;
5737 /* Source Cell {{{ */
5738 @interface SourceCell : CYTableViewCell <
5743 NSString *description_;
5747 - (void) setSource:(Source *)source;
5751 @implementation SourceCell
5753 - (void) clearSource {
5756 [description_ release];
5765 - (void) setSource:(Source *)source {
5769 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5771 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5772 icon_ = [icon_ retain];
5774 origin_ = [[source name] retain];
5775 label_ = [[source uri] retain];
5776 description_ = [[source description] retain];
5778 [content_ setNeedsDisplay];
5786 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5787 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5788 UIView *content([self contentView]);
5789 CGRect bounds([content bounds]);
5791 content_ = [[ContentView alloc] initWithFrame:bounds];
5792 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5793 [content_ setBackgroundColor:[UIColor whiteColor]];
5794 [content addSubview:content_];
5796 [content_ setDelegate:self];
5797 [content_ setOpaque:YES];
5801 - (void) drawContentRect:(CGRect)rect {
5802 bool highlighted(highlighted_);
5803 float width(rect.size.width);
5806 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5813 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5817 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5821 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5826 /* Source Table {{{ */
5827 @interface SourceTable : CYViewController <
5828 UITableViewDataSource,
5831 _transient Database *database_;
5833 NSMutableArray *sources_;
5837 UIProgressHUD *hud_;
5840 //NSURLConnection *installer_;
5841 NSURLConnection *trivial_;
5842 NSURLConnection *trivial_bz2_;
5843 NSURLConnection *trivial_gz_;
5844 //NSURLConnection *automatic_;
5849 - (id) initWithDatabase:(Database *)database;
5851 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5855 @implementation SourceTable
5857 - (void) _releaseConnection:(NSURLConnection *)connection {
5858 if (connection != nil) {
5859 [connection cancel];
5860 //[connection setDelegate:nil];
5861 [connection release];
5873 //[self _releaseConnection:installer_];
5874 [self _releaseConnection:trivial_];
5875 [self _releaseConnection:trivial_gz_];
5876 [self _releaseConnection:trivial_bz2_];
5877 //[self _releaseConnection:automatic_];
5884 - (void) viewDidAppear:(BOOL)animated {
5885 [super viewDidAppear:animated];
5886 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5889 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5890 return offset_ == 0 ? 1 : 2;
5893 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5894 switch (section + (offset_ == 0 ? 1 : 0)) {
5895 case 0: return UCLocalize("ENTERED_BY_USER");
5896 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5902 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5903 int count = [sources_ count];
5905 case 0: return (offset_ == 0 ? count : offset_);
5906 case 1: return count - offset_;
5912 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5914 switch (indexPath.section) {
5915 case 0: idx = indexPath.row; break;
5916 case 1: idx = indexPath.row + offset_; break;
5920 return [sources_ objectAtIndex:idx];
5923 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5924 Source *source = [self sourceAtIndexPath:indexPath];
5925 return [source description] == nil ? 56 : 73;
5928 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5929 static NSString *cellIdentifier = @"SourceCell";
5931 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5932 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5933 [cell setSource:[self sourceAtIndexPath:indexPath]];
5938 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5939 return UITableViewCellAccessoryDisclosureIndicator;
5942 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5943 Source *source = [self sourceAtIndexPath:indexPath];
5945 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5946 initWithDatabase:database_
5947 title:[source label]
5948 filter:@selector(isVisibleInSource:)
5952 [packages setDelegate:delegate_];
5954 [[self navigationController] pushViewController:packages animated:YES];
5957 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5958 Source *source = [self sourceAtIndexPath:indexPath];
5959 return [source record] != nil;
5962 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5963 Source *source = [self sourceAtIndexPath:indexPath];
5964 [Sources_ removeObjectForKey:[source key]];
5965 [delegate_ syncData];
5969 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5972 @"./", @"Distribution",
5973 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5975 [delegate_ syncData];
5978 - (NSString *) getWarning {
5979 NSString *href(href_);
5980 NSRange colon([href rangeOfString:@"://"]);
5981 if (colon.location != NSNotFound)
5982 href = [href substringFromIndex:(colon.location + 3)];
5983 href = [href stringByAddingPercentEscapes];
5984 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5985 href = [href stringByCachingURLWithCurrentCDN];
5987 NSURL *url([NSURL URLWithString:href]);
5989 NSStringEncoding encoding;
5990 NSError *error(nil);
5992 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5993 return [warning length] == 0 ? nil : warning;
5997 - (void) _endConnection:(NSURLConnection *)connection {
5998 // XXX: the memory management in this method is horribly awkward
6000 NSURLConnection **field = NULL;
6001 if (connection == trivial_)
6003 else if (connection == trivial_bz2_)
6004 field = &trivial_bz2_;
6005 else if (connection == trivial_gz_)
6006 field = &trivial_gz_;
6007 _assert(field != NULL);
6008 [connection release];
6013 trivial_bz2_ == nil &&
6019 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6022 UIAlertView *alert = [[[UIAlertView alloc]
6023 initWithTitle:UCLocalize("SOURCE_WARNING")
6026 cancelButtonTitle:UCLocalize("CANCEL")
6027 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6030 [alert setContext:@"warning"];
6031 [alert setNumberOfRows:1];
6035 } else if (error_ != nil) {
6036 UIAlertView *alert = [[[UIAlertView alloc]
6037 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6038 message:[error_ localizedDescription]
6040 cancelButtonTitle:UCLocalize("OK")
6041 otherButtonTitles:nil
6044 [alert setContext:@"urlerror"];
6047 UIAlertView *alert = [[[UIAlertView alloc]
6048 initWithTitle:UCLocalize("NOT_REPOSITORY")
6049 message:UCLocalize("NOT_REPOSITORY_EX")
6051 cancelButtonTitle:UCLocalize("OK")
6052 otherButtonTitles:nil
6055 [alert setContext:@"trivial"];
6059 [delegate_ setStatusBarShowsProgress:NO];
6060 [delegate_ removeProgressHUD:hud_];
6070 if (error_ != nil) {
6077 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6078 switch ([response statusCode]) {
6084 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6085 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6087 error_ = [error retain];
6088 [self _endConnection:connection];
6091 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6092 [self _endConnection:connection];
6095 - (NSString *) title { return UCLocalize("SOURCES"); }
6097 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6098 NSMutableURLRequest *request = [NSMutableURLRequest
6099 requestWithURL:[NSURL URLWithString:href]
6100 cachePolicy:NSURLRequestUseProtocolCachePolicy
6101 timeoutInterval:120.0
6104 [request setHTTPMethod:method];
6106 if (Machine_ != NULL)
6107 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6108 if (UniqueID_ != nil)
6109 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6111 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6113 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6116 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6117 NSString *context([alert context]);
6119 if ([context isEqualToString:@"source"]) {
6122 NSString *href = [[alert textField] text];
6124 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6126 if (![href hasSuffix:@"/"])
6127 href_ = [href stringByAppendingString:@"/"];
6130 href_ = [href_ retain];
6132 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6133 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6134 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6135 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6139 // XXX: this is stupid
6140 hud_ = [[delegate_ addProgressHUD] retain];
6141 [hud_ setText:UCLocalize("VERIFYING_URL")];
6150 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6151 } else if ([context isEqualToString:@"trivial"])
6152 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6153 else if ([context isEqualToString:@"urlerror"])
6154 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6155 else if ([context isEqualToString:@"warning"]) {
6170 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6174 - (id) initWithDatabase:(Database *)database {
6175 if ((self = [super init]) != nil) {
6176 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6177 [self updateButtonsForEditingStatus:NO animated:NO];
6179 database_ = database;
6180 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6182 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6183 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6184 [[self view] addSubview:list_];
6186 [list_ setDataSource:self];
6187 [list_ setDelegate:self];
6193 - (void) reloadData {
6195 if (!list.ReadMainList())
6198 [sources_ removeAllObjects];
6199 [sources_ addObjectsFromArray:[database_ sources]];
6201 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6204 int count([sources_ count]);
6206 for (int i = 0; i != count; i++) {
6207 if ([[sources_ objectAtIndex:i] record] == nil)
6212 [list_ setEditing:NO];
6213 [self updateButtonsForEditingStatus:NO animated:NO];
6217 - (void) addButtonClicked {
6218 /*[book_ pushPage:[[[AddSourceController alloc]
6223 UIAlertView *alert = [[[UIAlertView alloc]
6224 initWithTitle:UCLocalize("ENTER_APT_URL")
6227 cancelButtonTitle:UCLocalize("CANCEL")
6228 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6231 [alert setContext:@"source"];
6232 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6234 [alert setNumberOfRows:1];
6235 [alert addTextFieldWithValue:@"http://" label:@""];
6237 UITextInputTraits *traits = [[alert textField] textInputTraits];
6238 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6239 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6240 [traits setKeyboardType:UIKeyboardTypeURL];
6241 // XXX: UIReturnKeyDone
6242 [traits setReturnKeyType:UIReturnKeyNext];
6247 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6248 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6249 initWithTitle:UCLocalize("ADD")
6250 style:UIBarButtonItemStylePlain
6252 action:@selector(addButtonClicked)
6253 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6255 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6256 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6257 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6259 action:@selector(editButtonClicked)
6260 ] autorelease] animated:animated];
6262 if (IsWildcat_ && !editing)
6263 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6264 initWithTitle:UCLocalize("SETTINGS")
6265 style:UIBarButtonItemStylePlain
6267 action:@selector(settingsButtonClicked)
6271 - (void) settingsButtonClicked {
6272 [delegate_ showSettings];
6275 - (void) editButtonClicked {
6276 [list_ setEditing:![list_ isEditing] animated:YES];
6278 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6284 /* Installed Controller {{{ */
6285 @interface InstalledController : FilteredPackageController {
6289 - (id) initWithDatabase:(Database *)database;
6291 - (void) updateRoleButton;
6292 - (void) queueStatusDidChange;
6296 @implementation InstalledController
6302 - (NSString *) title { return UCLocalize("INSTALLED"); }
6304 - (id) initWithDatabase:(Database *)database {
6305 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6306 [self updateRoleButton];
6307 [self queueStatusDidChange];
6312 - (void) queueButtonClicked {
6317 - (void) queueStatusDidChange {
6321 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6322 initWithTitle:UCLocalize("QUEUE")
6323 style:UIBarButtonItemStyleDone
6325 action:@selector(queueButtonClicked)
6328 [[self navigationItem] setLeftBarButtonItem:nil];
6334 - (void) reloadData {
6335 [packages_ reloadData];
6338 - (void) updateRoleButton {
6339 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6340 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6341 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6342 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6344 action:@selector(roleButtonClicked)
6348 - (void) roleButtonClicked {
6349 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6350 [packages_ reloadData];
6353 [self updateRoleButton];
6356 - (void) setDelegate:(id)delegate {
6357 [super setDelegate:delegate];
6358 [packages_ setDelegate:delegate];
6364 /* Home Controller {{{ */
6365 @interface HomeController : CYBrowserController {
6370 @implementation HomeController
6372 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6373 [super _setMoreHeaders:request];
6376 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6377 if (UniqueID_ != nil)
6378 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6380 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6383 - (void) aboutButtonClicked {
6384 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6386 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6387 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6388 [alert setCancelButtonIndex:0];
6391 @"Copyright (C) 2008-2010\n"
6392 "Jay Freeman (saurik)\n"
6393 "saurik@saurik.com\n"
6394 "http://www.saurik.com/"
6400 - (void) viewWillAppear:(BOOL)animated {
6401 [super viewWillAppear:animated];
6402 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6405 - (void) viewWillDisappear:(BOOL)animated {
6406 [super viewWillDisappear:animated];
6407 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6411 if ((self = [super init]) != nil) {
6412 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6413 initWithTitle:UCLocalize("ABOUT")
6414 style:UIBarButtonItemStylePlain
6416 action:@selector(aboutButtonClicked)
6423 /* Manage Controller {{{ */
6424 @interface ManageController : CYBrowserController {
6427 - (void) queueStatusDidChange;
6430 @implementation ManageController
6433 if ((self = [super init]) != nil) {
6434 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6436 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6437 initWithTitle:UCLocalize("SETTINGS")
6438 style:UIBarButtonItemStylePlain
6440 action:@selector(settingsButtonClicked)
6443 [self queueStatusDidChange];
6447 - (void) settingsButtonClicked {
6448 [delegate_ showSettings];
6452 - (void) queueButtonClicked {
6456 - (void) applyLoadingTitle {
6457 // No "Loading" title.
6460 - (void) applyRightButton {
6465 - (void) queueStatusDidChange {
6467 if (!IsWildcat_ && Queuing_) {
6468 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6469 initWithTitle:UCLocalize("QUEUE")
6470 style:UIBarButtonItemStyleDone
6472 action:@selector(queueButtonClicked)
6475 [[self navigationItem] setRightBarButtonItem:nil];
6480 - (bool) isLoading {
6487 /* Refresh Bar {{{ */
6488 @interface RefreshBar : UINavigationBar {
6489 UIProgressIndicator *indicator_;
6490 UITextLabel *prompt_;
6491 UIProgressBar *progress_;
6492 UINavigationButton *cancel_;
6497 @implementation RefreshBar
6500 [indicator_ release];
6502 [progress_ release];
6507 - (void) positionViews {
6508 CGRect frame = [cancel_ frame];
6509 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6510 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6511 [cancel_ setFrame:frame];
6513 CGSize prgsize = {75, 100};
6515 [self frame].size.width - prgsize.width - 10,
6516 ([self frame].size.height - prgsize.height) / 2
6518 [progress_ setFrame:prgrect];
6520 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6521 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6522 CGRect indrect = {{indoffset, indoffset}, indsize};
6523 [indicator_ setFrame:indrect];
6525 CGSize prmsize = {215, indsize.height + 4};
6527 indoffset * 2 + indsize.width,
6528 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6530 [prompt_ setFrame:prmrect];
6533 - (void)setFrame:(CGRect)frame {
6534 [super setFrame:frame];
6536 [self positionViews];
6539 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6540 if ((self = [super initWithFrame:frame])) {
6541 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6543 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6544 [self setBarStyle:UIBarStyleBlack];
6546 UIBarStyle barstyle([self _barStyle:NO]);
6547 bool ugly(barstyle == UIBarStyleDefault);
6549 UIProgressIndicatorStyle style = ugly ?
6550 UIProgressIndicatorStyleMediumBrown :
6551 UIProgressIndicatorStyleMediumWhite;
6553 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6554 [indicator_ setStyle:style];
6555 [indicator_ startAnimation];
6556 [self addSubview:indicator_];
6558 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6559 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6560 [prompt_ setBackgroundColor:[UIColor clearColor]];
6561 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6562 [self addSubview:prompt_];
6564 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6565 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6566 [progress_ setStyle:0];
6567 [self addSubview:progress_];
6569 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6570 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6571 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6572 [cancel_ setBarStyle:barstyle];
6574 [self positionViews];
6579 [cancel_ removeFromSuperview];
6583 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6584 [progress_ setProgress:0];
6585 [self addSubview:cancel_];
6589 [cancel_ removeFromSuperview];
6592 - (void) setPrompt:(NSString *)prompt {
6593 [prompt_ setText:prompt];
6596 - (void) setProgress:(float)progress {
6597 [progress_ setProgress:progress];
6603 @class CYNavigationController;
6605 /* Cydia Tab Bar Controller {{{ */
6606 @interface CYTabBarController : UITabBarController {
6607 _transient Database *database_;
6612 @implementation CYTabBarController
6614 /* XXX: some logic should probably go here related to
6615 freeing the view controllers on tab change */
6617 - (void) reloadData {
6618 size_t count([[self viewControllers] count]);
6619 for (size_t i(0); i != count; ++i) {
6620 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6625 - (id) initWithDatabase:(Database *)database {
6626 if ((self = [super init]) != nil) {
6627 database_ = database;
6634 /* Cydia Navigation Controller {{{ */
6635 @interface CYNavigationController : UINavigationController {
6636 _transient Database *database_;
6637 _transient id<UINavigationControllerDelegate> delegate_;
6640 - (id) initWithDatabase:(Database *)database;
6641 - (void) reloadData;
6646 @implementation CYNavigationController
6648 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6649 // Inherit autorotation settings for modal parents.
6650 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6651 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6653 return [super shouldAutorotateToInterfaceOrientation:orientation];
6661 - (void) reloadData {
6662 size_t count([[self viewControllers] count]);
6663 for (size_t i(0); i != count; ++i) {
6664 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6669 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6670 delegate_ = delegate;
6673 - (id) initWithDatabase:(Database *)database {
6674 if ((self = [super init]) != nil) {
6675 database_ = database;
6681 /* Cydia:// Protocol {{{ */
6682 @interface CydiaURLProtocol : NSURLProtocol {
6687 @implementation CydiaURLProtocol
6689 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6690 NSURL *url([request URL]);
6693 NSString *scheme([[url scheme] lowercaseString]);
6694 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6699 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6703 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6704 id<NSURLProtocolClient> client([self client]);
6706 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6708 NSData *data(UIImagePNGRepresentation(icon));
6710 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6711 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6712 [client URLProtocol:self didLoadData:data];
6713 [client URLProtocolDidFinishLoading:self];
6717 - (void) startLoading {
6718 id<NSURLProtocolClient> client([self client]);
6719 NSURLRequest *request([self request]);
6721 NSURL *url([request URL]);
6722 NSString *href([url absoluteString]);
6724 NSString *path([href substringFromIndex:8]);
6725 NSRange slash([path rangeOfString:@"/"]);
6728 if (slash.location == NSNotFound) {
6732 command = [path substringToIndex:slash.location];
6733 path = [path substringFromIndex:(slash.location + 1)];
6736 Database *database([Database sharedInstance]);
6738 if ([command isEqualToString:@"package-icon"]) {
6741 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6742 Package *package([database packageWithName:path]);
6745 UIImage *icon([package icon]);
6746 [self _returnPNGWithImage:icon forRequest:request];
6747 } else if ([command isEqualToString:@"source-icon"]) {
6750 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6751 NSString *source(Simplify(path));
6752 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6754 icon = [UIImage applicationImageNamed:@"unknown.png"];
6755 [self _returnPNGWithImage:icon forRequest:request];
6756 } else if ([command isEqualToString:@"uikit-image"]) {
6759 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6760 UIImage *icon(_UIImageWithName(path));
6761 [self _returnPNGWithImage:icon forRequest:request];
6762 } else if ([command isEqualToString:@"section-icon"]) {
6765 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6766 NSString *section(Simplify(path));
6767 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6769 icon = [UIImage applicationImageNamed:@"unknown.png"];
6770 [self _returnPNGWithImage:icon forRequest:request];
6772 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6776 - (void) stopLoading {
6782 /* Sections Controller {{{ */
6783 @interface SectionsController : CYViewController <
6784 UITableViewDataSource,
6787 _transient Database *database_;
6788 NSMutableArray *sections_;
6789 NSMutableArray *filtered_;
6795 - (id) initWithDatabase:(Database *)database;
6796 - (void) reloadData;
6799 - (void) editButtonClicked;
6803 @implementation SectionsController
6806 [list_ setDataSource:nil];
6807 [list_ setDelegate:nil];
6809 [sections_ release];
6810 [filtered_ release];
6812 [accessory_ release];
6816 - (void) viewDidAppear:(BOOL)animated {
6817 [super viewDidAppear:animated];
6818 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6821 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6822 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6826 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6827 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6830 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6834 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6835 static NSString *reuseIdentifier = @"SectionCell";
6837 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6839 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6841 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6846 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6850 Section *section = [self sectionAtIndexPath:indexPath];
6851 NSString *name = [section name];
6854 if ([indexPath row] == 0) {
6857 title = UCLocalize("ALL_PACKAGES");
6860 name = [NSString stringWithString:name];
6861 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6864 title = UCLocalize("NO_SECTION");
6868 FilteredPackageController *table = [[[FilteredPackageController alloc]
6869 initWithDatabase:database_
6871 filter:@selector(isVisibleInSection:)
6875 [table setDelegate:delegate_];
6877 [[self navigationController] pushViewController:table animated:YES];
6880 - (NSString *) title { return UCLocalize("SECTIONS"); }
6882 - (id) initWithDatabase:(Database *)database {
6883 if ((self = [super init]) != nil) {
6884 database_ = database;
6886 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6888 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6889 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6891 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6892 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6893 [list_ setRowHeight:45.0f];
6894 [[self view] addSubview:list_];
6896 [list_ setDataSource:self];
6897 [list_ setDelegate:self];
6903 - (void) reloadData {
6904 NSArray *packages = [database_ packages];
6906 [sections_ removeAllObjects];
6907 [filtered_ removeAllObjects];
6909 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6912 for (Package *package in packages) {
6913 NSString *name([package section]);
6914 NSString *key(name == nil ? @"" : name);
6918 _profile(SectionsView$reloadData$Section)
6919 section = [sections objectForKey:key];
6920 if (section == nil) {
6921 _profile(SectionsView$reloadData$Section$Allocate)
6922 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6923 [sections setObject:section forKey:key];
6928 [section addToCount];
6930 _profile(SectionsView$reloadData$Filter)
6931 if (![package valid] || ![package visible])
6939 [sections_ addObjectsFromArray:[sections allValues]];
6941 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6943 for (Section *section in sections_) {
6944 size_t count([section row]);
6948 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6949 [section setCount:count];
6950 [filtered_ addObject:section];
6953 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6954 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
6955 style:UIBarButtonItemStylePlain
6957 action:@selector(editButtonClicked)
6958 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6964 - (void) resetView {
6966 [self editButtonClicked];
6969 - (void) editButtonClicked {
6970 if ((editing_ = !editing_))
6973 [delegate_ updateData];
6975 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6976 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6977 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6980 - (UIView *) accessoryView {
6986 /* Changes Controller {{{ */
6987 @interface ChangesController : CYViewController <
6988 UITableViewDataSource,
6991 _transient Database *database_;
6992 CFMutableArrayRef packages_;
6993 NSMutableArray *sections_;
6996 BOOL hasSentFirstLoad_;
6999 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
7000 - (void) reloadData;
7004 @implementation ChangesController
7007 [list_ setDelegate:nil];
7008 [list_ setDataSource:nil];
7010 CFRelease(packages_);
7012 [sections_ release];
7017 - (void) viewDidAppear:(BOOL)animated {
7018 [super viewDidAppear:animated];
7019 if (!hasSentFirstLoad_) {
7020 hasSentFirstLoad_ = YES;
7021 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7023 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7027 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7028 NSInteger count([sections_ count]);
7029 return count == 0 ? 1 : count;
7032 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7033 if ([sections_ count] == 0)
7035 return [[sections_ objectAtIndex:section] name];
7038 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7039 if ([sections_ count] == 0)
7041 return [[sections_ objectAtIndex:section] count];
7044 - (Package *) packageAtIndex:(NSUInteger)index {
7045 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7048 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7049 Section *section([sections_ objectAtIndex:[path section]]);
7050 NSInteger row([path row]);
7051 return [self packageAtIndex:([section row] + row)];
7054 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7055 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7057 cell = [[[PackageCell alloc] init] autorelease];
7058 [cell setPackage:[self packageAtIndexPath:path]];
7062 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7063 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7066 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7067 Package *package([self packageAtIndexPath:path]);
7068 PackageController *view([delegate_ packageController]);
7069 [view setDelegate:delegate_];
7070 [view setPackage:package];
7071 [[self navigationController] pushViewController:view animated:YES];
7075 - (void) refreshButtonClicked {
7076 [delegate_ beginUpdate];
7077 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7080 - (void) upgradeButtonClicked {
7081 [delegate_ distUpgrade];
7084 - (NSString *) title { return UCLocalize("CHANGES"); }
7086 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7087 if ((self = [super init]) != nil) {
7088 database_ = database;
7089 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7091 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7093 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7095 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7096 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7097 [list_ setRowHeight:73.0f];
7098 [[self view] addSubview:list_];
7100 [list_ setDataSource:self];
7101 [list_ setDelegate:self];
7103 delegate_ = delegate;
7107 - (void) _reloadPackages:(NSArray *)packages {
7109 for (Package *package in packages)
7110 if ([package upgradableAndEssential:YES] || [package visible])
7111 CFArrayAppendValue(packages_, package);
7114 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7118 - (void) reloadData {
7119 NSArray *packages = [database_ packages];
7121 CFArrayRemoveAllValues(packages_);
7123 [sections_ removeAllObjects];
7126 UIProgressHUD *hud([delegate_ addProgressHUD]);
7127 [hud setText:UCLocalize("LOADING")];
7128 //NSLog(@"HUD:%@::%@", delegate_, hud);
7129 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7130 [delegate_ removeProgressHUD:hud];
7132 [self _reloadPackages:packages];
7135 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7136 Section *ignored = nil;
7137 Section *section = nil;
7141 bool unseens = false;
7143 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7145 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7146 Package *package = [self packageAtIndex:offset];
7148 BOOL uae = [package upgradableAndEssential:YES];
7152 time_t seen([package seen]);
7154 if (section == nil || last != seen) {
7158 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7161 _profile(ChangesController$reloadData$Allocate)
7162 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7163 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7164 [sections_ addObject:section];
7168 [section addToCount];
7169 } else if ([package ignored]) {
7170 if (ignored == nil) {
7171 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7173 [ignored addToCount];
7176 [upgradable addToCount];
7181 CFRelease(formatter);
7184 Section *last = [sections_ lastObject];
7185 size_t count = [last count];
7186 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7187 [sections_ removeLastObject];
7190 if ([ignored count] != 0)
7191 [sections_ insertObject:ignored atIndex:0];
7193 [sections_ insertObject:upgradable atIndex:0];
7198 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7199 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7200 style:UIBarButtonItemStylePlain
7202 action:@selector(upgradeButtonClicked)
7205 if (![delegate_ updating])
7206 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7207 initWithTitle:UCLocalize("REFRESH")
7208 style:UIBarButtonItemStylePlain
7210 action:@selector(refreshButtonClicked)
7216 /* Search Controller {{{ */
7217 @interface SearchController : FilteredPackageController <
7220 UISearchBar *search_;
7223 - (id) initWithDatabase:(Database *)database;
7224 - (void) reloadData;
7228 @implementation SearchController
7235 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7236 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7237 [search_ resignFirstResponder];
7241 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7242 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7246 - (NSString *) title { return nil; }
7248 - (id) initWithDatabase:(Database *)database {
7249 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7252 - (void)viewDidAppear:(BOOL)animated {
7253 [super viewDidAppear:animated];
7255 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7256 [search_ layoutSubviews];
7257 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7258 UITextField *textField = [search_ searchField];
7259 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7260 [search_ setDelegate:self];
7261 [textField setEnablesReturnKeyAutomatically:NO];
7262 [[self navigationItem] setTitleView:textField];
7266 - (void) _reloadData {
7269 - (void) reloadData {
7270 _profile(SearchController$reloadData)
7271 [packages_ reloadData];
7274 [packages_ resetCursor];
7277 - (void) didSelectPackage:(Package *)package {
7278 [search_ resignFirstResponder];
7279 [super didSelectPackage:package];
7284 /* Settings Controller {{{ */
7285 @interface SettingsController : CYViewController <
7286 UITableViewDataSource,
7289 _transient Database *database_;
7292 UITableView *table_;
7293 UISwitch *subscribedSwitch_;
7294 UISwitch *ignoredSwitch_;
7295 UITableViewCell *subscribedCell_;
7296 UITableViewCell *ignoredCell_;
7299 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7303 @implementation SettingsController
7307 if (package_ != nil)
7310 [subscribedSwitch_ release];
7311 [ignoredSwitch_ release];
7312 [subscribedCell_ release];
7313 [ignoredCell_ release];
7318 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7319 if (package_ == nil)
7325 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7326 if (package_ == nil)
7332 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7333 return UCLocalize("SHOW_ALL_CHANGES_EX");
7336 - (void) onSubscribed:(id)control {
7337 bool value([control isOn]);
7338 if (package_ == nil)
7340 if ([package_ setSubscribed:value])
7341 [delegate_ updateData];
7344 - (void) onIgnored:(id)control {
7345 // TODO: set Held state - possibly call out to dpkg, etc.
7348 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7349 if (package_ == nil)
7352 switch ([indexPath row]) {
7353 case 0: return subscribedCell_;
7354 case 1: return ignoredCell_;
7362 - (NSString *) title { return UCLocalize("SETTINGS"); }
7364 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7365 if ((self = [super init])) {
7366 database_ = database;
7367 name_ = [package retain];
7369 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7371 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7372 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7373 [[self view] addSubview:table_];
7375 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7376 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7377 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7379 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7380 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7381 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7383 subscribedCell_ = [[UITableViewCell alloc] init];
7384 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7385 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7386 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7388 ignoredCell_ = [[UITableViewCell alloc] init];
7389 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7390 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7391 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7393 [table_ setDataSource:self];
7394 [table_ setDelegate:self];
7399 - (void) reloadData {
7400 if (package_ != nil)
7401 [package_ autorelease];
7402 package_ = [database_ packageWithName:name_];
7403 if (package_ != nil) {
7405 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7406 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7409 [table_ reloadData];
7414 /* Signature Controller {{{ */
7415 @interface SignatureController : CYBrowserController {
7416 _transient Database *database_;
7420 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7424 @implementation SignatureController
7431 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7433 [super webView:view didClearWindowObject:window forFrame:frame];
7436 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7437 if ((self = [super init]) != nil) {
7438 database_ = database;
7439 package_ = [package retain];
7444 - (void) reloadData {
7445 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7451 /* Role Controller {{{ */
7452 @interface RoleController : CYViewController <
7453 UITableViewDataSource,
7456 _transient Database *database_;
7457 // XXX: ok, "roledelegate_"?...
7458 _transient id roledelegate_;
7459 UITableView *table_;
7460 UISegmentedControl *segment_;
7464 - (void) showDoneButton;
7465 - (void) resizeSegmentedControl;
7469 @implementation RoleController
7473 [container_ release];
7478 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7479 if ((self = [super init])) {
7480 database_ = database;
7481 roledelegate_ = delegate;
7483 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7485 NSArray *items = [NSArray arrayWithObjects:
7487 UCLocalize("HACKER"),
7488 UCLocalize("DEVELOPER"),
7490 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7491 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7492 [container_ addSubview:segment_];
7495 if ([Role_ isEqualToString:@"User"]) index = 0;
7496 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7497 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7499 [segment_ setSelectedSegmentIndex:index];
7500 [self showDoneButton];
7503 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7504 [self resizeSegmentedControl];
7506 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7507 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7508 [table_ setDelegate:self];
7509 [table_ setDataSource:self];
7510 [[self view] addSubview:table_];
7511 [table_ reloadData];
7515 - (void) resizeSegmentedControl {
7516 CGFloat width = [[self view] frame].size.width;
7517 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7520 - (void) viewWillAppear:(BOOL)animated {
7521 [super viewWillAppear:animated];
7523 [self resizeSegmentedControl];
7526 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7527 [self resizeSegmentedControl];
7530 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7531 [self resizeSegmentedControl];
7535 NSString *role(nil);
7537 switch ([segment_ selectedSegmentIndex]) {
7538 case 0: role = @"User"; break;
7539 case 1: role = @"Hacker"; break;
7540 case 2: role = @"Developer"; break;
7545 if (![role isEqualToString:Role_]) {
7546 bool rolling(Role_ == nil);
7549 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7553 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7557 [roledelegate_ loadData];
7559 [roledelegate_ updateData];
7563 - (void) segmentChanged:(UISegmentedControl *)control {
7564 [self showDoneButton];
7567 - (void) saveAndClose {
7570 [[self navigationItem] setRightBarButtonItem:nil];
7571 [[self navigationController] dismissModalViewControllerAnimated:YES];
7574 - (void) doneButtonClicked {
7575 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7576 [spinner startAnimating];
7577 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7578 [[self navigationItem] setRightBarButtonItem:spinItem];
7580 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7583 - (void) showDoneButton {
7584 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7585 initWithTitle:UCLocalize("DONE")
7586 style:UIBarButtonItemStyleDone
7588 action:@selector(doneButtonClicked)
7589 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7592 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7593 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7597 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7601 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7602 return nil; // This method is required by the protocol.
7605 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7607 return UCLocalize("ROLE_EX");
7609 return [NSString stringWithFormat:
7610 @"%@: %@\n%@: %@\n%@: %@",
7611 UCLocalize("USER"), UCLocalize("USER_EX"),
7612 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7613 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7618 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7619 return section == 3 ? 44.0f : 0;
7622 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7623 return section == 3 ? container_ : nil;
7628 /* Stash Controller {{{ */
7629 @interface CYStashController : CYViewController {
7630 // XXX: just delete these things
7631 _transient UIActivityIndicatorView *spinner_;
7632 _transient UILabel *status_;
7633 _transient UILabel *caption_;
7637 @implementation CYStashController
7639 if ((self = [super init])) {
7640 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7642 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7643 CGRect spinrect = [spinner_ frame];
7644 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7645 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7646 [spinner_ setFrame:spinrect];
7647 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7648 [[self view] addSubview:spinner_];
7649 [spinner_ startAnimating];
7652 captrect.size.width = [[self view] frame].size.width;
7653 captrect.size.height = 40.0f;
7654 captrect.origin.x = 0;
7655 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7656 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7657 [caption_ setText:@"Initializing Filesystem"];
7658 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7659 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7660 [caption_ setTextColor:[UIColor whiteColor]];
7661 [caption_ setBackgroundColor:[UIColor clearColor]];
7662 [caption_ setShadowColor:[UIColor blackColor]];
7663 [caption_ setTextAlignment:UITextAlignmentCenter];
7664 [[self view] addSubview:caption_];
7667 statusrect.size.width = [[self view] frame].size.width;
7668 statusrect.size.height = 30.0f;
7669 statusrect.origin.x = 0;
7670 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7671 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7672 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7673 [status_ setText:@"(Cydia will exit when complete.)"];
7674 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7675 [status_ setTextColor:[UIColor whiteColor]];
7676 [status_ setBackgroundColor:[UIColor clearColor]];
7677 [status_ setShadowColor:[UIColor blackColor]];
7678 [status_ setTextAlignment:UITextAlignmentCenter];
7679 [[self view] addSubview:status_];
7683 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7684 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7689 /* Cydia Container {{{ */
7690 @interface CYContainer : UIViewController <ProgressDelegate> {
7691 _transient Database *database_;
7692 RefreshBar *refreshbar_;
7696 // XXX: ok, "updatedelegate_"?...
7697 _transient NSObject<CydiaDelegate> *updatedelegate_;
7698 // XXX: can't we query for this variable when we need it?
7699 _transient UITabBarController *root_;
7702 - (void) setTabBarController:(UITabBarController *)controller;
7704 - (void) dropBar:(BOOL)animated;
7705 - (void) beginUpdate;
7706 - (void) raiseBar:(BOOL)animated;
7711 @implementation CYContainer
7713 - (BOOL) _reallyWantsFullScreenLayout {
7717 // NOTE: UIWindow only sends the top controller these messages,
7718 // So we have to forward them on.
7720 - (void) viewDidAppear:(BOOL)animated {
7721 [super viewDidAppear:animated];
7722 [root_ viewDidAppear:animated];
7725 - (void) viewWillAppear:(BOOL)animated {
7726 [super viewWillAppear:animated];
7727 [root_ viewWillAppear:animated];
7730 - (void) viewDidDisappear:(BOOL)animated {
7731 [super viewDidDisappear:animated];
7732 [root_ viewDidDisappear:animated];
7735 - (void) viewWillDisappear:(BOOL)animated {
7736 [super viewWillDisappear:animated];
7737 [root_ viewWillDisappear:animated];
7740 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7741 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7744 - (void) setTabBarController:(UITabBarController *)controller {
7746 [[self view] addSubview:[root_ view]];
7749 - (void) setUpdate:(NSDate *)date {
7753 - (void) beginUpdate {
7755 [refreshbar_ start];
7760 detachNewThreadSelector:@selector(performUpdate)
7766 - (void) performUpdate { _pooled
7768 status.setDelegate(self);
7769 [database_ updateWithStatus:status];
7772 performSelectorOnMainThread:@selector(completeUpdate)
7778 - (void) completeUpdate {
7783 [self raiseBar:YES];
7785 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7788 - (void) cancelUpdate {
7790 [self raiseBar:YES];
7792 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7795 - (void) cancelPressed {
7796 [self cancelUpdate];
7803 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7804 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7807 - (void) startProgress {
7810 - (void) setProgressTitle:(NSString *)title {
7812 performSelectorOnMainThread:@selector(_setProgressTitle:)
7818 - (bool) isCancelling:(size_t)received {
7822 - (void) setProgressPercent:(float)percent {
7824 performSelectorOnMainThread:@selector(_setProgressPercent:)
7825 withObject:[NSNumber numberWithFloat:percent]
7830 - (void) addProgressOutput:(NSString *)output {
7832 performSelectorOnMainThread:@selector(_addProgressOutput:)
7838 - (void) _setProgressTitle:(NSString *)title {
7839 [refreshbar_ setPrompt:title];
7842 - (void) _setProgressPercent:(NSNumber *)percent {
7843 [refreshbar_ setProgress:[percent floatValue]];
7846 - (void) _addProgressOutput:(NSString *)output {
7849 - (void) setUpdateDelegate:(id)delegate {
7850 updatedelegate_ = delegate;
7853 - (CGFloat) statusBarHeight {
7854 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7855 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7857 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7861 - (void) dropBar:(BOOL)animated {
7866 [[self view] addSubview:refreshbar_];
7868 CGFloat sboffset = [self statusBarHeight];
7870 CGRect barframe = [refreshbar_ frame];
7871 barframe.origin.y = sboffset;
7872 [refreshbar_ setFrame:barframe];
7875 [UIView beginAnimations:nil context:NULL];
7876 CGRect viewframe = [[root_ view] frame];
7877 viewframe.origin.y += barframe.size.height + sboffset;
7878 viewframe.size.height -= barframe.size.height + sboffset;
7879 [[root_ view] setFrame:viewframe];
7881 [UIView commitAnimations];
7883 // Ensure bar has the proper width for our view, it might have changed
7884 barframe.size.width = viewframe.size.width;
7885 [refreshbar_ setFrame:barframe];
7887 // XXX: fix Apple's layout bug
7888 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7891 - (void) raiseBar:(BOOL)animated {
7896 [refreshbar_ removeFromSuperview];
7898 CGFloat sboffset = [self statusBarHeight];
7901 [UIView beginAnimations:nil context:NULL];
7902 CGRect barframe = [refreshbar_ frame];
7903 CGRect viewframe = [[root_ view] frame];
7904 viewframe.origin.y -= barframe.size.height + sboffset;
7905 viewframe.size.height += barframe.size.height + sboffset;
7906 [[root_ view] setFrame:viewframe];
7908 [UIView commitAnimations];
7910 // XXX: fix Apple's layout bug
7911 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7914 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7915 // XXX: fix Apple's layout bug
7916 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7919 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7925 // XXX: fix Apple's layout bug
7926 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7929 - (void) statusBarFrameChanged:(NSNotification *)notification {
7937 [refreshbar_ release];
7938 [[NSNotificationCenter defaultCenter] removeObserver:self];
7942 - (id) initWithDatabase:(Database *)database {
7943 if ((self = [super init]) != nil) {
7944 database_ = database;
7946 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7947 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7949 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7966 @interface Cydia : UIApplication <
7967 ConfirmationControllerDelegate,
7968 ProgressControllerDelegate,
7970 UINavigationControllerDelegate,
7971 UITabBarControllerDelegate
7973 // XXX: evaluate all fields for _transient
7976 CYContainer *container_;
7977 CYTabBarController *tabbar_;
7979 NSMutableArray *essential_;
7980 NSMutableArray *broken_;
7982 Database *database_;
7988 SectionsController *sections_;
7989 ChangesController *changes_;
7990 ManageController *manage_;
7991 SearchController *search_;
7992 SourceTable *sources_;
7993 InstalledController *installed_;
7996 CYStashController *stash_;
8001 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
8002 - (void) setPage:(CYViewController *)page;
8005 // XXX: I hate prototypes
8006 - (id) queueBadgeController;
8010 static _finline void _setHomePage(Cydia *self) {
8011 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
8014 @implementation Cydia
8016 - (void) beginUpdate {
8017 [container_ beginUpdate];
8021 return [container_ updating];
8024 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8029 if ([broken_ count] != 0) {
8030 int count = [broken_ count];
8032 UIAlertView *alert = [[[UIAlertView alloc]
8033 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8034 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8036 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8037 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8040 [alert setContext:@"fixhalf"];
8042 } else if (!Ignored_ && [essential_ count] != 0) {
8043 int count = [essential_ count];
8045 UIAlertView *alert = [[[UIAlertView alloc]
8046 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8047 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8049 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8050 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8053 [alert setContext:@"upgrade"];
8058 - (void) _saveConfig {
8064 NSString *error(nil);
8066 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8068 NSError *error(nil);
8069 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8070 NSLog(@"failure to save metadata data: %@", error);
8075 NSLog(@"failure to serialize metadata: %@", error);
8080 - (void) _updateData {
8083 /* XXX: this is just stupid */
8084 if (tag_ != 1 && sections_ != nil)
8085 [sections_ reloadData];
8086 if (tag_ != 2 && changes_ != nil)
8087 [changes_ reloadData];
8088 if (tag_ != 4 && search_ != nil)
8089 [search_ reloadData];
8091 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8093 [queueDelegate_ queueStatusDidChange];
8094 [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8097 - (int)indexOfTabWithTag:(int)tag {
8099 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8100 if ([[controller tabBarItem] tag] == tag)
8108 - (void) _refreshIfPossible {
8109 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8111 bool recently = false;
8112 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8113 if (update != nil) {
8114 NSTimeInterval interval([update timeIntervalSinceNow]);
8115 if (interval <= 0 && interval > -(15*60))
8119 // Don't automatic refresh if:
8120 // - We already refreshed recently.
8121 // - We already auto-refreshed this launch.
8122 // - Auto-refresh is disabled.
8123 if (recently || loaded_ || ManualRefresh) {
8124 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8126 // If we are cancelling due to ManualRefresh or a recent refresh
8127 // we need to make sure it knows it's already loaded.
8131 // We are going to load, so remember that.
8135 SCNetworkReachabilityFlags flags; {
8136 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8137 SCNetworkReachabilityGetFlags(reachability, &flags);
8138 CFRelease(reachability);
8141 // XXX: this elaborate mess is what Apple is using to determine this? :(
8142 // XXX: do we care if the user has to intervene? maybe that's ok?
8144 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8145 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8146 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8147 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8148 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8149 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8153 // If we can reach the server, auto-refresh!
8155 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8160 - (void) refreshIfPossible {
8161 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8164 - (void) _reloadData {
8165 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8166 [hud setText:UCLocalize("RELOADING_DATA")];
8168 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8171 [self removeProgressHUD:hud];
8175 [essential_ removeAllObjects];
8176 [broken_ removeAllObjects];
8178 NSArray *packages([database_ packages]);
8179 for (Package *package in packages) {
8181 [broken_ addObject:package];
8182 if ([package upgradableAndEssential:NO]) {
8183 if ([package essential])
8184 [essential_ addObject:package];
8189 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8191 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8192 [changesItem setBadgeValue:badge];
8193 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8195 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8196 [self setApplicationBadge:badge];
8198 [self setApplicationBadgeString:badge];
8200 [changesItem setBadgeValue:nil];
8201 [changesItem setAnimatedBadge:NO];
8203 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8204 [self removeApplicationBadge];
8205 else // XXX: maybe use setApplicationBadgeString also?
8206 [self setApplicationIconBadgeNumber:0];
8211 [self refreshIfPossible];
8214 - (void) updateData {
8223 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8224 _assert(file != NULL);
8226 for (NSString *key in [Sources_ allKeys]) {
8227 NSDictionary *source([Sources_ objectForKey:key]);
8229 fprintf(file, "%s %s %s\n",
8230 [[source objectForKey:@"Type"] UTF8String],
8231 [[source objectForKey:@"URI"] UTF8String],
8232 [[source objectForKey:@"Distribution"] UTF8String]
8240 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8241 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8243 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8244 [container_ presentModalViewController:navigation animated:YES];
8247 detachNewThreadSelector:@selector(update_)
8250 title:UCLocalize("UPDATING_SOURCES")
8254 - (void) reloadData {
8255 @synchronized (self) {
8261 pkgProblemResolver *resolver = [database_ resolver];
8263 resolver->InstallProtect();
8264 if (!resolver->Resolve(true))
8268 - (CGRect) popUpBounds {
8269 return [[tabbar_ view] bounds];
8273 if (![database_ prepare])
8276 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8277 [page setDelegate:self];
8278 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8279 [confirm_ setDelegate:self];
8282 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8283 [container_ presentModalViewController:confirm_ animated:YES];
8289 @synchronized (self) {
8294 - (void) clearPackage:(Package *)package {
8295 @synchronized (self) {
8302 - (void) installPackages:(NSArray *)packages {
8303 @synchronized (self) {
8304 for (Package *package in packages)
8311 - (void) installPackage:(Package *)package {
8312 @synchronized (self) {
8319 - (void) removePackage:(Package *)package {
8320 @synchronized (self) {
8327 - (void) distUpgrade {
8328 @synchronized (self) {
8329 if (![database_ upgrade])
8336 @synchronized (self) {
8341 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8344 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8346 if (navigation != nil) {
8347 [navigation pushViewController:progress animated:YES];
8349 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8351 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8352 [container_ presentModalViewController:navigation animated:YES];
8356 detachNewThreadSelector:@selector(perform)
8359 title:UCLocalize("RUNNING")
8363 - (void) progressControllerIsComplete:(ProgressController *)progress {
8367 - (void) setPage:(CYViewController *)page {
8368 [page setDelegate:self];
8370 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8371 [navController setViewControllers:[NSArray arrayWithObject:page]];
8372 for (CYNavigationController *page in [tabbar_ viewControllers])
8373 if (page != navController)
8374 [page setViewControllers:nil];
8377 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8378 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8379 [browser loadURL:url];
8383 - (SectionsController *) sectionsController {
8384 if (sections_ == nil)
8385 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8389 - (ChangesController *) changesController {
8390 if (changes_ == nil)
8391 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8395 - (ManageController *) manageController {
8396 if (manage_ == nil) {
8397 manage_ = (ManageController *) [[self
8398 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8399 withClass:[ManageController class]
8402 queueDelegate_ = manage_;
8407 - (SearchController *) searchController {
8409 search_ = [[SearchController alloc] initWithDatabase:database_];
8413 - (SourceTable *) sourcesController {
8414 if (sources_ == nil)
8415 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8419 - (InstalledController *) installedController {
8420 if (installed_ == nil) {
8421 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8423 queueDelegate_ = installed_;
8428 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8429 int tag = [[viewController tabBarItem] tag];
8431 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8433 } else if (tag_ == 1) {
8434 [[self sectionsController] resetView];
8438 case kCydiaTag: _setHomePage(self); break;
8440 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8441 case kChangesTag: [self setPage:[self changesController]]; break;
8442 case kManageTag: [self setPage:[self manageController]]; break;
8443 case kInstalledTag: [self setPage:[self installedController]]; break;
8444 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8445 case kSearchTag: [self setPage:[self searchController]]; break;
8453 - (void) showSettings {
8454 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8455 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8457 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8458 [container_ presentModalViewController:nav animated:YES];
8461 - (void) setPackageController:(PackageController *)view {
8463 [view setPackage:nil];
8467 - (PackageController *) _packageController {
8468 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8471 - (PackageController *) packageController {
8472 return [self _packageController];
8475 // Returns the navigation controller for the queuing badge.
8476 - (id) queueBadgeController {
8477 int index = [self indexOfTabWithTag:kManageTag];
8479 index = [self indexOfTabWithTag:kInstalledTag];
8481 return [[tabbar_ viewControllers] objectAtIndex:index];
8484 - (void) cancelAndClear:(bool)clear {
8485 @synchronized (self) {
8497 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8498 NSString *context([alert context]);
8500 if ([context isEqualToString:@"fixhalf"]) {
8501 if (button == [alert firstOtherButtonIndex]) {
8502 @synchronized (self) {
8503 for (Package *broken in broken_) {
8506 NSString *id = [broken id];
8507 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8508 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8509 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8510 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8516 } else if (button == [alert cancelButtonIndex]) {
8517 [broken_ removeAllObjects];
8521 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8522 } else if ([context isEqualToString:@"upgrade"]) {
8523 if (button == [alert firstOtherButtonIndex]) {
8524 @synchronized (self) {
8525 for (Package *essential in essential_)
8526 [essential install];
8531 } else if (button == [alert firstOtherButtonIndex] + 1) {
8533 } else if (button == [alert cancelButtonIndex]) {
8537 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8541 - (void) system:(NSString *)command { _pooled
8542 system([command UTF8String]);
8545 - (void) applicationWillSuspend {
8547 [super applicationWillSuspend];
8550 - (BOOL) hudIsShowing {
8551 return (hudcount_ > 0);
8554 - (void) applicationSuspend:(__GSEvent *)event {
8555 // Use external process status API internally.
8556 // This is probably a really bad idea.
8557 uint64_t status = 0;
8559 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8560 notify_get_state(notify_token, &status);
8561 notify_cancel(notify_token);
8564 if (![self hudIsShowing] && status == 0)
8565 [super applicationSuspend:event];
8568 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8569 if (![self hudIsShowing])
8570 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8573 - (void) _setSuspended:(BOOL)value {
8574 if (![self hudIsShowing])
8575 [super _setSuspended:value];
8578 - (UIProgressHUD *) addProgressHUD {
8579 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8580 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8582 [window_ setUserInteractionEnabled:NO];
8585 UIViewController *target = container_;
8586 while ([target modalViewController] != nil) target = [target modalViewController];
8587 [[target view] addSubview:hud];
8593 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8595 [hud removeFromSuperview];
8596 [window_ setUserInteractionEnabled:YES];
8600 - (CYViewController *) pageForPackage:(NSString *)name {
8601 if (Package *package = [database_ packageWithName:name]) {
8602 PackageController *view([self packageController]);
8603 [view setPackage:package];
8606 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8607 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8608 return [self _pageForURL:url withClass:[CYBrowserController class]];
8612 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8616 NSString *href([url absoluteString]);
8617 if ([href hasPrefix:@"apptapp://package/"])
8618 return [self pageForPackage:[href substringFromIndex:18]];
8620 NSString *scheme([[url scheme] lowercaseString]);
8621 if (![scheme isEqualToString:@"cydia"])
8623 NSString *path([url absoluteString]);
8624 if ([path length] < 8)
8626 path = [path substringFromIndex:8];
8627 if (![path hasPrefix:@"/"])
8628 path = [@"/" stringByAppendingString:path];
8630 if ([path isEqualToString:@"/add-source"])
8631 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8632 else if ([path isEqualToString:@"/storage"])
8633 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8634 else if ([path isEqualToString:@"/sources"])
8635 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8636 else if ([path isEqualToString:@"/packages"])
8637 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8638 else if ([path hasPrefix:@"/url/"])
8639 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8640 else if ([path hasPrefix:@"/launch/"])
8641 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8642 else if ([path hasPrefix:@"/package-settings/"])
8643 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8644 else if ([path hasPrefix:@"/package-signature/"])
8645 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8646 else if ([path hasPrefix:@"/package/"])
8647 return [self pageForPackage:[path substringFromIndex:9]];
8648 else if ([path hasPrefix:@"/files/"]) {
8649 NSString *name = [path substringFromIndex:7];
8651 if (Package *package = [database_ packageWithName:name]) {
8652 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8653 [files setPackage:package];
8661 - (BOOL) openCydiaURL:(NSURL *)url {
8662 CYViewController *page = nil;
8665 NSLog(@"open url: %@", url);
8667 if ((page = [self pageForURL:url hasTag:&tag])) {
8668 [self setPage:page];
8670 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8676 - (void) applicationOpenURL:(NSURL *)url {
8677 [super applicationOpenURL:url];
8678 NSLog(@"first: %@", url);
8679 if (!loaded_) starturl_ = [url retain];
8680 else [self openCydiaURL:url];
8683 - (void) applicationWillResignActive:(UIApplication *)application {
8684 // Stop refreshing if you get a phone call or lock the device.
8685 if ([container_ updating])
8686 [container_ cancelUpdate];
8688 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8689 [super applicationWillResignActive:application];
8692 - (void) addStashController {
8693 stash_ = [[CYStashController alloc] init];
8694 [window_ addSubview:[stash_ view]];
8697 - (void) removeStashController {
8698 [[stash_ view] removeFromSuperview];
8703 [self setIdleTimerDisabled:YES];
8705 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8706 [self setStatusBarShowsProgress:YES];
8707 UpdateExternalStatus(1);
8709 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8711 UpdateExternalStatus(0);
8712 [self setStatusBarShowsProgress:NO];
8714 [self removeStashController];
8716 if (ExecFork() == 0) {
8717 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8718 perror("launchctl stop");
8722 - (void) setupTabBarController {
8723 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8724 [tabbar_ setDelegate:self];
8726 NSMutableArray *items([NSMutableArray arrayWithObjects:
8727 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8728 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8729 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8730 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8734 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8735 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8737 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8740 NSMutableArray *controllers([NSMutableArray array]);
8742 for (UITabBarItem *item in items) {
8743 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8744 [controller setTabBarItem:item];
8745 [controllers addObject:controller];
8748 [tabbar_ setViewControllers:controllers];
8751 - (void) applicationDidFinishLaunching:(id)unused {
8753 [CYBrowserController _initialize];
8755 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8757 Font12_ = [[UIFont systemFontOfSize:12] retain];
8758 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8759 Font14_ = [[UIFont systemFontOfSize:14] retain];
8760 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8761 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8765 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8766 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8768 UIScreen *screen([UIScreen mainScreen]);
8770 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8771 [window_ orderFront:self];
8772 [window_ makeKey:self];
8773 [window_ setHidden:NO];
8776 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8777 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8778 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8779 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8780 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8781 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8782 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8783 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8784 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8787 [self addStashController];
8788 // XXX: this would be much cleaner as a yieldToSelector:
8789 // that way the removeStashController could happen right here inline
8790 // we also could no longer require the useless stash_ field anymore
8791 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8795 database_ = [Database sharedInstance];
8797 [self setupTabBarController];
8799 container_ = [[CYContainer alloc] initWithDatabase:database_];
8800 [container_ setUpdateDelegate:self];
8801 [container_ setTabBarController:tabbar_];
8802 [window_ addSubview:[container_ view]];
8804 // Show pinstripes while loading data.
8805 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8807 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8814 [self showSettings];
8818 [window_ setUserInteractionEnabled:NO];
8820 UIView *container = [[[UIView alloc] init] autorelease];
8821 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8823 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8824 [spinner startAnimating];
8825 [container addSubview:spinner];
8827 UILabel *label = [[[UILabel alloc] init] autorelease];
8828 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8829 [label setBackgroundColor:[UIColor clearColor]];
8830 [label setTextColor:[UIColor blackColor]];
8831 [label setShadowColor:[UIColor whiteColor]];
8832 [label setShadowOffset:CGSizeMake(0, 1)];
8833 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8834 [container addSubview:label];
8836 CGSize viewsize = [[tabbar_ view] frame].size;
8837 CGSize spinnersize = [spinner bounds].size;
8838 CGSize textsize = [[label text] sizeWithFont:[label font]];
8839 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8841 CGRect containrect = {
8842 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8843 CGSizeMake(bothwidth, spinnersize.height)
8846 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8854 [container setFrame:containrect];
8855 [spinner setFrame:spinrect];
8856 [label setFrame:textrect];
8857 [[container_ view] addSubview:container];
8862 // Show the initial page
8863 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
8864 [tabbar_ setSelectedIndex:0];
8868 [starturl_ release];
8871 [window_ setUserInteractionEnabled:YES];
8873 // XXX: does this actually slow anything down?
8874 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8875 [container removeFromSuperview];
8878 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8879 if (item != nil && IsWildcat_) {
8880 [sheet showFromBarButtonItem:item animated:YES];
8882 [sheet showInView:window_];
8889 id Alloc_(id self, SEL selector) {
8890 id object = alloc_(self, selector);
8891 lprintf("[%s]A-%p\n", self->isa->name, object);
8896 id Dealloc_(id self, SEL selector) {
8897 id object = dealloc_(self, selector);
8898 lprintf("[%s]D-%p\n", self->isa->name, object);
8902 Class $WebDefaultUIKitDelegate;
8904 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8905 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8906 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8907 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8910 static NSNumber *shouldPlayKeyboardSounds;
8914 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8916 case 1104: // Keyboard Button Clicked
8917 case 1105: // Keyboard Delete Repeated
8918 if (shouldPlayKeyboardSounds == nil) {
8919 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8920 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8923 if (![shouldPlayKeyboardSounds boolValue])
8927 _UIHardware$_playSystemSound$(self, _cmd, sound);
8931 int main(int argc, char *argv[]) { _pooled
8934 if (Class $UIDevice = objc_getClass("UIDevice")) {
8935 UIDevice *device([$UIDevice currentDevice]);
8936 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8940 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8942 /* Library Hacks {{{ */
8943 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8945 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8946 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8947 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8948 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8949 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8952 $UIHardware = objc_getClass("UIHardware");
8953 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8954 if (UIHardware$_playSystemSound$ != NULL) {
8955 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8956 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8959 /* Set Locale {{{ */
8960 Locale_ = CFLocaleCopyCurrent();
8961 Languages_ = [NSLocale preferredLanguages];
8962 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8963 //NSLog(@"%@", [Languages_ description]);
8966 if (Languages_ == nil || [Languages_ count] == 0)
8967 // XXX: consider just setting to C and then falling through?
8970 lang = [[Languages_ objectAtIndex:0] UTF8String];
8971 setenv("LANG", lang, true);
8974 //std::setlocale(LC_ALL, lang);
8975 NSLog(@"Setting Language: %s", lang);
8978 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8980 /* Parse Arguments {{{ */
8981 bool substrate(false);
8987 for (int argi(1); argi != argc; ++argi)
8988 if (strcmp(argv[argi], "--") == 0) {
8990 argv[argi] = argv[0];
8996 for (int argi(1); argi != arge; ++argi)
8997 if (strcmp(args[argi], "--substrate") == 0)
9000 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9004 App_ = [[NSBundle mainBundle] bundlePath];
9005 Home_ = NSHomeDirectory();
9011 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9012 alloc_ = alloc->method_imp;
9013 alloc->method_imp = (IMP) &Alloc_;*/
9015 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9016 dealloc_ = dealloc->method_imp;
9017 dealloc->method_imp = (IMP) &Dealloc_;*/
9019 /* System Information {{{ */
9023 size = sizeof(maxproc);
9024 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9025 perror("sysctlbyname(\"kern.maxproc\", ?)");
9026 else if (maxproc < 64) {
9028 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9029 perror("sysctlbyname(\"kern.maxproc\", #)");
9032 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9033 char *osversion = new char[size];
9034 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9035 perror("sysctlbyname(\"kern.osversion\", ?)");
9037 System_ = [NSString stringWithUTF8String:osversion];
9039 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9040 char *machine = new char[size];
9041 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9042 perror("sysctlbyname(\"hw.machine\", ?)");
9046 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9047 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9048 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9049 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9053 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9054 NSData *data((NSData *) ecid);
9055 size_t length([data length]);
9056 uint8_t bytes[length];
9057 [data getBytes:bytes];
9058 char string[length * 2 + 1];
9059 for (size_t i(0); i != length; ++i)
9060 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9061 ChipID_ = [NSString stringWithUTF8String:string];
9065 IOObjectRelease(service);
9069 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9071 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9072 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9073 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9075 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9076 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9077 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9079 if (mcc != NULL && mnc != NULL)
9080 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9087 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9088 Build_ = [system objectForKey:@"ProductBuildVersion"];
9089 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9090 Product_ = [info objectForKey:@"SafariProductVersion"];
9091 Safari_ = [info objectForKey:@"CFBundleVersion"];
9094 /* Load Database {{{ */
9096 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9098 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9100 if (Metadata_ == NULL)
9101 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9103 Settings_ = [Metadata_ objectForKey:@"Settings"];
9105 Packages_ = [Metadata_ objectForKey:@"Packages"];
9106 Sections_ = [Metadata_ objectForKey:@"Sections"];
9107 Sources_ = [Metadata_ objectForKey:@"Sources"];
9109 Token_ = [Metadata_ objectForKey:@"Token"];
9112 if (Settings_ != nil)
9113 Role_ = [Settings_ objectForKey:@"Role"];
9115 if (Sections_ == nil) {
9116 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9117 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9120 if (Sources_ == nil) {
9121 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9122 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9127 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9130 if (Packages_ != nil) {
9131 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9133 [Metadata_ removeObjectForKey:@"Packages"];
9138 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9140 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9141 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9142 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9143 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9144 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9145 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9147 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9149 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9150 unlink("/tmp/.cydia.fw");
9152 } else if (access("/User", F_OK) != 0 || version < 2) {
9155 system("/usr/libexec/cydia/firmware.sh");
9159 _assert([[NSFileManager defaultManager]
9160 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9161 withIntermediateDirectories:YES
9166 if (access("/tmp/cydia.chk", F_OK) == 0) {
9167 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9168 _assert(errno == ENOENT);
9169 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9170 _assert(errno == ENOENT);
9173 /* APT Initialization {{{ */
9174 _assert(pkgInitConfig(*_config));
9175 _assert(pkgInitSystem(*_config, _system));
9178 _config->Set("APT::Acquire::Translation", lang);
9180 // XXX: this timeout might be important :(
9181 //_config->Set("Acquire::http::Timeout", 15);
9183 _config->Set("Acquire::http::MaxParallel", 3);
9185 /* Color Choices {{{ */
9186 space_ = CGColorSpaceCreateDeviceRGB();
9188 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9189 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9190 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9191 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9192 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9193 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9194 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9195 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9196 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9198 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9199 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9201 /* UIKit Configuration {{{ */
9202 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9203 if ($GSFontSetUseLegacyFontMetrics != NULL)
9204 $GSFontSetUseLegacyFontMetrics(YES);
9206 // XXX: I have a feeling this was important
9207 //UIKeyboardDisableAutomaticAppearance();
9210 Colon_ = UCLocalize("COLON_DELIMITED");
9211 Elision_ = UCLocalize("ELISION");
9212 Error_ = UCLocalize("ERROR");
9213 Warning_ = UCLocalize("WARNING");
9216 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9218 CGColorSpaceRelease(space_);