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 bool versioned(false);
1502 if (NSDate *date = [package objectForKey:@"LastSeen"]) {
1503 time_t time([date timeIntervalSince1970]);
1504 if (metadata->last_ < time || metadata->last_ == 0) {
1505 metadata->last_ = time;
1508 } else if (metadata->last_ == 0) {
1509 metadata->last_ = metadata->first_;
1510 if (metadata->version_[0] == '\0')
1515 if (NSString *version = [package objectForKey:@"LastVersion"])
1516 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1517 size_t length(strlen(buffer));
1518 uint16_t vhash(hashlittle(buffer, length));
1520 size_t capped(std::min<size_t>(8, length));
1521 char *latest(buffer + length - capped);
1523 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1524 metadata->vhash_ = vhash;
1529 /* Source Class {{{ */
1530 @interface Source : NSObject {
1531 CYString depiction_;
1532 CYString description_;
1538 CYString distribution_;
1543 NSString *authority_;
1545 CYString defaultIcon_;
1547 NSDictionary *record_;
1551 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1553 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1555 - (NSString *) depictionForPackage:(NSString *)package;
1556 - (NSString *) supportForPackage:(NSString *)package;
1558 - (NSDictionary *) record;
1562 - (NSString *) distribution;
1563 - (NSString *) type;
1565 - (NSString *) host;
1567 - (NSString *) name;
1568 - (NSString *) description;
1569 - (NSString *) label;
1570 - (NSString *) origin;
1571 - (NSString *) version;
1573 - (NSString *) defaultIcon;
1577 @implementation Source
1581 distribution_.clear();
1584 description_.clear();
1590 defaultIcon_.clear();
1592 if (record_ != nil) {
1602 if (authority_ != nil) {
1603 [authority_ release];
1609 // XXX: this is a very inefficient way to call these deconstructors
1614 + (NSArray *) _attributeKeys {
1615 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1618 - (NSArray *) attributeKeys {
1619 return [[self class] _attributeKeys];
1622 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1623 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1626 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1629 trusted_ = index->IsTrusted();
1631 uri_.set(pool, index->GetURI());
1632 distribution_.set(pool, index->GetDist());
1633 type_.set(pool, index->GetType());
1635 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1636 if (dindex != NULL) {
1638 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1641 pkgTagFile tags(&fd);
1643 pkgTagSection section;
1650 {"default-icon", &defaultIcon_},
1651 {"depiction", &depiction_},
1652 {"description", &description_},
1654 {"origin", &origin_},
1655 {"support", &support_},
1656 {"version", &version_},
1659 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1660 const char *start, *end;
1662 if (section.Find(names[i].name_, start, end)) {
1663 CYString &value(*names[i].value_);
1664 value.set(pool, start, end - start);
1670 record_ = [Sources_ objectForKey:[self key]];
1672 record_ = [record_ retain];
1674 NSURL *url([NSURL URLWithString:uri_]);
1678 host_ = [[host_ lowercaseString] retain];
1683 authority_ = [url path];
1685 if (authority_ != nil)
1686 authority_ = [authority_ retain];
1689 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1690 if ((self = [super init]) != nil) {
1691 [self setMetaIndex:index inPool:pool];
1695 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1696 NSDictionary *lhr = [self record];
1697 NSDictionary *rhr = [source record];
1700 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1702 NSString *lhs = [self name];
1703 NSString *rhs = [source name];
1705 if ([lhs length] != 0 && [rhs length] != 0) {
1706 unichar lhc = [lhs characterAtIndex:0];
1707 unichar rhc = [rhs characterAtIndex:0];
1709 if (isalpha(lhc) && !isalpha(rhc))
1710 return NSOrderedAscending;
1711 else if (!isalpha(lhc) && isalpha(rhc))
1712 return NSOrderedDescending;
1715 return [lhs compare:rhs options:LaxCompareOptions_];
1718 - (NSString *) depictionForPackage:(NSString *)package {
1719 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1722 - (NSString *) supportForPackage:(NSString *)package {
1723 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1726 - (NSDictionary *) record {
1734 - (NSString *) uri {
1738 - (NSString *) distribution {
1739 return distribution_;
1742 - (NSString *) type {
1746 - (NSString *) key {
1747 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1750 - (NSString *) host {
1754 - (NSString *) name {
1755 return origin_.empty() ? authority_ : origin_;
1758 - (NSString *) description {
1759 return description_;
1762 - (NSString *) label {
1763 return label_.empty() ? authority_ : label_;
1766 - (NSString *) origin {
1770 - (NSString *) version {
1774 - (NSString *) defaultIcon {
1775 return defaultIcon_;
1780 /* Relationship Class {{{ */
1781 @interface Relationship : NSObject {
1786 - (NSString *) type;
1788 - (NSString *) name;
1792 @implementation Relationship
1800 - (NSString *) type {
1808 - (NSString *) name {
1815 /* Package Class {{{ */
1816 struct ParsedPackage {
1821 CYString depiction_;
1831 @interface Package : NSObject {
1833 uint32_t essential_ : 1;
1834 uint32_t obsolete_ : 1;
1835 uint32_t ignored_ : 1;
1839 _transient Database *database_;
1841 pkgCache::VerIterator version_;
1842 pkgCache::PkgIterator iterator_;
1843 pkgCache::VerFileIterator file_;
1849 CYString installed_;
1852 _transient NSString *section$_;
1856 PackageValue *metadata_;
1857 ParsedPackage *parsed_;
1859 NSMutableArray *tags_;
1863 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1864 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1866 - (pkgCache::PkgIterator) iterator;
1869 - (NSString *) section;
1870 - (NSString *) simpleSection;
1872 - (NSString *) longSection;
1873 - (NSString *) shortSection;
1877 - (Address *) maintainer;
1879 - (NSString *) longDescription;
1880 - (NSString *) shortDescription;
1883 - (PackageValue *) metadata;
1886 - (bool) subscribed;
1887 - (bool) setSubscribed:(bool)subscribed;
1891 - (NSString *) latest;
1892 - (NSString *) installed;
1893 - (BOOL) uninstalled;
1896 - (BOOL) upgradableAndEssential:(BOOL)essential;
1899 - (BOOL) unfiltered;
1903 - (BOOL) halfConfigured;
1904 - (BOOL) halfInstalled;
1906 - (NSString *) mode;
1909 - (NSString *) name;
1911 - (NSString *) homepage;
1912 - (NSString *) depiction;
1913 - (Address *) author;
1915 - (NSString *) support;
1917 - (NSArray *) files;
1918 - (NSArray *) warnings;
1919 - (NSArray *) applications;
1921 - (Source *) source;
1922 - (NSString *) role;
1924 - (BOOL) matches:(NSString *)text;
1926 - (bool) hasSupportingRole;
1927 - (BOOL) hasTag:(NSString *)tag;
1928 - (NSString *) primaryPurpose;
1929 - (NSArray *) purposes;
1930 - (bool) isCommercial;
1932 - (void) setIndex:(size_t)index;
1934 - (CYString &) cyname;
1936 - (uint32_t) compareBySection:(NSArray *)sections;
1941 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1942 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1943 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1944 - (bool) isVisibleInSection:(NSString *)section;
1945 - (bool) isVisibleInSource:(Source *)source;
1949 uint32_t PackageChangesRadix(Package *self, void *) {
1954 uint32_t timestamp : 30;
1955 uint32_t ignored : 1;
1956 uint32_t upgradable : 1;
1960 bool upgradable([self upgradableAndEssential:YES]);
1961 value.bits.upgradable = upgradable ? 1 : 0;
1964 value.bits.timestamp = 0;
1965 value.bits.ignored = [self ignored] ? 0 : 1;
1966 value.bits.upgradable = 1;
1968 value.bits.timestamp = [self seen] >> 2;
1969 value.bits.ignored = 0;
1970 value.bits.upgradable = 0;
1973 return _not(uint32_t) - value.key;
1976 uint32_t PackagePrefixRadix(Package *self, void *context) {
1977 size_t offset(reinterpret_cast<size_t>(context));
1978 CYString &name([self cyname]);
1980 size_t size(name.size());
1983 char *text(name.data());
1986 if (!isdigit(text[0]))
1990 while (size != digits && isdigit(text[digits]))
1998 if (offset == 0 && zeros != 0) {
1999 memset(data, '0', zeros);
2000 memcpy(data + zeros, text, 4 - zeros);
2002 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2003 if (size <= offset - zeros)
2006 text += offset - zeros;
2007 size -= offset - zeros;
2010 memcpy(data, text, 4);
2012 memcpy(data, text, size);
2013 memset(data + size, 0, 4 - size);
2016 for (size_t i(0); i != 4; ++i)
2017 if (isalpha(data[i]))
2025 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2027 /* XXX: ntohl may be more honest */
2028 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2031 CYString &(*PackageName)(Package *self, SEL sel);
2033 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2034 _profile(PackageNameCompare)
2035 CYString &lhi(PackageName(lhs, @selector(cyname)));
2036 CYString &rhi(PackageName(rhs, @selector(cyname)));
2037 CFStringRef lhn(lhi), rhn(rhi);
2040 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2041 else if (rhn == NULL)
2042 return NSOrderedDescending;
2044 _profile(PackageNameCompare$NumbersLast)
2045 if (!lhi.empty() && !rhi.empty()) {
2046 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2047 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2048 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2049 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2050 return lha ? NSOrderedAscending : NSOrderedDescending;
2054 CFIndex length = CFStringGetLength(lhn);
2056 _profile(PackageNameCompare$Compare)
2057 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2062 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2063 return PackageNameCompare(*lhs, *rhs, context);
2066 struct PackageNameOrdering :
2067 std::binary_function<Package *, Package *, bool>
2069 _finline bool operator ()(Package *lhs, Package *rhs) const {
2070 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2074 @implementation Package
2076 - (NSString *) description {
2077 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2081 if (parsed_ != NULL)
2095 + (NSString *) webScriptNameForSelector:(SEL)selector {
2096 if (selector == @selector(hasTag:))
2102 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2103 return [self webScriptNameForSelector:selector] == nil;
2106 + (NSArray *) _attributeKeys {
2107 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];
2110 - (NSArray *) attributeKeys {
2111 return [[self class] _attributeKeys];
2114 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2115 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2119 if (parsed_ != NULL)
2121 @synchronized (database_) {
2122 if ([database_ era] != era_ || file_.end())
2125 ParsedPackage *parsed(new ParsedPackage);
2128 _profile(Package$parse)
2129 pkgRecords::Parser *parser;
2131 _profile(Package$parse$Lookup)
2132 parser = &[database_ records]->Lookup(file_);
2137 _profile(Package$parse$Find)
2142 {"icon", &parsed->icon_},
2143 {"depiction", &parsed->depiction_},
2144 {"homepage", &parsed->homepage_},
2145 {"website", &website},
2146 {"bugs", &parsed->bugs_},
2147 {"support", &parsed->support_},
2148 {"sponsor", &parsed->sponsor_},
2149 {"author", &parsed->author_},
2152 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2153 const char *start, *end;
2155 if (parser->Find(names[i].name_, start, end)) {
2156 CYString &value(*names[i].value_);
2157 _profile(Package$parse$Value)
2158 value.set(pool_, start, end - start);
2164 _profile(Package$parse$Tagline)
2165 const char *start, *end;
2166 if (parser->ShortDesc(start, end)) {
2167 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2170 while (stop != start && stop[-1] == '\r')
2172 parsed->tagline_.set(pool_, start, stop - start);
2176 _profile(Package$parse$Retain)
2177 if (parsed->homepage_.empty())
2178 parsed->homepage_ = website;
2179 if (parsed->homepage_ == parsed->depiction_)
2180 parsed->homepage_.clear();
2185 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2186 if ((self = [super init]) != nil) {
2187 _profile(Package$initWithVersion)
2190 database_ = database;
2191 era_ = [database era];
2195 pkgCache::PkgIterator iterator(version.ParentPkg());
2196 iterator_ = iterator;
2198 _profile(Package$initWithVersion$Version)
2199 if (!version_.end())
2200 file_ = version_.FileList();
2202 pkgCache &cache([database_ cache]);
2203 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2207 _profile(Package$initWithVersion$Cache)
2208 id_.set(NULL, iterator.Name());
2209 name_.set(NULL, iterator.Display());
2211 latest_.set(NULL, StripVersion_(version_.VerStr()));
2213 pkgCache::VerIterator current(iterator.CurrentVer());
2215 installed_.set(NULL, StripVersion_(current.VerStr()));
2218 _profile(Package$initWithVersion$Lower)
2219 // XXX: do not use tolower() as this is not locale-specific? :(
2220 char *data(id_.data());
2221 for (size_t i(0), e(id_.size()); i != e; ++i)
2222 if ((data[i] & 0x20) == 0) {
2231 _profile(Package$initWithVersion$Tags)
2232 pkgCache::TagIterator tag(iterator.TagList());
2234 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2236 const char *name(tag.Name());
2237 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2239 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2240 role_ = (NSString *) CYStringCreate(name + 6);
2242 if (strncmp(name, "cydia::", 7) == 0) {
2243 if (strcmp(name + 7, "essential") == 0)
2245 else if (strcmp(name + 7, "obsolete") == 0)
2250 } while (!tag.end());
2254 _profile(Package$initWithVersion$Metadata)
2255 PackageValue *metadata(PackageFind(id_.data(), id_.size()));
2256 metadata_ = metadata;
2258 const char *latest(version_.VerStr());
2259 size_t length(strlen(latest));
2261 uint16_t vhash(hashlittle(latest, length));
2263 size_t capped(std::min<size_t>(8, length));
2264 latest = latest + length - capped;
2266 if (metadata->first_ == 0)
2267 metadata->first_ = now_;
2269 if (metadata->last_ == 0)
2270 metadata->last_ = metadata->first_;
2272 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2273 if (metadata->version_[0] != '\0')
2274 metadata->last_ = now_;
2275 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2276 metadata->vhash_ = vhash;
2280 _profile(Package$initWithVersion$Section)
2281 section_.set(NULL, iterator.Section());
2284 _profile(Package$initWithVersion$Flags)
2285 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2286 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2291 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2292 pkgCache::VerIterator version;
2294 _profile(Package$packageWithIterator$GetCandidateVer)
2295 version = [database policy]->GetCandidateVer(iterator);
2303 _profile(Package$packageWithIterator$Allocate)
2304 package = [Package allocWithZone:zone];
2307 _profile(Package$packageWithIterator$Initialize)
2309 initWithVersion:version
2316 _profile(Package$packageWithIterator$Autorelease)
2317 package = [package autorelease];
2323 - (pkgCache::PkgIterator) iterator {
2327 - (NSString *) section {
2328 if (section$_ == nil) {
2329 if (section_.empty())
2332 _profile(Package$section)
2333 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2334 NSString *name(section_);
2335 section$_ = [SectionMap_ objectForKey:name] ?: name;
2340 - (NSString *) simpleSection {
2341 if (NSString *section = [self section])
2342 return Simplify(section);
2347 - (NSString *) longSection {
2348 return LocalizeSection([self section]);
2351 - (NSString *) shortSection {
2352 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2355 - (NSString *) uri {
2358 pkgIndexFile *index;
2359 pkgCache::PkgFileIterator file(file_.File());
2360 if (![database_ list].FindIndex(file, index))
2362 return [NSString stringWithUTF8String:iterator_->Path];
2363 //return [NSString stringWithUTF8String:file.Site()];
2364 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2368 - (Address *) maintainer {
2369 @synchronized (database_) {
2370 if ([database_ era] != era_ || file_.end())
2373 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2374 const std::string &maintainer(parser->Maintainer());
2375 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2379 @synchronized (database_) {
2380 if ([database_ era] != era_ || version_.end())
2383 return version_->InstalledSize;
2386 - (NSString *) longDescription {
2387 @synchronized (database_) {
2388 if ([database_ era] != era_ || file_.end())
2391 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2392 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2394 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2395 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2396 if ([lines count] < 2)
2399 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2400 for (size_t i(1), e([lines count]); i != e; ++i) {
2401 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2402 [trimmed addObject:trim];
2405 return [trimmed componentsJoinedByString:@"\n"];
2408 - (NSString *) shortDescription {
2409 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2413 _profile(Package$index)
2414 CFStringRef name((CFStringRef) [self name]);
2415 if (CFStringGetLength(name) == 0)
2417 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2418 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2420 return toupper(character);
2424 - (PackageValue *) metadata {
2429 PackageValue *metadata([self metadata]);
2430 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2433 - (bool) subscribed {
2434 return [self metadata]->subscribed_;
2437 - (bool) setSubscribed:(bool)subscribed {
2438 PackageValue *metadata([self metadata]);
2439 if (metadata->subscribed_ == subscribed)
2441 metadata->subscribed_ = subscribed;
2449 - (NSString *) latest {
2453 - (NSString *) installed {
2457 - (BOOL) uninstalled {
2458 return installed_.empty();
2462 return !version_.end();
2465 - (BOOL) upgradableAndEssential:(BOOL)essential {
2466 _profile(Package$upgradableAndEssential)
2467 pkgCache::VerIterator current(iterator_.CurrentVer());
2469 return essential && essential_;
2471 return !version_.end() && version_ != current;
2475 - (BOOL) essential {
2480 return [database_ cache][iterator_].InstBroken();
2483 - (BOOL) unfiltered {
2484 _profile(Package$unfiltered$obsolete)
2489 _profile(Package$unfiltered$hasSupportingRole)
2490 if (![self hasSupportingRole])
2498 if (![self unfiltered])
2501 NSString *section([self section]);
2503 _profile(Package$visible$isSectionVisible)
2504 if (section != nil && !isSectionVisible(section))
2512 unsigned char current(iterator_->CurrentState);
2513 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2516 - (BOOL) halfConfigured {
2517 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2520 - (BOOL) halfInstalled {
2521 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2525 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2526 return state.Mode != pkgDepCache::ModeKeep;
2529 - (NSString *) mode {
2530 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2532 switch (state.Mode) {
2533 case pkgDepCache::ModeDelete:
2534 if ((state.iFlags & pkgDepCache::Purge) != 0)
2538 case pkgDepCache::ModeKeep:
2539 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2540 return @"REINSTALL";
2541 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2545 case pkgDepCache::ModeInstall:
2546 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2547 return @"REINSTALL";
2548 else*/ switch (state.Status) {
2550 return @"DOWNGRADE";
2556 return @"NEW_INSTALL";
2567 - (NSString *) name {
2568 return name_.empty() ? id_ : name_;
2571 - (UIImage *) icon {
2572 NSString *section = [self simpleSection];
2575 if (parsed_ != NULL)
2576 if (NSString *href = parsed_->icon_)
2577 if ([href hasPrefix:@"file:///"])
2578 // XXX: correct escaping
2579 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2580 if (icon == nil) if (section != nil)
2581 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2582 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2583 if ([dicon hasPrefix:@"file:///"])
2584 // XXX: correct escaping
2585 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2587 icon = [UIImage applicationImageNamed:@"unknown.png"];
2591 - (NSString *) homepage {
2592 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2595 - (NSString *) depiction {
2596 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2599 - (Address *) sponsor {
2600 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2603 - (Address *) author {
2604 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2607 - (NSString *) support {
2608 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2611 - (NSArray *) files {
2612 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2613 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2616 fin.open([path UTF8String]);
2621 while (std::getline(fin, line))
2622 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2627 - (NSArray *) warnings {
2628 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2629 const char *name(iterator_.Name());
2631 size_t length(strlen(name));
2632 if (length < 2) invalid:
2633 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2634 else for (size_t i(0); i != length; ++i)
2636 /* XXX: technically this is not allowed */
2637 (name[i] < 'A' || name[i] > 'Z') &&
2638 (name[i] < 'a' || name[i] > 'z') &&
2639 (name[i] < '0' || name[i] > '9') &&
2640 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2643 if (strcmp(name, "cydia") != 0) {
2646 bool _private = false;
2649 bool repository = [[self section] isEqualToString:@"Repositories"];
2651 if (NSArray *files = [self files])
2652 for (NSString *file in files)
2653 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2655 else if (!user && [file isEqualToString:@"/User"])
2657 else if (!_private && [file isEqualToString:@"/private"])
2659 else if (!stash && [file isEqualToString:@"/var/stash"])
2662 /* XXX: this is not sensitive enough. only some folders are valid. */
2663 if (cydia && !repository)
2664 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2666 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2668 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2670 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2673 return [warnings count] == 0 ? nil : warnings;
2676 - (NSArray *) applications {
2677 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2679 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2681 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2682 if (NSArray *files = [self files])
2683 for (NSString *file in files)
2684 if (application_r(file)) {
2685 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2686 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2687 if ([id isEqualToString:me])
2690 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2692 display = application_r[1];
2694 NSString *bundle([file stringByDeletingLastPathComponent]);
2695 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2696 if (icon == nil || [icon length] == 0)
2698 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2700 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2701 [applications addObject:application];
2703 [application addObject:id];
2704 [application addObject:display];
2705 [application addObject:url];
2708 return [applications count] == 0 ? nil : applications;
2711 - (Source *) source {
2712 if (source_ == nil) {
2713 @synchronized (database_) {
2714 if ([database_ era] != era_ || file_.end())
2715 source_ = (Source *) [NSNull null];
2717 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2721 return source_ == (Source *) [NSNull null] ? nil : source_;
2724 - (NSString *) role {
2728 - (BOOL) matches:(NSString *)text {
2734 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2735 if (range.location != NSNotFound)
2738 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2739 if (range.location != NSNotFound)
2742 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2743 if (range.location != NSNotFound)
2749 - (bool) hasSupportingRole {
2752 if ([role_ isEqualToString:@"enduser"])
2754 if ([Role_ isEqualToString:@"User"])
2756 if ([role_ isEqualToString:@"hacker"])
2758 if ([Role_ isEqualToString:@"Hacker"])
2760 if ([role_ isEqualToString:@"developer"])
2762 if ([Role_ isEqualToString:@"Developer"])
2767 - (BOOL) hasTag:(NSString *)tag {
2768 return tags_ == nil ? NO : [tags_ containsObject:tag];
2771 - (NSString *) primaryPurpose {
2772 for (NSString *tag in tags_)
2773 if ([tag hasPrefix:@"purpose::"])
2774 return [tag substringFromIndex:9];
2778 - (NSArray *) purposes {
2779 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2780 for (NSString *tag in tags_)
2781 if ([tag hasPrefix:@"purpose::"])
2782 [purposes addObject:[tag substringFromIndex:9]];
2783 return [purposes count] == 0 ? nil : purposes;
2786 - (bool) isCommercial {
2787 return [self hasTag:@"cydia::commercial"];
2790 - (void) setIndex:(size_t)index {
2791 if (metadata_->index_ != index)
2792 metadata_->index_ = index;
2795 - (CYString &) cyname {
2796 return name_.empty() ? id_ : name_;
2799 - (uint32_t) compareBySection:(NSArray *)sections {
2800 NSString *section([self section]);
2801 for (size_t i(0), e([sections count]); i != e; ++i) {
2802 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2806 return _not(uint32_t);
2810 @synchronized (database_) {
2811 pkgProblemResolver *resolver = [database_ resolver];
2812 resolver->Clear(iterator_);
2814 pkgCacheFile &cache([database_ cache]);
2815 cache->SetReInstall(iterator_, false);
2816 cache->MarkKeep(iterator_, false);
2820 @synchronized (database_) {
2821 pkgProblemResolver *resolver = [database_ resolver];
2822 resolver->Clear(iterator_);
2823 resolver->Protect(iterator_);
2825 pkgCacheFile &cache([database_ cache]);
2826 cache->SetReInstall(iterator_, false);
2827 cache->MarkInstall(iterator_, false);
2829 pkgDepCache::StateCache &state((*cache)[iterator_]);
2830 if (!state.Install())
2831 cache->SetReInstall(iterator_, true);
2835 @synchronized (database_) {
2836 pkgProblemResolver *resolver = [database_ resolver];
2837 resolver->Clear(iterator_);
2838 resolver->Remove(iterator_);
2839 resolver->Protect(iterator_);
2841 pkgCacheFile &cache([database_ cache]);
2842 cache->SetReInstall(iterator_, false);
2843 cache->MarkDelete(iterator_, true);
2846 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2847 _profile(Package$isUnfilteredAndSearchedForBy)
2850 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2851 value &= [self unfiltered];
2854 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2855 value &= [self matches:search];
2862 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2863 if ([search length] == 0)
2866 _profile(Package$isUnfilteredAndSelectedForBy)
2869 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2870 value &= [self unfiltered];
2873 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2874 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2881 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2882 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2885 - (bool) isVisibleInSection:(NSString *)name {
2886 NSString *section([self section]);
2890 section == nil && [name length] == 0 ||
2891 [name isEqualToString:section]
2892 ) && [self visible];
2895 - (bool) isVisibleInSource:(Source *)source {
2896 return [self source] == source && [self visible];
2901 /* Section Class {{{ */
2902 @interface Section : NSObject {
2907 NSString *localized_;
2910 - (NSComparisonResult) compareByLocalized:(Section *)section;
2911 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2912 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2913 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2914 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2915 - (NSString *) name;
2922 - (void) addToCount;
2924 - (void) setCount:(size_t)count;
2925 - (NSString *) localized;
2929 @implementation Section
2933 if (localized_ != nil)
2934 [localized_ release];
2938 - (NSComparisonResult) compareByLocalized:(Section *)section {
2939 NSString *lhs(localized_);
2940 NSString *rhs([section localized]);
2942 /*if ([lhs length] != 0 && [rhs length] != 0) {
2943 unichar lhc = [lhs characterAtIndex:0];
2944 unichar rhc = [rhs characterAtIndex:0];
2946 if (isalpha(lhc) && !isalpha(rhc))
2947 return NSOrderedAscending;
2948 else if (!isalpha(lhc) && isalpha(rhc))
2949 return NSOrderedDescending;
2952 return [lhs compare:rhs options:LaxCompareOptions_];
2955 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2956 if ((self = [self initWithName:name localize:NO]) != nil) {
2957 if (localized != nil)
2958 localized_ = [localized retain];
2962 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2963 return [self initWithName:name row:0 localize:localize];
2966 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2967 if ((self = [super init]) != nil) {
2968 name_ = [name retain];
2972 localized_ = [LocalizeSection(name_) retain];
2976 /* XXX: localize the index thingees */
2977 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2978 if ((self = [super init]) != nil) {
2979 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2985 - (NSString *) name {
3005 - (void) addToCount {
3009 - (void) setCount:(size_t)count {
3013 - (NSString *) localized {
3020 static NSString *Colon_;
3021 static NSString *Elision_;
3022 static NSString *Error_;
3023 static NSString *Warning_;
3025 /* Database Implementation {{{ */
3026 @implementation Database
3028 + (Database *) sharedInstance {
3029 static Database *instance;
3030 if (instance == nil)
3031 instance = [[Database alloc] init];
3039 - (void) releasePackages {
3040 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3041 CFArrayRemoveAllValues(packages_);
3045 // XXX: actually implement this thing
3047 [self releasePackages];
3048 apr_pool_destroy(pool_);
3049 NSRecycleZone(zone_);
3053 - (void) _readCydia:(NSNumber *)fd { _pooled
3054 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3055 std::istream is(&ib);
3058 static Pcre finish_r("^finish:([^:]*)$");
3060 while (std::getline(is, line)) {
3061 const char *data(line.c_str());
3062 size_t size = line.size();
3063 lprintf("C:%s\n", data);
3065 if (finish_r(data, size)) {
3066 NSString *finish = finish_r[1];
3067 int index = [Finishes_ indexOfObject:finish];
3068 if (index != INT_MAX && index > Finish_)
3076 - (void) _readStatus:(NSNumber *)fd { _pooled
3077 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3078 std::istream is(&ib);
3081 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3082 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3084 while (std::getline(is, line)) {
3085 const char *data(line.c_str());
3086 size_t size(line.size());
3087 lprintf("S:%s\n", data);
3089 if (conffile_r(data, size)) {
3090 [delegate_ setConfigurationData:conffile_r[1]];
3091 } else if (strncmp(data, "status: ", 8) == 0) {
3092 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3093 [delegate_ setProgressTitle:string];
3094 } else if (pmstatus_r(data, size)) {
3095 std::string type([pmstatus_r[1] UTF8String]);
3096 NSString *id = pmstatus_r[2];
3098 float percent([pmstatus_r[3] floatValue]);
3099 [delegate_ setProgressPercent:(percent / 100)];
3101 NSString *string = pmstatus_r[4];
3103 if (type == "pmerror")
3104 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3105 withObject:[NSArray arrayWithObjects:string, id, nil]
3108 else if (type == "pmstatus") {
3109 [delegate_ setProgressTitle:string];
3110 } else if (type == "pmconffile")
3111 [delegate_ setConfigurationData:string];
3113 lprintf("E:unknown pmstatus\n");
3115 lprintf("E:unknown status\n");
3121 - (void) _readOutput:(NSNumber *)fd { _pooled
3122 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3123 std::istream is(&ib);
3126 while (std::getline(is, line)) {
3127 lprintf("O:%s\n", line.c_str());
3128 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3138 - (Package *) packageWithName:(NSString *)name {
3139 @synchronized (self) {
3140 if (static_cast<pkgDepCache *>(cache_) == NULL)
3142 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3143 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3147 if ((self = [super init]) != nil) {
3154 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3155 apr_pool_create(&pool_, NULL);
3157 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3161 _assert(pipe(fds) != -1);
3164 _config->Set("APT::Keep-Fds::", cydiafd_);
3165 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3168 detachNewThreadSelector:@selector(_readCydia:)
3170 withObject:[NSNumber numberWithInt:fds[0]]
3173 _assert(pipe(fds) != -1);
3177 detachNewThreadSelector:@selector(_readStatus:)
3179 withObject:[NSNumber numberWithInt:fds[0]]
3182 _assert(pipe(fds) != -1);
3183 _assert(dup2(fds[0], 0) != -1);
3184 _assert(close(fds[0]) != -1);
3186 input_ = fdopen(fds[1], "a");
3188 _assert(pipe(fds) != -1);
3189 _assert(dup2(fds[1], 1) != -1);
3190 _assert(close(fds[1]) != -1);
3193 detachNewThreadSelector:@selector(_readOutput:)
3195 withObject:[NSNumber numberWithInt:fds[0]]
3200 - (pkgCacheFile &) cache {
3204 - (pkgDepCache::Policy *) policy {
3208 - (pkgRecords *) records {
3212 - (pkgProblemResolver *) resolver {
3216 - (pkgAcquire &) fetcher {
3220 - (pkgSourceList &) list {
3224 - (NSArray *) packages {
3225 return (NSArray *) packages_;
3228 - (NSArray *) sources {
3229 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3230 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3231 [sources addObject:i->second];
3235 - (NSArray *) issues {
3236 if (cache_->BrokenCount() == 0)
3239 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3241 for (Package *package in [self packages]) {
3242 if (![package broken])
3244 pkgCache::PkgIterator pkg([package iterator]);
3246 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3247 [entry addObject:[package name]];
3248 [issues addObject:entry];
3250 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3254 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3255 pkgCache::DepIterator start;
3256 pkgCache::DepIterator end;
3257 dep.GlobOr(start, end); // ++dep
3259 if (!cache_->IsImportantDep(end))
3261 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3264 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3265 [entry addObject:failure];
3266 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3268 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3269 if (Package *package = [self packageWithName:name])
3270 name = [package name];
3271 [failure addObject:name];
3273 pkgCache::PkgIterator target(start.TargetPkg());
3274 if (target->ProvidesList != 0)
3275 [failure addObject:@"?"];
3277 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3279 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3280 else if (!cache_[target].CandidateVerIter(cache_).end())
3281 [failure addObject:@"-"];
3282 else if (target->ProvidesList == 0)
3283 [failure addObject:@"!"];
3285 [failure addObject:@"%"];
3289 if (start.TargetVer() != 0)
3290 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3301 - (bool) popErrorWithTitle:(NSString *)title {
3303 std::string message;
3305 while (!_error->empty()) {
3307 bool warning(!_error->PopMessage(error));
3311 size_t size(error.size());
3312 if (size == 0 || error[size - 1] != '\n')
3314 error.resize(size - 1);
3316 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3318 if (!message.empty())
3323 if (fatal && !message.empty())
3324 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3329 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3330 return [self popErrorWithTitle:title] || !success;
3333 - (void) reloadData { CYPoolStart() {
3334 @synchronized (self) {
3337 [self releasePackages];
3358 apr_pool_clear(pool_);
3359 NSRecycleZone(zone_);
3361 int chk(creat("/tmp/cydia.chk", 0644));
3365 NSString *title(UCLocalize("DATABASE"));
3368 if (!cache_.Open(progress_, true)) { pop:
3370 bool warning(!_error->PopMessage(error));
3371 lprintf("cache_.Open():[%s]\n", error.c_str());
3373 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3374 [delegate_ repairWithSelector:@selector(configure)];
3375 else if (error == "The package lists or status file could not be parsed or opened.")
3376 [delegate_ repairWithSelector:@selector(update)];
3377 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3378 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3379 // else if (error == "The list of sources could not be read.")
3381 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3390 unlink("/tmp/cydia.chk");
3392 now_ = [[NSDate date] timeIntervalSince1970];
3394 policy_ = new pkgDepCache::Policy();
3395 records_ = new pkgRecords(cache_);
3396 resolver_ = new pkgProblemResolver(cache_);
3397 fetcher_ = new pkgAcquire(&status_);
3400 list_ = new pkgSourceList();
3401 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3404 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3405 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3409 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3412 if (cache_->BrokenCount() != 0) {
3413 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3416 if (cache_->BrokenCount() != 0) {
3417 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3421 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3425 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3426 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3427 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3428 // XXX: this could be more intelligent
3429 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3430 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3432 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3437 /*std::vector<Package *> packages;
3438 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3439 [packages_ release];
3444 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3445 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3446 //packages.push_back(package);
3447 CFArrayAppendValue(packages_, [package retain]);
3451 /*if (packages.empty())
3452 packages_ = [[NSArray alloc] init];
3454 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3457 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3458 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3459 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3467 /*if (!packages.empty())
3468 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3469 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3471 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3473 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3475 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3479 size_t count(CFArrayGetCount(packages_));
3480 for (size_t index(0); index != count; ++index)
3481 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3485 } } CYPoolEnd() _trace(); }
3488 @synchronized (self) {
3490 resolver_ = new pkgProblemResolver(cache_);
3492 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3493 if (!cache_[iterator].Keep()) {
3494 cache_->MarkKeep(iterator, false);
3495 cache_->SetReInstall(iterator, false);
3500 - (void) configure {
3501 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3502 system([dpkg UTF8String]);
3506 // XXX: I don't remember this condition
3511 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3513 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3515 if ([self popErrorWithTitle:title])
3519 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3522 public pkgArchiveCleaner
3525 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3530 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3537 fetcher_->Shutdown();
3539 pkgRecords records(cache_);
3541 lock_ = new FileFd();
3542 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3544 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3546 if ([self popErrorWithTitle:title])
3550 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3553 manager_ = (_system->CreatePM(cache_));
3554 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3561 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3563 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3565 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3567 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3568 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3571 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3576 bool failed = false;
3577 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3578 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3580 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3583 std::string uri = (*item)->DescURI();
3584 std::string error = (*item)->ErrorText;
3586 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3589 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3590 withObject:[NSArray arrayWithObjects:
3591 [NSString stringWithUTF8String:error.c_str()],
3603 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3605 if (_error->PendingError()) {
3610 if (result == pkgPackageManager::Failed) {
3615 if (result != pkgPackageManager::Completed) {
3620 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3622 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3624 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3625 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3628 if (![before isEqualToArray:after])
3633 NSString *title(UCLocalize("UPGRADE"));
3634 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3640 [self updateWithStatus:status_];
3643 - (void) updateWithStatus:(Status &)status {
3644 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3645 NSString *title(UCLocalize("REFRESHING_DATA"));
3648 if (!list.ReadMainList())
3649 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3652 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3653 if ([self popErrorWithTitle:title])
3656 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3657 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3658 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3660 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3664 - (void) setDelegate:(id)delegate {
3665 delegate_ = delegate;
3666 status_.setDelegate(delegate);
3667 progress_.setDelegate(delegate);
3670 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3671 SourceMap::const_iterator i(sources_.find(file->ID));
3672 return i == sources_.end() ? nil : i->second;
3678 /* Confirmation Controller {{{ */
3679 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3680 if (!iterator.end())
3681 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3682 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3684 pkgCache::PkgIterator package(dep.TargetPkg());
3687 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3695 /* Web Scripting {{{ */
3696 @interface CydiaObject : NSObject {
3698 _transient id delegate_;
3701 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3704 @implementation CydiaObject
3707 [indirect_ release];
3711 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3712 if ((self = [super init]) != nil) {
3713 indirect_ = [indirect retain];
3717 - (void) setDelegate:(id)delegate {
3718 delegate_ = delegate;
3721 + (NSArray *) _attributeKeys {
3722 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3725 - (NSArray *) attributeKeys {
3726 return [[self class] _attributeKeys];
3729 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3730 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3733 - (NSString *) device {
3734 return [[UIDevice currentDevice] uniqueIdentifier];
3737 #if 0 // XXX: implement!
3738 - (NSString *) mac {
3739 if (![indirect_ promptForSensitive:@"Mac Address"])
3743 - (NSString *) serial {
3744 if (![indirect_ promptForSensitive:@"Serial #"])
3748 - (NSString *) firewire {
3749 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3753 - (NSString *) imei {
3754 if (![indirect_ promptForSensitive:@"IMEI"])
3759 + (NSString *) webScriptNameForSelector:(SEL)selector {
3760 if (selector == @selector(close))
3762 else if (selector == @selector(getInstalledPackages))
3763 return @"getInstalledPackages";
3764 else if (selector == @selector(getPackageById:))
3765 return @"getPackageById";
3766 else if (selector == @selector(installPackages:))
3767 return @"installPackages";
3768 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3769 return @"setButtonImage";
3770 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3771 return @"setButtonTitle";
3772 else if (selector == @selector(setPopupHook:))
3773 return @"setPopupHook";
3774 else if (selector == @selector(setSpecial:))
3775 return @"setSpecial";
3776 else if (selector == @selector(setToken:))
3778 else if (selector == @selector(setViewportWidth:))
3779 return @"setViewportWidth";
3780 else if (selector == @selector(supports:))
3782 else if (selector == @selector(stringWithFormat:arguments:))
3784 else if (selector == @selector(localizedStringForKey:value:table:))
3786 else if (selector == @selector(du:))
3788 else if (selector == @selector(statfs:))
3794 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3795 return [self webScriptNameForSelector:selector] == nil;
3798 - (BOOL) supports:(NSString *)feature {
3799 return [feature isEqualToString:@"window.open"];
3802 - (NSArray *) getInstalledPackages {
3803 NSArray *packages([[Database sharedInstance] packages]);
3804 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3805 for (Package *package in packages)
3806 if ([package installed] != nil)
3807 [installed addObject:package];
3811 - (Package *) getPackageById:(NSString *)id {
3812 Package *package([[Database sharedInstance] packageWithName:id]);
3817 - (NSArray *) statfs:(NSString *)path {
3820 if (path == nil || statfs([path UTF8String], &stat) == -1)
3823 return [NSArray arrayWithObjects:
3824 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3825 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3826 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3830 - (NSNumber *) du:(NSString *)path {
3831 NSNumber *value(nil);
3834 _assert(pipe(fds) != -1);
3836 pid_t pid(ExecFork());
3838 _assert(dup2(fds[1], 1) != -1);
3839 _assert(close(fds[0]) != -1);
3840 _assert(close(fds[1]) != -1);
3841 /* XXX: this should probably not use du */
3842 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3847 _assert(close(fds[1]) != -1);
3849 if (FILE *du = fdopen(fds[0], "r")) {
3851 while (fgets(line, sizeof(line), du) != NULL) {
3852 size_t length(strlen(line));
3853 while (length != 0 && line[length - 1] == '\n')
3854 line[--length] = '\0';
3855 if (char *tab = strchr(line, '\t')) {
3857 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3862 } else _assert(close(fds[0]));
3866 if (waitpid(pid, &status, 0) == -1)
3869 else _assert(false);
3878 - (void) installPackages:(NSArray *)packages {
3879 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3882 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3883 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3886 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3887 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3890 - (void) setSpecial:(id)function {
3891 [indirect_ setSpecial:function];
3894 - (void) setToken:(NSString *)token {
3897 Token_ = [token retain];
3899 [Metadata_ setObject:Token_ forKey:@"Token"];
3903 - (void) setPopupHook:(id)function {
3904 [indirect_ setPopupHook:function];
3907 - (void) setViewportWidth:(float)width {
3908 [indirect_ setViewportWidth:width];
3911 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3912 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3913 unsigned count([arguments count]);
3915 for (unsigned i(0); i != count; ++i)
3916 values[i] = [arguments objectAtIndex:i];
3917 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3920 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3921 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3923 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3925 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3931 /* Cydia Browser Controller {{{ */
3932 @interface CYBrowserController : BrowserController {
3933 CydiaObject *cydia_;
3938 @implementation CYBrowserController
3945 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3948 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3949 [super webView:view didClearWindowObject:window forFrame:frame];
3951 WebDataSource *source([frame dataSource]);
3952 NSURLResponse *response([source response]);
3953 NSURL *url([response URL]);
3954 NSString *scheme([url scheme]);
3956 NSHTTPURLResponse *http;
3957 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3958 http = (NSHTTPURLResponse *) response;
3962 NSDictionary *headers([http allHeaderFields]);
3963 NSString *host([url host]);
3964 [self setHeaders:headers forHost:host];
3967 [host isEqualToString:@"cydia.saurik.com"] ||
3968 [host hasSuffix:@".cydia.saurik.com"] ||
3969 [scheme isEqualToString:@"file"]
3971 [window setValue:cydia_ forKey:@"cydia"];
3974 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3975 if (System_ != NULL)
3976 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3977 if (Machine_ != NULL)
3978 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3980 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3982 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3985 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3986 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3987 [self _setMoreHeaders:copy];
3991 - (void) setDelegate:(id)delegate {
3992 [super setDelegate:delegate];
3993 [cydia_ setDelegate:delegate];
3997 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3998 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4000 WebView *webview([[webview_ _documentView] webView]);
4002 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4004 NSString *application = package == nil ? @"Cydia" : [NSString
4005 stringWithFormat:@"Cydia/%@",
4010 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4012 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4013 if (Product_ != nil)
4014 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4016 [webview setApplicationNameForUserAgent:application];
4023 /* Confirmation {{{ */
4024 @protocol ConfirmationControllerDelegate
4025 - (void) cancelAndClear:(bool)clear;
4026 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4030 @interface ConfirmationController : CYBrowserController {
4031 _transient Database *database_;
4032 UIAlertView *essential_;
4039 - (id) initWithDatabase:(Database *)database;
4043 @implementation ConfirmationController
4050 if (essential_ != nil)
4051 [essential_ release];
4055 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4056 NSString *context([alert context]);
4058 if ([context isEqualToString:@"remove"]) {
4059 if (button == [alert cancelButtonIndex]) {
4060 [self dismissModalViewControllerAnimated:YES];
4061 } else if (button == [alert firstOtherButtonIndex]) {
4064 [delegate_ confirmWithNavigationController:[self navigationController]];
4067 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4068 } else if ([context isEqualToString:@"unable"]) {
4069 [self dismissModalViewControllerAnimated:YES];
4070 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4072 [super alertView:alert clickedButtonAtIndex:button];
4076 - (void) _doContinue {
4077 [self dismissModalViewControllerAnimated:YES];
4078 [delegate_ cancelAndClear:NO];
4081 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4082 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4086 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4087 [super webView:view didClearWindowObject:window forFrame:frame];
4088 [window setValue:changes_ forKey:@"changes"];
4089 [window setValue:issues_ forKey:@"issues"];
4090 [window setValue:sizes_ forKey:@"sizes"];
4091 [window setValue:self forKey:@"queue"];
4094 - (id) initWithDatabase:(Database *)database {
4095 if ((self = [super init]) != nil) {
4096 database_ = database;
4098 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4100 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4101 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4102 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4103 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4104 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4108 pkgDepCache::Policy *policy([database_ policy]);
4110 pkgCacheFile &cache([database_ cache]);
4111 NSArray *packages = [database_ packages];
4112 for (Package *package in packages) {
4113 pkgCache::PkgIterator iterator = [package iterator];
4114 pkgDepCache::StateCache &state(cache[iterator]);
4116 NSString *name([package name]);
4118 if (state.NewInstall())
4119 [installing addObject:name];
4120 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4121 [reinstalling addObject:name];
4122 else if (state.Upgrade())
4123 [upgrading addObject:name];
4124 else if (state.Downgrade())
4125 [downgrading addObject:name];
4126 else if (state.Delete()) {
4127 if ([package essential])
4129 [removing addObject:name];
4132 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4133 substrate_ |= DepSubstrate(iterator.CurrentVer());
4138 else if (Advanced_) {
4139 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4141 essential_ = [[UIAlertView alloc]
4142 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4143 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4145 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4146 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4149 [essential_ setContext:@"remove"];
4151 essential_ = [[UIAlertView alloc]
4152 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4153 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4155 cancelButtonTitle:UCLocalize("OKAY")
4156 otherButtonTitles:nil
4159 [essential_ setContext:@"unable"];
4162 changes_ = [[NSArray alloc] initWithObjects:
4170 issues_ = [database_ issues];
4172 issues_ = [issues_ retain];
4174 sizes_ = [[NSArray alloc] initWithObjects:
4175 SizeString([database_ fetcher].FetchNeeded()),
4176 SizeString([database_ fetcher].PartialPresent()),
4179 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4181 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4182 initWithTitle:UCLocalize("CANCEL")
4183 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4184 style:UIBarButtonItemStylePlain
4186 action:@selector(cancelButtonClicked)
4191 - (void) applyRightButton {
4192 #if !AlwaysReload && !IgnoreInstall
4193 if (issues_ == nil && ![self isLoading])
4194 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4195 initWithTitle:UCLocalize("CONFIRM")
4196 style:UIBarButtonItemStylePlain
4198 action:@selector(confirmButtonClicked)
4201 [super applyRightButton];
4203 [[self navigationItem] setRightBarButtonItem:nil];
4207 - (void) cancelButtonClicked {
4208 [self dismissModalViewControllerAnimated:YES];
4209 [delegate_ cancelAndClear:YES];
4213 - (void) confirmButtonClicked {
4217 if (essential_ != nil)
4222 [delegate_ confirmWithNavigationController:[self navigationController]];
4230 /* Progress Data {{{ */
4231 @interface ProgressData : NSObject {
4233 // XXX: should these really both be _transient?
4234 _transient id target_;
4235 _transient id object_;
4238 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4245 @implementation ProgressData
4247 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4248 if ((self = [super init]) != nil) {
4249 selector_ = selector;
4269 /* Progress Controller {{{ */
4270 @interface ProgressController : CYViewController <
4271 ConfigurationDelegate,
4274 _transient Database *database_;
4275 UIProgressBar *progress_;
4276 UITextView *output_;
4277 UITextLabel *status_;
4278 UIPushButton *close_;
4280 SHA1SumValue springlist_;
4281 SHA1SumValue notifyconf_;
4285 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4287 - (void) _retachThread;
4288 - (void) _detachNewThreadData:(ProgressData *)data;
4289 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4295 @protocol ProgressControllerDelegate
4296 - (void) progressControllerIsComplete:(ProgressController *)sender;
4299 @implementation ProgressController
4302 [database_ setDelegate:nil];
4303 [progress_ release];
4312 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4313 if ((self = [super init]) != nil) {
4314 database_ = database;
4315 [database_ setDelegate:self];
4316 delegate_ = delegate;
4318 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4320 progress_ = [[UIProgressBar alloc] init];
4321 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4322 [progress_ setStyle:0];
4324 status_ = [[UITextLabel alloc] init];
4325 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4326 [status_ setColor:[UIColor whiteColor]];
4327 [status_ setBackgroundColor:[UIColor clearColor]];
4328 [status_ setCentersHorizontally:YES];
4329 //[status_ setFont:font];
4331 output_ = [[UITextView alloc] init];
4333 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4334 //[output_ setTextFont:@"Courier New"];
4335 [output_ setFont:[[output_ font] fontWithSize:12]];
4336 [output_ setTextColor:[UIColor whiteColor]];
4337 [output_ setBackgroundColor:[UIColor clearColor]];
4338 [output_ setMarginTop:0];
4339 [output_ setAllowsRubberBanding:YES];
4340 [output_ setEditable:NO];
4341 [[self view] addSubview:output_];
4343 close_ = [[UIPushButton alloc] init];
4344 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4345 [close_ setAutosizesToFit:NO];
4346 [close_ setDrawsShadow:YES];
4347 [close_ setStretchBackground:YES];
4348 [close_ setEnabled:YES];
4349 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4350 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4351 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4352 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4356 - (void) positionViews {
4357 CGRect bounds = [[self view] bounds];
4358 CGSize prgsize = [UIProgressBar defaultSize];
4361 (bounds.size.width - prgsize.width) / 2,
4362 bounds.size.height - prgsize.height - 20
4365 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4367 [progress_ setFrame:prgrect];
4368 [status_ setFrame:CGRectMake(
4370 bounds.size.height - prgsize.height - 50,
4371 bounds.size.width - 20,
4374 [output_ setFrame:CGRectMake(
4377 bounds.size.width - 20,
4378 bounds.size.height - 62
4380 [close_ setFrame:CGRectMake(
4381 (bounds.size.width - closewidth) / 2,
4382 bounds.size.height - prgsize.height - 50,
4388 - (void) viewWillAppear:(BOOL)animated {
4389 [super viewDidAppear:animated];
4390 [[self navigationItem] setHidesBackButton:YES];
4391 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4393 [self positionViews];
4396 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4397 [self positionViews];
4400 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4401 NSString *context([alert context]);
4403 if ([context isEqualToString:@"conffile"]) {
4404 FILE *input = [database_ input];
4405 if (button == [alert cancelButtonIndex])
4406 fprintf(input, "N\n");
4407 else if (button == [alert firstOtherButtonIndex])
4408 fprintf(input, "Y\n");
4413 - (void) closeButtonPushed {
4416 UpdateExternalStatus(0);
4420 [self dismissModalViewControllerAnimated:YES];
4424 [delegate_ terminateWithSuccess];
4425 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4426 [delegate_ suspendWithAnimation:YES];
4428 [delegate_ suspend];*/
4432 system("launchctl stop com.apple.SpringBoard");
4436 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4445 - (void) _retachThread {
4446 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4448 [[self view] addSubview:close_];
4449 [progress_ removeFromSuperview];
4450 [status_ removeFromSuperview];
4452 [database_ popErrorWithTitle:title_];
4453 [delegate_ progressControllerIsComplete:self];
4457 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4460 MMap mmap(file, MMap::ReadOnly);
4462 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4463 if (!(notifyconf_ == sha1.Result()))
4470 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4473 MMap mmap(file, MMap::ReadOnly);
4475 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4476 if (!(springlist_ == sha1.Result()))
4482 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4483 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4484 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4485 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4486 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4489 system("su -c /usr/bin/uicache mobile");
4491 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4493 [delegate_ setStatusBarShowsProgress:NO];
4496 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4497 [[data target] performSelector:[data selector] withObject:[data object]];
4498 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4501 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4502 UpdateExternalStatus(1);
4509 title_ = [title retain];
4511 [[self navigationItem] setTitle:title_];
4513 [status_ setText:nil];
4514 [output_ setText:@""];
4515 [progress_ setProgress:0];
4517 [close_ removeFromSuperview];
4518 [[self view] addSubview:progress_];
4519 [[self view] addSubview:status_];
4521 [delegate_ setStatusBarShowsProgress:YES];
4526 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4529 MMap mmap(file, MMap::ReadOnly);
4531 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4532 notifyconf_ = sha1.Result();
4538 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4541 MMap mmap(file, MMap::ReadOnly);
4543 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4544 springlist_ = sha1.Result();
4549 detachNewThreadSelector:@selector(_detachNewThreadData:)
4551 withObject:[[[ProgressData alloc]
4552 initWithSelector:selector
4559 - (void) repairWithSelector:(SEL)selector {
4561 detachNewThreadSelector:selector
4564 title:UCLocalize("REPAIRING")
4568 - (void) setConfigurationData:(NSString *)data {
4570 performSelectorOnMainThread:@selector(_setConfigurationData:)
4576 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4577 CYActionSheet *sheet([[[CYActionSheet alloc]
4579 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4580 defaultButtonIndex:0
4583 [sheet setMessage:error];
4584 [sheet yieldToPopupAlertAnimated:YES];
4588 - (void) setProgressTitle:(NSString *)title {
4590 performSelectorOnMainThread:@selector(_setProgressTitle:)
4596 - (void) setProgressPercent:(float)percent {
4598 performSelectorOnMainThread:@selector(_setProgressPercent:)
4599 withObject:[NSNumber numberWithFloat:percent]
4604 - (void) startProgress {
4607 - (void) addProgressOutput:(NSString *)output {
4609 performSelectorOnMainThread:@selector(_addProgressOutput:)
4615 - (bool) isCancelling:(size_t)received {
4619 - (void) _setConfigurationData:(NSString *)data {
4620 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4622 if (!conffile_r(data)) {
4623 lprintf("E:invalid conffile\n");
4627 NSString *ofile = conffile_r[1];
4628 //NSString *nfile = conffile_r[2];
4630 UIAlertView *alert = [[[UIAlertView alloc]
4631 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4632 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4634 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4635 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4636 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4640 [alert setContext:@"conffile"];
4644 - (void) _setProgressTitle:(NSString *)title {
4645 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4646 for (size_t i(0), e([words count]); i != e; ++i) {
4647 NSString *word([words objectAtIndex:i]);
4648 if (Package *package = [database_ packageWithName:word])
4649 [words replaceObjectAtIndex:i withObject:[package name]];
4652 [status_ setText:[words componentsJoinedByString:@" "]];
4655 - (void) _setProgressPercent:(NSNumber *)percent {
4656 [progress_ setProgress:[percent floatValue]];
4659 - (void) _addProgressOutput:(NSString *)output {
4660 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4661 CGSize size = [output_ contentSize];
4662 CGRect rect = {{0, size.height}, {size.width, 0}};
4663 [output_ scrollRectToVisible:rect animated:YES];
4666 - (BOOL) isRunning {
4673 /* Cell Content View {{{ */
4674 @protocol ContentDelegate
4675 - (void) drawContentRect:(CGRect)rect;
4678 @interface ContentView : UIView {
4679 _transient id<ContentDelegate> delegate_;
4684 @implementation ContentView
4686 - (id) initWithFrame:(CGRect)frame {
4687 if ((self = [super initWithFrame:frame]) != nil) {
4688 [self setNeedsDisplayOnBoundsChange:YES];
4692 - (void) setDelegate:(id<ContentDelegate>)delegate {
4693 delegate_ = delegate;
4696 - (void) drawRect:(CGRect)rect {
4697 [super drawRect:rect];
4698 [delegate_ drawContentRect:rect];
4703 /* Cydia TableView Cell {{{ */
4704 @interface CYTableViewCell : UITableViewCell {
4705 ContentView *content_;
4711 @implementation CYTableViewCell
4718 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4719 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4721 if (view == content_) {
4722 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4723 highlighted_ = highlighted;
4726 [super _updateHighlightColorsForView:view highlighted:highlighted];
4729 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4730 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4731 highlighted_ = selected;
4733 [super setSelected:selected animated:animated];
4734 [content_ setNeedsDisplay];
4739 /* Package Cell {{{ */
4740 @interface PackageCell : CYTableViewCell <
4745 NSString *description_;
4753 - (PackageCell *) init;
4754 - (void) setPackage:(Package *)package;
4756 + (int) heightForPackage:(Package *)package;
4757 - (void) drawContentRect:(CGRect)rect;
4761 @implementation PackageCell
4763 - (void) clearPackage {
4774 if (description_ != nil) {
4775 [description_ release];
4779 if (source_ != nil) {
4784 if (badge_ != nil) {
4789 if (placard_ != nil) {
4799 [self clearPackage];
4803 - (PackageCell *) init {
4804 CGRect frame(CGRectMake(0, 0, 320, 74));
4805 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4806 UIView *content([self contentView]);
4807 CGRect bounds([content bounds]);
4809 content_ = [[ContentView alloc] initWithFrame:bounds];
4810 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4811 [content addSubview:content_];
4813 [content_ setDelegate:self];
4814 [content_ setOpaque:YES];
4818 - (void) _setBackgroundColor {
4820 if (NSString *mode = [package_ mode]) {
4821 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4822 color = remove ? RemovingColor_ : InstallingColor_;
4824 color = [UIColor whiteColor];
4826 [content_ setBackgroundColor:color];
4827 [self setNeedsDisplay];
4830 - (void) setPackage:(Package *)package {
4831 [self clearPackage];
4834 Source *source = [package source];
4836 icon_ = [[package icon] retain];
4837 name_ = [[package name] retain];
4840 description_ = [package longDescription];
4841 if (description_ == nil)
4842 description_ = [package shortDescription];
4843 if (description_ != nil)
4844 description_ = [description_ retain];
4846 commercial_ = [package isCommercial];
4848 package_ = [package retain];
4850 NSString *label = nil;
4851 bool trusted = false;
4853 if (source != nil) {
4854 label = [source label];
4855 trusted = [source trusted];
4856 } else if ([[package id] isEqualToString:@"firmware"])
4857 label = UCLocalize("APPLE");
4859 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4861 NSString *from(label);
4863 NSString *section = [package simpleSection];
4864 if (section != nil && ![section isEqualToString:label]) {
4865 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4866 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4869 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4870 source_ = [from retain];
4872 if (NSString *purpose = [package primaryPurpose])
4873 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4874 badge_ = [badge_ retain];
4876 if ([package installed] != nil)
4877 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4878 placard_ = [placard_ retain];
4880 [self _setBackgroundColor];
4881 [content_ setNeedsDisplay];
4884 - (void) drawContentRect:(CGRect)rect {
4885 bool highlighted(highlighted_);
4886 float width([self bounds].size.width);
4889 CGContextRef context(UIGraphicsGetCurrentContext());
4890 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4891 CGContextFillRect(context, rect);
4896 rect.size = [icon_ size];
4898 rect.size.width /= 2;
4899 rect.size.height /= 2;
4901 rect.origin.x = 25 - rect.size.width / 2;
4902 rect.origin.y = 25 - rect.size.height / 2;
4904 [icon_ drawInRect:rect];
4907 if (badge_ != nil) {
4908 CGSize size = [badge_ size];
4910 [badge_ drawAtPoint:CGPointMake(
4911 36 - size.width / 2,
4912 36 - size.height / 2
4920 UISetColor(commercial_ ? Purple_ : Black_);
4921 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4922 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4925 UISetColor(commercial_ ? Purplish_ : Gray_);
4926 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4928 if (placard_ != nil)
4929 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4932 + (int) heightForPackage:(Package *)package {
4938 /* Section Cell {{{ */
4939 @interface SectionCell : CYTableViewCell <
4951 - (void) setSection:(Section *)section editing:(BOOL)editing;
4955 @implementation SectionCell
4957 - (void) clearSection {
4958 if (basic_ != nil) {
4963 if (section_ != nil) {
4973 if (count_ != nil) {
4980 [self clearSection];
4986 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4987 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4988 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4989 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4990 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4992 UIView *content([self contentView]);
4993 CGRect bounds([content bounds]);
4995 content_ = [[ContentView alloc] initWithFrame:bounds];
4996 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4997 [content addSubview:content_];
4998 [content_ setBackgroundColor:[UIColor whiteColor]];
5000 [content_ setDelegate:self];
5004 - (void) onSwitch:(id)sender {
5005 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5006 if (metadata == nil) {
5007 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5008 [Sections_ setObject:metadata forKey:basic_];
5011 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5015 - (void) setSection:(Section *)section editing:(BOOL)editing {
5016 if (editing != editing_) {
5018 [switch_ removeFromSuperview];
5020 [self addSubview:switch_];
5024 [self clearSection];
5026 if (section == nil) {
5027 name_ = [UCLocalize("ALL_PACKAGES") retain];
5030 basic_ = [section name];
5032 basic_ = [basic_ retain];
5034 section_ = [section localized];
5035 if (section_ != nil)
5036 section_ = [section_ retain];
5038 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5039 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5042 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5045 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5046 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5048 [content_ setNeedsDisplay];
5051 - (void) setFrame:(CGRect)frame {
5052 [super setFrame:frame];
5054 CGRect rect([switch_ frame]);
5055 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5058 - (void) drawContentRect:(CGRect)rect {
5059 bool highlighted(highlighted_);
5061 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5066 float width(rect.size.width);
5072 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5074 CGSize size = [count_ sizeWithFont:Font14_];
5078 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5084 /* File Table {{{ */
5085 @interface FileTable : CYViewController <
5086 UITableViewDataSource,
5089 _transient Database *database_;
5092 NSMutableArray *files_;
5096 - (id) initWithDatabase:(Database *)database;
5097 - (void) setPackage:(Package *)package;
5101 @implementation FileTable
5104 if (package_ != nil)
5113 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5114 return files_ == nil ? 0 : [files_ count];
5117 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5121 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5122 static NSString *reuseIdentifier = @"Cell";
5124 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5126 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5127 [cell setFont:[UIFont systemFontOfSize:16]];
5129 [cell setText:[files_ objectAtIndex:indexPath.row]];
5130 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5135 - (id) initWithDatabase:(Database *)database {
5136 if ((self = [super init]) != nil) {
5137 database_ = database;
5139 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5141 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5143 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5144 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5145 [list_ setRowHeight:24.0f];
5146 [[self view] addSubview:list_];
5148 [list_ setDataSource:self];
5149 [list_ setDelegate:self];
5153 - (void) setPackage:(Package *)package {
5154 if (package_ != nil) {
5155 [package_ autorelease];
5164 [files_ removeAllObjects];
5166 if (package != nil) {
5167 package_ = [package retain];
5168 name_ = [[package id] retain];
5170 if (NSArray *files = [package files])
5171 [files_ addObjectsFromArray:files];
5173 if ([files_ count] != 0) {
5174 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5175 [files_ removeObjectAtIndex:0];
5176 [files_ sortUsingSelector:@selector(compareByPath:)];
5178 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5179 [stack addObject:@"/"];
5181 for (int i(0), e([files_ count]); i != e; ++i) {
5182 NSString *file = [files_ objectAtIndex:i];
5183 while (![file hasPrefix:[stack lastObject]])
5184 [stack removeLastObject];
5185 NSString *directory = [stack lastObject];
5186 [stack addObject:[file stringByAppendingString:@"/"]];
5187 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5188 ([stack count] - 2) * 3, "",
5189 [file substringFromIndex:[directory length]]
5198 - (void) reloadData {
5199 [self setPackage:[database_ packageWithName:name_]];
5204 /* Package Controller {{{ */
5205 @interface PackageController : CYBrowserController <
5206 UIActionSheetDelegate
5208 _transient Database *database_;
5212 NSMutableArray *buttons_;
5213 UIBarButtonItem *button_;
5216 - (id) initWithDatabase:(Database *)database;
5217 - (void) setPackage:(Package *)package;
5221 @implementation PackageController
5224 if (package_ != nil)
5238 if ([self retainCount] == 1)
5239 [delegate_ setPackageController:self];
5243 /* XXX: this is not safe at all... localization of /fail/ */
5244 - (void) _clickButtonWithName:(NSString *)name {
5245 if ([name isEqualToString:UCLocalize("CLEAR")])
5246 [delegate_ clearPackage:package_];
5247 else if ([name isEqualToString:UCLocalize("INSTALL")])
5248 [delegate_ installPackage:package_];
5249 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5250 [delegate_ installPackage:package_];
5251 else if ([name isEqualToString:UCLocalize("REMOVE")])
5252 [delegate_ removePackage:package_];
5253 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5254 [delegate_ installPackage:package_];
5255 else _assert(false);
5258 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5259 NSString *context([sheet context]);
5261 if ([context isEqualToString:@"modify"]) {
5262 if (button != [sheet cancelButtonIndex]) {
5263 NSString *buttonName = [buttons_ objectAtIndex:button];
5264 [self _clickButtonWithName:buttonName];
5267 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5271 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5272 [super webView:view didClearWindowObject:window forFrame:frame];
5273 [window setValue:package_ forKey:@"package"];
5276 - (bool) _allowJavaScriptPanel {
5281 - (void) _customButtonClicked {
5282 int count([buttons_ count]);
5287 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5289 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5290 [buttons addObjectsFromArray:buttons_];
5292 UIActionSheet *sheet = [[[UIActionSheet alloc]
5295 cancelButtonTitle:nil
5296 destructiveButtonTitle:nil
5297 otherButtonTitles:nil
5300 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5302 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5303 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5305 [sheet setContext:@"modify"];
5307 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5311 // We don't want to allow non-commercial packages to do custom things to the install button,
5312 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5313 - (void) customButtonClicked {
5315 [super customButtonClicked];
5317 [self _customButtonClicked];
5320 - (void) reloadButtonClicked {
5321 // Don't reload a package view by clicking the button.
5324 - (void) applyLoadingTitle {
5325 // Don't show "Loading" as the title. Ever.
5328 - (UIBarButtonItem *) rightButton {
5333 - (id) initWithDatabase:(Database *)database {
5334 if ((self = [super init]) != nil) {
5335 database_ = database;
5336 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5337 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5341 - (void) setPackage:(Package *)package {
5342 if (package_ != nil) {
5343 [package_ autorelease];
5352 [buttons_ removeAllObjects];
5354 if (package != nil) {
5357 package_ = [package retain];
5358 name_ = [[package id] retain];
5359 commercial_ = [package isCommercial];
5361 if ([package_ mode] != nil)
5362 [buttons_ addObject:UCLocalize("CLEAR")];
5363 if ([package_ source] == nil);
5364 else if ([package_ upgradableAndEssential:NO])
5365 [buttons_ addObject:UCLocalize("UPGRADE")];
5366 else if ([package_ uninstalled])
5367 [buttons_ addObject:UCLocalize("INSTALL")];
5369 [buttons_ addObject:UCLocalize("REINSTALL")];
5370 if (![package_ uninstalled])
5371 [buttons_ addObject:UCLocalize("REMOVE")];
5378 switch ([buttons_ count]) {
5379 case 0: title = nil; break;
5380 case 1: title = [buttons_ objectAtIndex:0]; break;
5381 default: title = UCLocalize("MODIFY"); break;
5384 button_ = [[UIBarButtonItem alloc]
5386 style:UIBarButtonItemStylePlain
5388 action:@selector(customButtonClicked)
5394 - (bool) isLoading {
5395 return commercial_ ? [super isLoading] : false;
5398 - (void) reloadData {
5399 [self setPackage:[database_ packageWithName:name_]];
5404 /* Package Table {{{ */
5405 @interface PackageTable : UIView <
5406 UITableViewDataSource,
5409 _transient Database *database_;
5410 NSMutableArray *packages_;
5411 NSMutableArray *sections_;
5413 NSMutableArray *index_;
5414 NSMutableDictionary *indices_;
5415 // XXX: this target_ seems to be delegate_. :(
5416 _transient id target_;
5418 // XXX: why do we even have this delegate_?
5419 _transient id delegate_;
5422 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5424 - (void) setDelegate:(id)delegate;
5426 - (void) reloadData;
5427 - (void) resetCursor;
5429 - (UITableView *) list;
5431 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5433 - (void) deselectWithAnimation:(BOOL)animated;
5437 @implementation PackageTable
5440 [packages_ release];
5441 [sections_ release];
5449 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5450 NSInteger count([sections_ count]);
5451 return count == 0 ? 1 : count;
5454 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5455 if ([sections_ count] == 0)
5457 return [[sections_ objectAtIndex:section] name];
5460 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5461 if ([sections_ count] == 0)
5463 return [[sections_ objectAtIndex:section] count];
5466 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5467 Section *section([sections_ objectAtIndex:[path section]]);
5468 NSInteger row([path row]);
5469 Package *package([packages_ objectAtIndex:([section row] + row)]);
5473 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5474 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5476 cell = [[[PackageCell alloc] init] autorelease];
5477 [cell setPackage:[self packageAtIndexPath:path]];
5481 - (void) deselectWithAnimation:(BOOL)animated {
5482 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5485 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5486 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5489 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5490 Package *package([self packageAtIndexPath:path]);
5491 package = [database_ packageWithName:[package id]];
5492 [target_ performSelector:action_ withObject:package];
5496 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5497 return [packages_ count] > 20 ? index_ : nil;
5500 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5504 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5505 if ((self = [super initWithFrame:frame]) != nil) {
5506 database_ = database;
5511 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5512 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5514 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5515 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5517 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5518 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5519 [list_ setRowHeight:73.0f];
5520 [self addSubview:list_];
5522 [list_ setDataSource:self];
5523 [list_ setDelegate:self];
5527 - (void) setDelegate:(id)delegate {
5528 delegate_ = delegate;
5531 - (bool) hasPackage:(Package *)package {
5535 - (void) reloadData {
5536 NSArray *packages = [database_ packages];
5538 [packages_ removeAllObjects];
5539 [sections_ removeAllObjects];
5541 _profile(PackageTable$reloadData$Filter)
5542 for (Package *package in packages)
5543 if ([self hasPackage:package])
5544 [packages_ addObject:package];
5547 [index_ removeAllObjects];
5548 [indices_ removeAllObjects];
5550 Section *section = nil;
5552 _profile(PackageTable$reloadData$Section)
5553 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5557 _profile(PackageTable$reloadData$Section$Package)
5558 package = [packages_ objectAtIndex:offset];
5559 index = [package index];
5562 if (section == nil || [section index] != index) {
5563 _profile(PackageTable$reloadData$Section$Allocate)
5564 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5567 [index_ addObject:[section name]];
5568 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5570 _profile(PackageTable$reloadData$Section$Add)
5571 [sections_ addObject:section];
5575 [section addToCount];
5579 _profile(PackageTable$reloadData$List)
5584 - (void) resetCursor {
5585 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5588 - (UITableView *) list {
5592 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5593 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5598 /* Filtered Package Table {{{ */
5599 @interface FilteredPackageTable : PackageTable {
5605 - (void) setObject:(id)object;
5606 - (void) setObject:(id)object forFilter:(SEL)filter;
5608 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5612 @implementation FilteredPackageTable
5620 - (void) setFilter:(SEL)filter {
5623 /* XXX: this is an unsafe optimization of doomy hell */
5624 Method method(class_getInstanceMethod([Package class], filter));
5625 _assert(method != NULL);
5626 imp_ = method_getImplementation(method);
5627 _assert(imp_ != NULL);
5630 - (void) setObject:(id)object {
5636 object_ = [object retain];
5639 - (void) setObject:(id)object forFilter:(SEL)filter {
5640 [self setFilter:filter];
5641 [self setObject:object];
5644 - (bool) hasPackage:(Package *)package {
5645 _profile(FilteredPackageTable$hasPackage)
5646 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5650 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5651 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5652 [self setFilter:filter];
5653 object_ = [object retain];
5661 /* Filtered Package Controller {{{ */
5662 @interface FilteredPackageController : CYViewController {
5663 _transient Database *database_;
5664 FilteredPackageTable *packages_;
5668 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5672 @implementation FilteredPackageController
5675 [packages_ release];
5681 - (void) viewDidAppear:(BOOL)animated {
5682 [super viewDidAppear:animated];
5683 [packages_ deselectWithAnimation:animated];
5686 - (void) didSelectPackage:(Package *)package {
5687 PackageController *view([delegate_ packageController]);
5688 [view setPackage:package];
5689 [view setDelegate:delegate_];
5690 [[self navigationController] pushViewController:view animated:YES];
5693 - (NSString *) title { return title_; }
5695 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5696 if ((self = [super init]) != nil) {
5697 database_ = database;
5698 title_ = [title copy];
5699 [[self navigationItem] setTitle:title_];
5701 packages_ = [[FilteredPackageTable alloc]
5702 initWithFrame:[[self view] bounds]
5705 action:@selector(didSelectPackage:)
5710 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5711 [[self view] addSubview:packages_];
5715 - (void) reloadData {
5716 [packages_ reloadData];
5719 - (void) setDelegate:(id)delegate {
5720 [super setDelegate:delegate];
5721 [packages_ setDelegate:delegate];
5728 /* Add Source Controller {{{ */
5729 @interface AddSourceController : CYViewController {
5730 _transient Database *database_;
5733 - (id) initWithDatabase:(Database *)database;
5737 @implementation AddSourceController
5739 - (id) initWithDatabase:(Database *)database {
5740 if ((self = [super init]) != nil) {
5741 database_ = database;
5747 /* Source Cell {{{ */
5748 @interface SourceCell : CYTableViewCell <
5753 NSString *description_;
5757 - (void) setSource:(Source *)source;
5761 @implementation SourceCell
5763 - (void) clearSource {
5766 [description_ release];
5775 - (void) setSource:(Source *)source {
5779 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5781 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5782 icon_ = [icon_ retain];
5784 origin_ = [[source name] retain];
5785 label_ = [[source uri] retain];
5786 description_ = [[source description] retain];
5788 [content_ setNeedsDisplay];
5796 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5797 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5798 UIView *content([self contentView]);
5799 CGRect bounds([content bounds]);
5801 content_ = [[ContentView alloc] initWithFrame:bounds];
5802 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5803 [content_ setBackgroundColor:[UIColor whiteColor]];
5804 [content addSubview:content_];
5806 [content_ setDelegate:self];
5807 [content_ setOpaque:YES];
5811 - (void) drawContentRect:(CGRect)rect {
5812 bool highlighted(highlighted_);
5813 float width(rect.size.width);
5816 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5823 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5827 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5831 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5836 /* Source Table {{{ */
5837 @interface SourceTable : CYViewController <
5838 UITableViewDataSource,
5841 _transient Database *database_;
5843 NSMutableArray *sources_;
5847 UIProgressHUD *hud_;
5850 //NSURLConnection *installer_;
5851 NSURLConnection *trivial_;
5852 NSURLConnection *trivial_bz2_;
5853 NSURLConnection *trivial_gz_;
5854 //NSURLConnection *automatic_;
5859 - (id) initWithDatabase:(Database *)database;
5861 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5865 @implementation SourceTable
5867 - (void) _releaseConnection:(NSURLConnection *)connection {
5868 if (connection != nil) {
5869 [connection cancel];
5870 //[connection setDelegate:nil];
5871 [connection release];
5883 //[self _releaseConnection:installer_];
5884 [self _releaseConnection:trivial_];
5885 [self _releaseConnection:trivial_gz_];
5886 [self _releaseConnection:trivial_bz2_];
5887 //[self _releaseConnection:automatic_];
5894 - (void) viewDidAppear:(BOOL)animated {
5895 [super viewDidAppear:animated];
5896 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5899 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5900 return offset_ == 0 ? 1 : 2;
5903 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5904 switch (section + (offset_ == 0 ? 1 : 0)) {
5905 case 0: return UCLocalize("ENTERED_BY_USER");
5906 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5912 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5913 int count = [sources_ count];
5915 case 0: return (offset_ == 0 ? count : offset_);
5916 case 1: return count - offset_;
5922 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5924 switch (indexPath.section) {
5925 case 0: idx = indexPath.row; break;
5926 case 1: idx = indexPath.row + offset_; break;
5930 return [sources_ objectAtIndex:idx];
5933 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5934 Source *source = [self sourceAtIndexPath:indexPath];
5935 return [source description] == nil ? 56 : 73;
5938 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5939 static NSString *cellIdentifier = @"SourceCell";
5941 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5942 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5943 [cell setSource:[self sourceAtIndexPath:indexPath]];
5948 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5949 return UITableViewCellAccessoryDisclosureIndicator;
5952 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5953 Source *source = [self sourceAtIndexPath:indexPath];
5955 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5956 initWithDatabase:database_
5957 title:[source label]
5958 filter:@selector(isVisibleInSource:)
5962 [packages setDelegate:delegate_];
5964 [[self navigationController] pushViewController:packages animated:YES];
5967 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5968 Source *source = [self sourceAtIndexPath:indexPath];
5969 return [source record] != nil;
5972 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5973 Source *source = [self sourceAtIndexPath:indexPath];
5974 [Sources_ removeObjectForKey:[source key]];
5975 [delegate_ syncData];
5979 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5982 @"./", @"Distribution",
5983 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5985 [delegate_ syncData];
5988 - (NSString *) getWarning {
5989 NSString *href(href_);
5990 NSRange colon([href rangeOfString:@"://"]);
5991 if (colon.location != NSNotFound)
5992 href = [href substringFromIndex:(colon.location + 3)];
5993 href = [href stringByAddingPercentEscapes];
5994 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5995 href = [href stringByCachingURLWithCurrentCDN];
5997 NSURL *url([NSURL URLWithString:href]);
5999 NSStringEncoding encoding;
6000 NSError *error(nil);
6002 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
6003 return [warning length] == 0 ? nil : warning;
6007 - (void) _endConnection:(NSURLConnection *)connection {
6008 // XXX: the memory management in this method is horribly awkward
6010 NSURLConnection **field = NULL;
6011 if (connection == trivial_)
6013 else if (connection == trivial_bz2_)
6014 field = &trivial_bz2_;
6015 else if (connection == trivial_gz_)
6016 field = &trivial_gz_;
6017 _assert(field != NULL);
6018 [connection release];
6023 trivial_bz2_ == nil &&
6029 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6032 UIAlertView *alert = [[[UIAlertView alloc]
6033 initWithTitle:UCLocalize("SOURCE_WARNING")
6036 cancelButtonTitle:UCLocalize("CANCEL")
6037 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6040 [alert setContext:@"warning"];
6041 [alert setNumberOfRows:1];
6045 } else if (error_ != nil) {
6046 UIAlertView *alert = [[[UIAlertView alloc]
6047 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6048 message:[error_ localizedDescription]
6050 cancelButtonTitle:UCLocalize("OK")
6051 otherButtonTitles:nil
6054 [alert setContext:@"urlerror"];
6057 UIAlertView *alert = [[[UIAlertView alloc]
6058 initWithTitle:UCLocalize("NOT_REPOSITORY")
6059 message:UCLocalize("NOT_REPOSITORY_EX")
6061 cancelButtonTitle:UCLocalize("OK")
6062 otherButtonTitles:nil
6065 [alert setContext:@"trivial"];
6069 [delegate_ setStatusBarShowsProgress:NO];
6070 [delegate_ removeProgressHUD:hud_];
6080 if (error_ != nil) {
6087 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6088 switch ([response statusCode]) {
6094 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6095 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6097 error_ = [error retain];
6098 [self _endConnection:connection];
6101 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6102 [self _endConnection:connection];
6105 - (NSString *) title { return UCLocalize("SOURCES"); }
6107 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6108 NSMutableURLRequest *request = [NSMutableURLRequest
6109 requestWithURL:[NSURL URLWithString:href]
6110 cachePolicy:NSURLRequestUseProtocolCachePolicy
6111 timeoutInterval:120.0
6114 [request setHTTPMethod:method];
6116 if (Machine_ != NULL)
6117 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6118 if (UniqueID_ != nil)
6119 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6121 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6123 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6126 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6127 NSString *context([alert context]);
6129 if ([context isEqualToString:@"source"]) {
6132 NSString *href = [[alert textField] text];
6134 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6136 if (![href hasSuffix:@"/"])
6137 href_ = [href stringByAppendingString:@"/"];
6140 href_ = [href_ retain];
6142 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6143 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6144 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6145 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6149 // XXX: this is stupid
6150 hud_ = [[delegate_ addProgressHUD] retain];
6151 [hud_ setText:UCLocalize("VERIFYING_URL")];
6160 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6161 } else if ([context isEqualToString:@"trivial"])
6162 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6163 else if ([context isEqualToString:@"urlerror"])
6164 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6165 else if ([context isEqualToString:@"warning"]) {
6180 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6184 - (id) initWithDatabase:(Database *)database {
6185 if ((self = [super init]) != nil) {
6186 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6187 [self updateButtonsForEditingStatus:NO animated:NO];
6189 database_ = database;
6190 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6192 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6193 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6194 [[self view] addSubview:list_];
6196 [list_ setDataSource:self];
6197 [list_ setDelegate:self];
6203 - (void) reloadData {
6205 if (!list.ReadMainList())
6208 [sources_ removeAllObjects];
6209 [sources_ addObjectsFromArray:[database_ sources]];
6211 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6214 int count([sources_ count]);
6216 for (int i = 0; i != count; i++) {
6217 if ([[sources_ objectAtIndex:i] record] == nil)
6222 [list_ setEditing:NO];
6223 [self updateButtonsForEditingStatus:NO animated:NO];
6227 - (void) addButtonClicked {
6228 /*[book_ pushPage:[[[AddSourceController alloc]
6233 UIAlertView *alert = [[[UIAlertView alloc]
6234 initWithTitle:UCLocalize("ENTER_APT_URL")
6237 cancelButtonTitle:UCLocalize("CANCEL")
6238 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6241 [alert setContext:@"source"];
6242 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6244 [alert setNumberOfRows:1];
6245 [alert addTextFieldWithValue:@"http://" label:@""];
6247 UITextInputTraits *traits = [[alert textField] textInputTraits];
6248 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6249 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6250 [traits setKeyboardType:UIKeyboardTypeURL];
6251 // XXX: UIReturnKeyDone
6252 [traits setReturnKeyType:UIReturnKeyNext];
6257 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6258 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6259 initWithTitle:UCLocalize("ADD")
6260 style:UIBarButtonItemStylePlain
6262 action:@selector(addButtonClicked)
6263 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6265 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6266 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6267 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6269 action:@selector(editButtonClicked)
6270 ] autorelease] animated:animated];
6272 if (IsWildcat_ && !editing)
6273 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6274 initWithTitle:UCLocalize("SETTINGS")
6275 style:UIBarButtonItemStylePlain
6277 action:@selector(settingsButtonClicked)
6281 - (void) settingsButtonClicked {
6282 [delegate_ showSettings];
6285 - (void) editButtonClicked {
6286 [list_ setEditing:![list_ isEditing] animated:YES];
6288 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6294 /* Installed Controller {{{ */
6295 @interface InstalledController : FilteredPackageController {
6299 - (id) initWithDatabase:(Database *)database;
6301 - (void) updateRoleButton;
6302 - (void) queueStatusDidChange;
6306 @implementation InstalledController
6312 - (NSString *) title { return UCLocalize("INSTALLED"); }
6314 - (id) initWithDatabase:(Database *)database {
6315 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6316 [self updateRoleButton];
6317 [self queueStatusDidChange];
6322 - (void) queueButtonClicked {
6327 - (void) queueStatusDidChange {
6331 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6332 initWithTitle:UCLocalize("QUEUE")
6333 style:UIBarButtonItemStyleDone
6335 action:@selector(queueButtonClicked)
6338 [[self navigationItem] setLeftBarButtonItem:nil];
6344 - (void) reloadData {
6345 [packages_ reloadData];
6348 - (void) updateRoleButton {
6349 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6350 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6351 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6352 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6354 action:@selector(roleButtonClicked)
6358 - (void) roleButtonClicked {
6359 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6360 [packages_ reloadData];
6363 [self updateRoleButton];
6366 - (void) setDelegate:(id)delegate {
6367 [super setDelegate:delegate];
6368 [packages_ setDelegate:delegate];
6374 /* Home Controller {{{ */
6375 @interface HomeController : CYBrowserController {
6380 @implementation HomeController
6382 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6383 [super _setMoreHeaders:request];
6386 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6387 if (UniqueID_ != nil)
6388 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6390 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6393 - (void) aboutButtonClicked {
6394 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6396 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6397 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6398 [alert setCancelButtonIndex:0];
6401 @"Copyright (C) 2008-2010\n"
6402 "Jay Freeman (saurik)\n"
6403 "saurik@saurik.com\n"
6404 "http://www.saurik.com/"
6410 - (void) viewWillAppear:(BOOL)animated {
6411 [super viewWillAppear:animated];
6412 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6415 - (void) viewWillDisappear:(BOOL)animated {
6416 [super viewWillDisappear:animated];
6417 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6421 if ((self = [super init]) != nil) {
6422 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6423 initWithTitle:UCLocalize("ABOUT")
6424 style:UIBarButtonItemStylePlain
6426 action:@selector(aboutButtonClicked)
6433 /* Manage Controller {{{ */
6434 @interface ManageController : CYBrowserController {
6437 - (void) queueStatusDidChange;
6440 @implementation ManageController
6443 if ((self = [super init]) != nil) {
6444 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6446 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6447 initWithTitle:UCLocalize("SETTINGS")
6448 style:UIBarButtonItemStylePlain
6450 action:@selector(settingsButtonClicked)
6453 [self queueStatusDidChange];
6457 - (void) settingsButtonClicked {
6458 [delegate_ showSettings];
6462 - (void) queueButtonClicked {
6466 - (void) applyLoadingTitle {
6467 // No "Loading" title.
6470 - (void) applyRightButton {
6475 - (void) queueStatusDidChange {
6477 if (!IsWildcat_ && Queuing_) {
6478 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6479 initWithTitle:UCLocalize("QUEUE")
6480 style:UIBarButtonItemStyleDone
6482 action:@selector(queueButtonClicked)
6485 [[self navigationItem] setRightBarButtonItem:nil];
6490 - (bool) isLoading {
6497 /* Refresh Bar {{{ */
6498 @interface RefreshBar : UINavigationBar {
6499 UIProgressIndicator *indicator_;
6500 UITextLabel *prompt_;
6501 UIProgressBar *progress_;
6502 UINavigationButton *cancel_;
6507 @implementation RefreshBar
6510 [indicator_ release];
6512 [progress_ release];
6517 - (void) positionViews {
6518 CGRect frame = [cancel_ frame];
6519 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6520 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6521 [cancel_ setFrame:frame];
6523 CGSize prgsize = {75, 100};
6525 [self frame].size.width - prgsize.width - 10,
6526 ([self frame].size.height - prgsize.height) / 2
6528 [progress_ setFrame:prgrect];
6530 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6531 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6532 CGRect indrect = {{indoffset, indoffset}, indsize};
6533 [indicator_ setFrame:indrect];
6535 CGSize prmsize = {215, indsize.height + 4};
6537 indoffset * 2 + indsize.width,
6538 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6540 [prompt_ setFrame:prmrect];
6543 - (void)setFrame:(CGRect)frame {
6544 [super setFrame:frame];
6546 [self positionViews];
6549 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6550 if ((self = [super initWithFrame:frame])) {
6551 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6553 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6554 [self setBarStyle:UIBarStyleBlack];
6556 UIBarStyle barstyle([self _barStyle:NO]);
6557 bool ugly(barstyle == UIBarStyleDefault);
6559 UIProgressIndicatorStyle style = ugly ?
6560 UIProgressIndicatorStyleMediumBrown :
6561 UIProgressIndicatorStyleMediumWhite;
6563 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6564 [indicator_ setStyle:style];
6565 [indicator_ startAnimation];
6566 [self addSubview:indicator_];
6568 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6569 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6570 [prompt_ setBackgroundColor:[UIColor clearColor]];
6571 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6572 [self addSubview:prompt_];
6574 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6575 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6576 [progress_ setStyle:0];
6577 [self addSubview:progress_];
6579 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6580 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6581 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6582 [cancel_ setBarStyle:barstyle];
6584 [self positionViews];
6589 [cancel_ removeFromSuperview];
6593 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6594 [progress_ setProgress:0];
6595 [self addSubview:cancel_];
6599 [cancel_ removeFromSuperview];
6602 - (void) setPrompt:(NSString *)prompt {
6603 [prompt_ setText:prompt];
6606 - (void) setProgress:(float)progress {
6607 [progress_ setProgress:progress];
6613 @class CYNavigationController;
6615 /* Cydia Tab Bar Controller {{{ */
6616 @interface CYTabBarController : UITabBarController {
6617 _transient Database *database_;
6622 @implementation CYTabBarController
6624 /* XXX: some logic should probably go here related to
6625 freeing the view controllers on tab change */
6627 - (void) reloadData {
6628 size_t count([[self viewControllers] count]);
6629 for (size_t i(0); i != count; ++i) {
6630 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6635 - (id) initWithDatabase:(Database *)database {
6636 if ((self = [super init]) != nil) {
6637 database_ = database;
6644 /* Cydia Navigation Controller {{{ */
6645 @interface CYNavigationController : UINavigationController {
6646 _transient Database *database_;
6647 _transient id<UINavigationControllerDelegate> delegate_;
6650 - (id) initWithDatabase:(Database *)database;
6651 - (void) reloadData;
6656 @implementation CYNavigationController
6658 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6659 // Inherit autorotation settings for modal parents.
6660 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6661 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6663 return [super shouldAutorotateToInterfaceOrientation:orientation];
6671 - (void) reloadData {
6672 size_t count([[self viewControllers] count]);
6673 for (size_t i(0); i != count; ++i) {
6674 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6679 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6680 delegate_ = delegate;
6683 - (id) initWithDatabase:(Database *)database {
6684 if ((self = [super init]) != nil) {
6685 database_ = database;
6691 /* Cydia:// Protocol {{{ */
6692 @interface CydiaURLProtocol : NSURLProtocol {
6697 @implementation CydiaURLProtocol
6699 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6700 NSURL *url([request URL]);
6703 NSString *scheme([[url scheme] lowercaseString]);
6704 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6709 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6713 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6714 id<NSURLProtocolClient> client([self client]);
6716 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6718 NSData *data(UIImagePNGRepresentation(icon));
6720 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6721 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6722 [client URLProtocol:self didLoadData:data];
6723 [client URLProtocolDidFinishLoading:self];
6727 - (void) startLoading {
6728 id<NSURLProtocolClient> client([self client]);
6729 NSURLRequest *request([self request]);
6731 NSURL *url([request URL]);
6732 NSString *href([url absoluteString]);
6734 NSString *path([href substringFromIndex:8]);
6735 NSRange slash([path rangeOfString:@"/"]);
6738 if (slash.location == NSNotFound) {
6742 command = [path substringToIndex:slash.location];
6743 path = [path substringFromIndex:(slash.location + 1)];
6746 Database *database([Database sharedInstance]);
6748 if ([command isEqualToString:@"package-icon"]) {
6751 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6752 Package *package([database packageWithName:path]);
6755 UIImage *icon([package icon]);
6756 [self _returnPNGWithImage:icon forRequest:request];
6757 } else if ([command isEqualToString:@"source-icon"]) {
6760 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6761 NSString *source(Simplify(path));
6762 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6764 icon = [UIImage applicationImageNamed:@"unknown.png"];
6765 [self _returnPNGWithImage:icon forRequest:request];
6766 } else if ([command isEqualToString:@"uikit-image"]) {
6769 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6770 UIImage *icon(_UIImageWithName(path));
6771 [self _returnPNGWithImage:icon forRequest:request];
6772 } else if ([command isEqualToString:@"section-icon"]) {
6775 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6776 NSString *section(Simplify(path));
6777 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6779 icon = [UIImage applicationImageNamed:@"unknown.png"];
6780 [self _returnPNGWithImage:icon forRequest:request];
6782 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6786 - (void) stopLoading {
6792 /* Sections Controller {{{ */
6793 @interface SectionsController : CYViewController <
6794 UITableViewDataSource,
6797 _transient Database *database_;
6798 NSMutableArray *sections_;
6799 NSMutableArray *filtered_;
6805 - (id) initWithDatabase:(Database *)database;
6806 - (void) reloadData;
6809 - (void) editButtonClicked;
6813 @implementation SectionsController
6816 [list_ setDataSource:nil];
6817 [list_ setDelegate:nil];
6819 [sections_ release];
6820 [filtered_ release];
6822 [accessory_ release];
6826 - (void) viewDidAppear:(BOOL)animated {
6827 [super viewDidAppear:animated];
6828 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6831 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6832 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6836 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6837 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6840 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6844 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6845 static NSString *reuseIdentifier = @"SectionCell";
6847 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6849 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6851 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6856 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6860 Section *section = [self sectionAtIndexPath:indexPath];
6861 NSString *name = [section name];
6864 if ([indexPath row] == 0) {
6867 title = UCLocalize("ALL_PACKAGES");
6870 name = [NSString stringWithString:name];
6871 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6874 title = UCLocalize("NO_SECTION");
6878 FilteredPackageController *table = [[[FilteredPackageController alloc]
6879 initWithDatabase:database_
6881 filter:@selector(isVisibleInSection:)
6885 [table setDelegate:delegate_];
6887 [[self navigationController] pushViewController:table animated:YES];
6890 - (NSString *) title { return UCLocalize("SECTIONS"); }
6892 - (id) initWithDatabase:(Database *)database {
6893 if ((self = [super init]) != nil) {
6894 database_ = database;
6896 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6898 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6899 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6901 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6902 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6903 [list_ setRowHeight:45.0f];
6904 [[self view] addSubview:list_];
6906 [list_ setDataSource:self];
6907 [list_ setDelegate:self];
6913 - (void) reloadData {
6914 NSArray *packages = [database_ packages];
6916 [sections_ removeAllObjects];
6917 [filtered_ removeAllObjects];
6919 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6922 for (Package *package in packages) {
6923 NSString *name([package section]);
6924 NSString *key(name == nil ? @"" : name);
6928 _profile(SectionsView$reloadData$Section)
6929 section = [sections objectForKey:key];
6930 if (section == nil) {
6931 _profile(SectionsView$reloadData$Section$Allocate)
6932 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6933 [sections setObject:section forKey:key];
6938 [section addToCount];
6940 _profile(SectionsView$reloadData$Filter)
6941 if (![package valid] || ![package visible])
6949 [sections_ addObjectsFromArray:[sections allValues]];
6951 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6953 for (Section *section in sections_) {
6954 size_t count([section row]);
6958 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6959 [section setCount:count];
6960 [filtered_ addObject:section];
6963 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6964 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
6965 style:UIBarButtonItemStylePlain
6967 action:@selector(editButtonClicked)
6968 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6974 - (void) resetView {
6976 [self editButtonClicked];
6979 - (void) editButtonClicked {
6980 if ((editing_ = !editing_))
6983 [delegate_ updateData];
6985 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6986 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6987 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6990 - (UIView *) accessoryView {
6996 /* Changes Controller {{{ */
6997 @interface ChangesController : CYViewController <
6998 UITableViewDataSource,
7001 _transient Database *database_;
7002 CFMutableArrayRef packages_;
7003 NSMutableArray *sections_;
7006 BOOL hasSentFirstLoad_;
7009 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
7010 - (void) reloadData;
7014 @implementation ChangesController
7017 [list_ setDelegate:nil];
7018 [list_ setDataSource:nil];
7020 CFRelease(packages_);
7022 [sections_ release];
7027 - (void) viewDidAppear:(BOOL)animated {
7028 [super viewDidAppear:animated];
7029 if (!hasSentFirstLoad_) {
7030 hasSentFirstLoad_ = YES;
7031 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7033 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7037 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7038 NSInteger count([sections_ count]);
7039 return count == 0 ? 1 : count;
7042 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7043 if ([sections_ count] == 0)
7045 return [[sections_ objectAtIndex:section] name];
7048 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7049 if ([sections_ count] == 0)
7051 return [[sections_ objectAtIndex:section] count];
7054 - (Package *) packageAtIndex:(NSUInteger)index {
7055 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7058 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7059 Section *section([sections_ objectAtIndex:[path section]]);
7060 NSInteger row([path row]);
7061 return [self packageAtIndex:([section row] + row)];
7064 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7065 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7067 cell = [[[PackageCell alloc] init] autorelease];
7068 [cell setPackage:[self packageAtIndexPath:path]];
7072 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7073 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7076 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7077 Package *package([self packageAtIndexPath:path]);
7078 PackageController *view([delegate_ packageController]);
7079 [view setDelegate:delegate_];
7080 [view setPackage:package];
7081 [[self navigationController] pushViewController:view animated:YES];
7085 - (void) refreshButtonClicked {
7086 [delegate_ beginUpdate];
7087 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7090 - (void) upgradeButtonClicked {
7091 [delegate_ distUpgrade];
7094 - (NSString *) title { return UCLocalize("CHANGES"); }
7096 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7097 if ((self = [super init]) != nil) {
7098 database_ = database;
7099 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7101 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7103 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7105 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7106 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7107 [list_ setRowHeight:73.0f];
7108 [[self view] addSubview:list_];
7110 [list_ setDataSource:self];
7111 [list_ setDelegate:self];
7113 delegate_ = delegate;
7117 - (void) _reloadPackages:(NSArray *)packages {
7119 for (Package *package in packages)
7120 if ([package upgradableAndEssential:YES] || [package visible])
7121 CFArrayAppendValue(packages_, package);
7124 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7128 - (void) reloadData {
7129 NSArray *packages = [database_ packages];
7131 CFArrayRemoveAllValues(packages_);
7133 [sections_ removeAllObjects];
7136 UIProgressHUD *hud([delegate_ addProgressHUD]);
7137 [hud setText:UCLocalize("LOADING")];
7138 //NSLog(@"HUD:%@::%@", delegate_, hud);
7139 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7140 [delegate_ removeProgressHUD:hud];
7142 [self _reloadPackages:packages];
7145 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7146 Section *ignored = nil;
7147 Section *section = nil;
7151 bool unseens = false;
7153 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7155 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7156 Package *package = [self packageAtIndex:offset];
7158 BOOL uae = [package upgradableAndEssential:YES];
7162 time_t seen([package seen]);
7164 if (section == nil || last != seen) {
7168 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7171 _profile(ChangesController$reloadData$Allocate)
7172 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7173 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7174 [sections_ addObject:section];
7178 [section addToCount];
7179 } else if ([package ignored]) {
7180 if (ignored == nil) {
7181 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7183 [ignored addToCount];
7186 [upgradable addToCount];
7191 CFRelease(formatter);
7194 Section *last = [sections_ lastObject];
7195 size_t count = [last count];
7196 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7197 [sections_ removeLastObject];
7200 if ([ignored count] != 0)
7201 [sections_ insertObject:ignored atIndex:0];
7203 [sections_ insertObject:upgradable atIndex:0];
7208 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7209 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7210 style:UIBarButtonItemStylePlain
7212 action:@selector(upgradeButtonClicked)
7215 if (![delegate_ updating])
7216 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7217 initWithTitle:UCLocalize("REFRESH")
7218 style:UIBarButtonItemStylePlain
7220 action:@selector(refreshButtonClicked)
7226 /* Search Controller {{{ */
7227 @interface SearchController : FilteredPackageController <
7230 UISearchBar *search_;
7233 - (id) initWithDatabase:(Database *)database;
7234 - (void) reloadData;
7238 @implementation SearchController
7245 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7246 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7247 [search_ resignFirstResponder];
7251 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7252 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7256 - (NSString *) title { return nil; }
7258 - (id) initWithDatabase:(Database *)database {
7259 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7262 - (void)viewDidAppear:(BOOL)animated {
7263 [super viewDidAppear:animated];
7265 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7266 [search_ layoutSubviews];
7267 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7268 UITextField *textField = [search_ searchField];
7269 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7270 [search_ setDelegate:self];
7271 [textField setEnablesReturnKeyAutomatically:NO];
7272 [[self navigationItem] setTitleView:textField];
7276 - (void) _reloadData {
7279 - (void) reloadData {
7280 _profile(SearchController$reloadData)
7281 [packages_ reloadData];
7284 [packages_ resetCursor];
7287 - (void) didSelectPackage:(Package *)package {
7288 [search_ resignFirstResponder];
7289 [super didSelectPackage:package];
7294 /* Settings Controller {{{ */
7295 @interface SettingsController : CYViewController <
7296 UITableViewDataSource,
7299 _transient Database *database_;
7302 UITableView *table_;
7303 UISwitch *subscribedSwitch_;
7304 UISwitch *ignoredSwitch_;
7305 UITableViewCell *subscribedCell_;
7306 UITableViewCell *ignoredCell_;
7309 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7313 @implementation SettingsController
7317 if (package_ != nil)
7320 [subscribedSwitch_ release];
7321 [ignoredSwitch_ release];
7322 [subscribedCell_ release];
7323 [ignoredCell_ release];
7328 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7329 if (package_ == nil)
7335 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7336 if (package_ == nil)
7342 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7343 return UCLocalize("SHOW_ALL_CHANGES_EX");
7346 - (void) onSubscribed:(id)control {
7347 bool value([control isOn]);
7348 if (package_ == nil)
7350 if ([package_ setSubscribed:value])
7351 [delegate_ updateData];
7354 - (void) onIgnored:(id)control {
7355 // TODO: set Held state - possibly call out to dpkg, etc.
7358 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7359 if (package_ == nil)
7362 switch ([indexPath row]) {
7363 case 0: return subscribedCell_;
7364 case 1: return ignoredCell_;
7372 - (NSString *) title { return UCLocalize("SETTINGS"); }
7374 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7375 if ((self = [super init])) {
7376 database_ = database;
7377 name_ = [package retain];
7379 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7381 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7382 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7383 [[self view] addSubview:table_];
7385 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7386 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7387 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7389 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7390 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7391 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7393 subscribedCell_ = [[UITableViewCell alloc] init];
7394 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7395 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7396 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7398 ignoredCell_ = [[UITableViewCell alloc] init];
7399 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7400 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7401 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7403 [table_ setDataSource:self];
7404 [table_ setDelegate:self];
7409 - (void) reloadData {
7410 if (package_ != nil)
7411 [package_ autorelease];
7412 package_ = [database_ packageWithName:name_];
7413 if (package_ != nil) {
7415 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7416 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7419 [table_ reloadData];
7424 /* Signature Controller {{{ */
7425 @interface SignatureController : CYBrowserController {
7426 _transient Database *database_;
7430 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7434 @implementation SignatureController
7441 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7443 [super webView:view didClearWindowObject:window forFrame:frame];
7446 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7447 if ((self = [super init]) != nil) {
7448 database_ = database;
7449 package_ = [package retain];
7454 - (void) reloadData {
7455 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7461 /* Role Controller {{{ */
7462 @interface RoleController : CYViewController <
7463 UITableViewDataSource,
7466 _transient Database *database_;
7467 // XXX: ok, "roledelegate_"?...
7468 _transient id roledelegate_;
7469 UITableView *table_;
7470 UISegmentedControl *segment_;
7474 - (void) showDoneButton;
7475 - (void) resizeSegmentedControl;
7479 @implementation RoleController
7483 [container_ release];
7488 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7489 if ((self = [super init])) {
7490 database_ = database;
7491 roledelegate_ = delegate;
7493 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7495 NSArray *items = [NSArray arrayWithObjects:
7497 UCLocalize("HACKER"),
7498 UCLocalize("DEVELOPER"),
7500 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7501 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7502 [container_ addSubview:segment_];
7505 if ([Role_ isEqualToString:@"User"]) index = 0;
7506 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7507 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7509 [segment_ setSelectedSegmentIndex:index];
7510 [self showDoneButton];
7513 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7514 [self resizeSegmentedControl];
7516 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7517 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7518 [table_ setDelegate:self];
7519 [table_ setDataSource:self];
7520 [[self view] addSubview:table_];
7521 [table_ reloadData];
7525 - (void) resizeSegmentedControl {
7526 CGFloat width = [[self view] frame].size.width;
7527 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7530 - (void) viewWillAppear:(BOOL)animated {
7531 [super viewWillAppear:animated];
7533 [self resizeSegmentedControl];
7536 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7537 [self resizeSegmentedControl];
7540 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7541 [self resizeSegmentedControl];
7545 NSString *role(nil);
7547 switch ([segment_ selectedSegmentIndex]) {
7548 case 0: role = @"User"; break;
7549 case 1: role = @"Hacker"; break;
7550 case 2: role = @"Developer"; break;
7555 if (![role isEqualToString:Role_]) {
7556 bool rolling(Role_ == nil);
7559 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7563 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7567 [roledelegate_ loadData];
7569 [roledelegate_ updateData];
7573 - (void) segmentChanged:(UISegmentedControl *)control {
7574 [self showDoneButton];
7577 - (void) saveAndClose {
7580 [[self navigationItem] setRightBarButtonItem:nil];
7581 [[self navigationController] dismissModalViewControllerAnimated:YES];
7584 - (void) doneButtonClicked {
7585 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7586 [spinner startAnimating];
7587 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7588 [[self navigationItem] setRightBarButtonItem:spinItem];
7590 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7593 - (void) showDoneButton {
7594 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7595 initWithTitle:UCLocalize("DONE")
7596 style:UIBarButtonItemStyleDone
7598 action:@selector(doneButtonClicked)
7599 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7602 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7603 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7607 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7611 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7612 return nil; // This method is required by the protocol.
7615 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7617 return UCLocalize("ROLE_EX");
7619 return [NSString stringWithFormat:
7620 @"%@: %@\n%@: %@\n%@: %@",
7621 UCLocalize("USER"), UCLocalize("USER_EX"),
7622 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7623 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7628 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7629 return section == 3 ? 44.0f : 0;
7632 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7633 return section == 3 ? container_ : nil;
7638 /* Stash Controller {{{ */
7639 @interface CYStashController : CYViewController {
7640 // XXX: just delete these things
7641 _transient UIActivityIndicatorView *spinner_;
7642 _transient UILabel *status_;
7643 _transient UILabel *caption_;
7647 @implementation CYStashController
7649 if ((self = [super init])) {
7650 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7652 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7653 CGRect spinrect = [spinner_ frame];
7654 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7655 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7656 [spinner_ setFrame:spinrect];
7657 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7658 [[self view] addSubview:spinner_];
7659 [spinner_ startAnimating];
7662 captrect.size.width = [[self view] frame].size.width;
7663 captrect.size.height = 40.0f;
7664 captrect.origin.x = 0;
7665 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7666 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7667 [caption_ setText:@"Initializing Filesystem"];
7668 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7669 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7670 [caption_ setTextColor:[UIColor whiteColor]];
7671 [caption_ setBackgroundColor:[UIColor clearColor]];
7672 [caption_ setShadowColor:[UIColor blackColor]];
7673 [caption_ setTextAlignment:UITextAlignmentCenter];
7674 [[self view] addSubview:caption_];
7677 statusrect.size.width = [[self view] frame].size.width;
7678 statusrect.size.height = 30.0f;
7679 statusrect.origin.x = 0;
7680 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7681 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7682 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7683 [status_ setText:@"(Cydia will exit when complete.)"];
7684 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7685 [status_ setTextColor:[UIColor whiteColor]];
7686 [status_ setBackgroundColor:[UIColor clearColor]];
7687 [status_ setShadowColor:[UIColor blackColor]];
7688 [status_ setTextAlignment:UITextAlignmentCenter];
7689 [[self view] addSubview:status_];
7693 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7694 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7699 /* Cydia Container {{{ */
7700 @interface CYContainer : UIViewController <ProgressDelegate> {
7701 _transient Database *database_;
7702 RefreshBar *refreshbar_;
7706 // XXX: ok, "updatedelegate_"?...
7707 _transient NSObject<CydiaDelegate> *updatedelegate_;
7708 // XXX: can't we query for this variable when we need it?
7709 _transient UITabBarController *root_;
7712 - (void) setTabBarController:(UITabBarController *)controller;
7714 - (void) dropBar:(BOOL)animated;
7715 - (void) beginUpdate;
7716 - (void) raiseBar:(BOOL)animated;
7721 @implementation CYContainer
7723 - (BOOL) _reallyWantsFullScreenLayout {
7727 // NOTE: UIWindow only sends the top controller these messages,
7728 // So we have to forward them on.
7730 - (void) viewDidAppear:(BOOL)animated {
7731 [super viewDidAppear:animated];
7732 [root_ viewDidAppear:animated];
7735 - (void) viewWillAppear:(BOOL)animated {
7736 [super viewWillAppear:animated];
7737 [root_ viewWillAppear:animated];
7740 - (void) viewDidDisappear:(BOOL)animated {
7741 [super viewDidDisappear:animated];
7742 [root_ viewDidDisappear:animated];
7745 - (void) viewWillDisappear:(BOOL)animated {
7746 [super viewWillDisappear:animated];
7747 [root_ viewWillDisappear:animated];
7750 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7751 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7754 - (void) setTabBarController:(UITabBarController *)controller {
7756 [[self view] addSubview:[root_ view]];
7759 - (void) setUpdate:(NSDate *)date {
7763 - (void) beginUpdate {
7765 [refreshbar_ start];
7770 detachNewThreadSelector:@selector(performUpdate)
7776 - (void) performUpdate { _pooled
7778 status.setDelegate(self);
7779 [database_ updateWithStatus:status];
7782 performSelectorOnMainThread:@selector(completeUpdate)
7788 - (void) completeUpdate {
7793 [self raiseBar:YES];
7795 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7798 - (void) cancelUpdate {
7800 [self raiseBar:YES];
7802 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7805 - (void) cancelPressed {
7806 [self cancelUpdate];
7813 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7814 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7817 - (void) startProgress {
7820 - (void) setProgressTitle:(NSString *)title {
7822 performSelectorOnMainThread:@selector(_setProgressTitle:)
7828 - (bool) isCancelling:(size_t)received {
7832 - (void) setProgressPercent:(float)percent {
7834 performSelectorOnMainThread:@selector(_setProgressPercent:)
7835 withObject:[NSNumber numberWithFloat:percent]
7840 - (void) addProgressOutput:(NSString *)output {
7842 performSelectorOnMainThread:@selector(_addProgressOutput:)
7848 - (void) _setProgressTitle:(NSString *)title {
7849 [refreshbar_ setPrompt:title];
7852 - (void) _setProgressPercent:(NSNumber *)percent {
7853 [refreshbar_ setProgress:[percent floatValue]];
7856 - (void) _addProgressOutput:(NSString *)output {
7859 - (void) setUpdateDelegate:(id)delegate {
7860 updatedelegate_ = delegate;
7863 - (CGFloat) statusBarHeight {
7864 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7865 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7867 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7871 - (void) dropBar:(BOOL)animated {
7876 [[self view] addSubview:refreshbar_];
7878 CGFloat sboffset = [self statusBarHeight];
7880 CGRect barframe = [refreshbar_ frame];
7881 barframe.origin.y = sboffset;
7882 [refreshbar_ setFrame:barframe];
7885 [UIView beginAnimations:nil context:NULL];
7886 CGRect viewframe = [[root_ view] frame];
7887 viewframe.origin.y += barframe.size.height + sboffset;
7888 viewframe.size.height -= barframe.size.height + sboffset;
7889 [[root_ view] setFrame:viewframe];
7891 [UIView commitAnimations];
7893 // Ensure bar has the proper width for our view, it might have changed
7894 barframe.size.width = viewframe.size.width;
7895 [refreshbar_ setFrame:barframe];
7897 // XXX: fix Apple's layout bug
7898 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7901 - (void) raiseBar:(BOOL)animated {
7906 [refreshbar_ removeFromSuperview];
7908 CGFloat sboffset = [self statusBarHeight];
7911 [UIView beginAnimations:nil context:NULL];
7912 CGRect barframe = [refreshbar_ frame];
7913 CGRect viewframe = [[root_ view] frame];
7914 viewframe.origin.y -= barframe.size.height + sboffset;
7915 viewframe.size.height += barframe.size.height + sboffset;
7916 [[root_ view] setFrame:viewframe];
7918 [UIView commitAnimations];
7920 // XXX: fix Apple's layout bug
7921 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7924 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7925 // XXX: fix Apple's layout bug
7926 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7929 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7935 // XXX: fix Apple's layout bug
7936 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7939 - (void) statusBarFrameChanged:(NSNotification *)notification {
7947 [refreshbar_ release];
7948 [[NSNotificationCenter defaultCenter] removeObserver:self];
7952 - (id) initWithDatabase:(Database *)database {
7953 if ((self = [super init]) != nil) {
7954 database_ = database;
7956 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7957 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7959 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7976 @interface Cydia : UIApplication <
7977 ConfirmationControllerDelegate,
7978 ProgressControllerDelegate,
7980 UINavigationControllerDelegate,
7981 UITabBarControllerDelegate
7983 // XXX: evaluate all fields for _transient
7986 CYContainer *container_;
7987 CYTabBarController *tabbar_;
7989 NSMutableArray *essential_;
7990 NSMutableArray *broken_;
7992 Database *database_;
7998 SectionsController *sections_;
7999 ChangesController *changes_;
8000 ManageController *manage_;
8001 SearchController *search_;
8002 SourceTable *sources_;
8003 InstalledController *installed_;
8006 CYStashController *stash_;
8011 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
8012 - (void) setPage:(CYViewController *)page;
8015 // XXX: I hate prototypes
8016 - (id) queueBadgeController;
8020 static _finline void _setHomePage(Cydia *self) {
8021 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
8024 @implementation Cydia
8026 - (void) beginUpdate {
8027 [container_ beginUpdate];
8031 return [container_ updating];
8034 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8039 if ([broken_ count] != 0) {
8040 int count = [broken_ count];
8042 UIAlertView *alert = [[[UIAlertView alloc]
8043 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8044 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8046 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8047 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8050 [alert setContext:@"fixhalf"];
8052 } else if (!Ignored_ && [essential_ count] != 0) {
8053 int count = [essential_ count];
8055 UIAlertView *alert = [[[UIAlertView alloc]
8056 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8057 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8059 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8060 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8063 [alert setContext:@"upgrade"];
8068 - (void) _saveConfig {
8074 NSString *error(nil);
8076 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8078 NSError *error(nil);
8079 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8080 NSLog(@"failure to save metadata data: %@", error);
8085 NSLog(@"failure to serialize metadata: %@", error);
8090 - (void) _updateData {
8093 /* XXX: this is just stupid */
8094 if (tag_ != 1 && sections_ != nil)
8095 [sections_ reloadData];
8096 if (tag_ != 2 && changes_ != nil)
8097 [changes_ reloadData];
8098 if (tag_ != 4 && search_ != nil)
8099 [search_ reloadData];
8101 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8103 [queueDelegate_ queueStatusDidChange];
8104 [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8107 - (int)indexOfTabWithTag:(int)tag {
8109 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8110 if ([[controller tabBarItem] tag] == tag)
8118 - (void) _refreshIfPossible {
8119 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8121 bool recently = false;
8122 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8123 if (update != nil) {
8124 NSTimeInterval interval([update timeIntervalSinceNow]);
8125 if (interval <= 0 && interval > -(15*60))
8129 // Don't automatic refresh if:
8130 // - We already refreshed recently.
8131 // - We already auto-refreshed this launch.
8132 // - Auto-refresh is disabled.
8133 if (recently || loaded_ || ManualRefresh) {
8134 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8136 // If we are cancelling due to ManualRefresh or a recent refresh
8137 // we need to make sure it knows it's already loaded.
8141 // We are going to load, so remember that.
8145 SCNetworkReachabilityFlags flags; {
8146 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8147 SCNetworkReachabilityGetFlags(reachability, &flags);
8148 CFRelease(reachability);
8151 // XXX: this elaborate mess is what Apple is using to determine this? :(
8152 // XXX: do we care if the user has to intervene? maybe that's ok?
8154 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8155 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8156 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8157 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8158 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8159 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8163 // If we can reach the server, auto-refresh!
8165 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8170 - (void) refreshIfPossible {
8171 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8174 - (void) _reloadData {
8175 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8176 [hud setText:UCLocalize("RELOADING_DATA")];
8178 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8181 [self removeProgressHUD:hud];
8185 [essential_ removeAllObjects];
8186 [broken_ removeAllObjects];
8188 NSArray *packages([database_ packages]);
8189 for (Package *package in packages) {
8191 [broken_ addObject:package];
8192 if ([package upgradableAndEssential:NO]) {
8193 if ([package essential])
8194 [essential_ addObject:package];
8199 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8201 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8202 [changesItem setBadgeValue:badge];
8203 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8205 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8206 [self setApplicationBadge:badge];
8208 [self setApplicationBadgeString:badge];
8210 [changesItem setBadgeValue:nil];
8211 [changesItem setAnimatedBadge:NO];
8213 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8214 [self removeApplicationBadge];
8215 else // XXX: maybe use setApplicationBadgeString also?
8216 [self setApplicationIconBadgeNumber:0];
8221 [self refreshIfPossible];
8224 - (void) updateData {
8233 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8234 _assert(file != NULL);
8236 for (NSString *key in [Sources_ allKeys]) {
8237 NSDictionary *source([Sources_ objectForKey:key]);
8239 fprintf(file, "%s %s %s\n",
8240 [[source objectForKey:@"Type"] UTF8String],
8241 [[source objectForKey:@"URI"] UTF8String],
8242 [[source objectForKey:@"Distribution"] UTF8String]
8250 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8251 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8253 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8254 [container_ presentModalViewController:navigation animated:YES];
8257 detachNewThreadSelector:@selector(update_)
8260 title:UCLocalize("UPDATING_SOURCES")
8264 - (void) reloadData {
8265 @synchronized (self) {
8271 pkgProblemResolver *resolver = [database_ resolver];
8273 resolver->InstallProtect();
8274 if (!resolver->Resolve(true))
8278 - (CGRect) popUpBounds {
8279 return [[tabbar_ view] bounds];
8283 if (![database_ prepare])
8286 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8287 [page setDelegate:self];
8288 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8289 [confirm_ setDelegate:self];
8292 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8293 [container_ presentModalViewController:confirm_ animated:YES];
8299 @synchronized (self) {
8304 - (void) clearPackage:(Package *)package {
8305 @synchronized (self) {
8312 - (void) installPackages:(NSArray *)packages {
8313 @synchronized (self) {
8314 for (Package *package in packages)
8321 - (void) installPackage:(Package *)package {
8322 @synchronized (self) {
8329 - (void) removePackage:(Package *)package {
8330 @synchronized (self) {
8337 - (void) distUpgrade {
8338 @synchronized (self) {
8339 if (![database_ upgrade])
8346 @synchronized (self) {
8351 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8354 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8356 if (navigation != nil) {
8357 [navigation pushViewController:progress animated:YES];
8359 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8361 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8362 [container_ presentModalViewController:navigation animated:YES];
8366 detachNewThreadSelector:@selector(perform)
8369 title:UCLocalize("RUNNING")
8373 - (void) progressControllerIsComplete:(ProgressController *)progress {
8377 - (void) setPage:(CYViewController *)page {
8378 [page setDelegate:self];
8380 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8381 [navController setViewControllers:[NSArray arrayWithObject:page]];
8382 for (CYNavigationController *page in [tabbar_ viewControllers])
8383 if (page != navController)
8384 [page setViewControllers:nil];
8387 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8388 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8389 [browser loadURL:url];
8393 - (SectionsController *) sectionsController {
8394 if (sections_ == nil)
8395 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8399 - (ChangesController *) changesController {
8400 if (changes_ == nil)
8401 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8405 - (ManageController *) manageController {
8406 if (manage_ == nil) {
8407 manage_ = (ManageController *) [[self
8408 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8409 withClass:[ManageController class]
8412 queueDelegate_ = manage_;
8417 - (SearchController *) searchController {
8419 search_ = [[SearchController alloc] initWithDatabase:database_];
8423 - (SourceTable *) sourcesController {
8424 if (sources_ == nil)
8425 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8429 - (InstalledController *) installedController {
8430 if (installed_ == nil) {
8431 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8433 queueDelegate_ = installed_;
8438 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8439 int tag = [[viewController tabBarItem] tag];
8441 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8443 } else if (tag_ == 1) {
8444 [[self sectionsController] resetView];
8448 case kCydiaTag: _setHomePage(self); break;
8450 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8451 case kChangesTag: [self setPage:[self changesController]]; break;
8452 case kManageTag: [self setPage:[self manageController]]; break;
8453 case kInstalledTag: [self setPage:[self installedController]]; break;
8454 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8455 case kSearchTag: [self setPage:[self searchController]]; break;
8463 - (void) showSettings {
8464 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8465 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8467 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8468 [container_ presentModalViewController:nav animated:YES];
8471 - (void) setPackageController:(PackageController *)view {
8473 [view setPackage:nil];
8477 - (PackageController *) _packageController {
8478 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8481 - (PackageController *) packageController {
8482 return [self _packageController];
8485 // Returns the navigation controller for the queuing badge.
8486 - (id) queueBadgeController {
8487 int index = [self indexOfTabWithTag:kManageTag];
8489 index = [self indexOfTabWithTag:kInstalledTag];
8491 return [[tabbar_ viewControllers] objectAtIndex:index];
8494 - (void) cancelAndClear:(bool)clear {
8495 @synchronized (self) {
8507 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8508 NSString *context([alert context]);
8510 if ([context isEqualToString:@"fixhalf"]) {
8511 if (button == [alert firstOtherButtonIndex]) {
8512 @synchronized (self) {
8513 for (Package *broken in broken_) {
8516 NSString *id = [broken id];
8517 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8518 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8519 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8520 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8526 } else if (button == [alert cancelButtonIndex]) {
8527 [broken_ removeAllObjects];
8531 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8532 } else if ([context isEqualToString:@"upgrade"]) {
8533 if (button == [alert firstOtherButtonIndex]) {
8534 @synchronized (self) {
8535 for (Package *essential in essential_)
8536 [essential install];
8541 } else if (button == [alert firstOtherButtonIndex] + 1) {
8543 } else if (button == [alert cancelButtonIndex]) {
8547 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8551 - (void) system:(NSString *)command { _pooled
8552 system([command UTF8String]);
8555 - (void) applicationWillSuspend {
8557 [super applicationWillSuspend];
8560 - (BOOL) hudIsShowing {
8561 return (hudcount_ > 0);
8564 - (void) applicationSuspend:(__GSEvent *)event {
8565 // Use external process status API internally.
8566 // This is probably a really bad idea.
8567 uint64_t status = 0;
8569 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8570 notify_get_state(notify_token, &status);
8571 notify_cancel(notify_token);
8574 if (![self hudIsShowing] && status == 0)
8575 [super applicationSuspend:event];
8578 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8579 if (![self hudIsShowing])
8580 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8583 - (void) _setSuspended:(BOOL)value {
8584 if (![self hudIsShowing])
8585 [super _setSuspended:value];
8588 - (UIProgressHUD *) addProgressHUD {
8589 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8590 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8592 [window_ setUserInteractionEnabled:NO];
8595 UIViewController *target = container_;
8596 while ([target modalViewController] != nil) target = [target modalViewController];
8597 [[target view] addSubview:hud];
8603 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8605 [hud removeFromSuperview];
8606 [window_ setUserInteractionEnabled:YES];
8610 - (CYViewController *) pageForPackage:(NSString *)name {
8611 if (Package *package = [database_ packageWithName:name]) {
8612 PackageController *view([self packageController]);
8613 [view setPackage:package];
8616 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8617 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8618 return [self _pageForURL:url withClass:[CYBrowserController class]];
8622 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8626 NSString *href([url absoluteString]);
8627 if ([href hasPrefix:@"apptapp://package/"])
8628 return [self pageForPackage:[href substringFromIndex:18]];
8630 NSString *scheme([[url scheme] lowercaseString]);
8631 if (![scheme isEqualToString:@"cydia"])
8633 NSString *path([url absoluteString]);
8634 if ([path length] < 8)
8636 path = [path substringFromIndex:8];
8637 if (![path hasPrefix:@"/"])
8638 path = [@"/" stringByAppendingString:path];
8640 if ([path isEqualToString:@"/add-source"])
8641 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8642 else if ([path isEqualToString:@"/storage"])
8643 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8644 else if ([path isEqualToString:@"/sources"])
8645 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8646 else if ([path isEqualToString:@"/packages"])
8647 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8648 else if ([path hasPrefix:@"/url/"])
8649 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8650 else if ([path hasPrefix:@"/launch/"])
8651 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8652 else if ([path hasPrefix:@"/package-settings/"])
8653 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8654 else if ([path hasPrefix:@"/package-signature/"])
8655 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8656 else if ([path hasPrefix:@"/package/"])
8657 return [self pageForPackage:[path substringFromIndex:9]];
8658 else if ([path hasPrefix:@"/files/"]) {
8659 NSString *name = [path substringFromIndex:7];
8661 if (Package *package = [database_ packageWithName:name]) {
8662 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8663 [files setPackage:package];
8671 - (BOOL) openCydiaURL:(NSURL *)url {
8672 CYViewController *page = nil;
8675 NSLog(@"open url: %@", url);
8677 if ((page = [self pageForURL:url hasTag:&tag])) {
8678 [self setPage:page];
8680 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8686 - (void) applicationOpenURL:(NSURL *)url {
8687 [super applicationOpenURL:url];
8688 NSLog(@"first: %@", url);
8689 if (!loaded_) starturl_ = [url retain];
8690 else [self openCydiaURL:url];
8693 - (void) applicationWillResignActive:(UIApplication *)application {
8694 // Stop refreshing if you get a phone call or lock the device.
8695 if ([container_ updating])
8696 [container_ cancelUpdate];
8698 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8699 [super applicationWillResignActive:application];
8702 - (void) addStashController {
8703 stash_ = [[CYStashController alloc] init];
8704 [window_ addSubview:[stash_ view]];
8707 - (void) removeStashController {
8708 [[stash_ view] removeFromSuperview];
8713 [self setIdleTimerDisabled:YES];
8715 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8716 [self setStatusBarShowsProgress:YES];
8717 UpdateExternalStatus(1);
8719 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8721 UpdateExternalStatus(0);
8722 [self setStatusBarShowsProgress:NO];
8724 [self removeStashController];
8726 if (ExecFork() == 0) {
8727 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8728 perror("launchctl stop");
8732 - (void) setupTabBarController {
8733 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8734 [tabbar_ setDelegate:self];
8736 NSMutableArray *items([NSMutableArray arrayWithObjects:
8737 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8738 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8739 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8740 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8744 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8745 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8747 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8750 NSMutableArray *controllers([NSMutableArray array]);
8752 for (UITabBarItem *item in items) {
8753 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8754 [controller setTabBarItem:item];
8755 [controllers addObject:controller];
8758 [tabbar_ setViewControllers:controllers];
8761 - (void) applicationDidFinishLaunching:(id)unused {
8763 [CYBrowserController _initialize];
8765 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8767 Font12_ = [[UIFont systemFontOfSize:12] retain];
8768 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8769 Font14_ = [[UIFont systemFontOfSize:14] retain];
8770 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8771 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8775 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8776 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8778 UIScreen *screen([UIScreen mainScreen]);
8780 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8781 [window_ orderFront:self];
8782 [window_ makeKey:self];
8783 [window_ setHidden:NO];
8786 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8787 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8788 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8789 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8790 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8791 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8792 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8793 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8794 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8797 [self addStashController];
8798 // XXX: this would be much cleaner as a yieldToSelector:
8799 // that way the removeStashController could happen right here inline
8800 // we also could no longer require the useless stash_ field anymore
8801 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8805 database_ = [Database sharedInstance];
8807 [self setupTabBarController];
8809 container_ = [[CYContainer alloc] initWithDatabase:database_];
8810 [container_ setUpdateDelegate:self];
8811 [container_ setTabBarController:tabbar_];
8812 [window_ addSubview:[container_ view]];
8814 // Show pinstripes while loading data.
8815 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8817 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8824 [self showSettings];
8828 [window_ setUserInteractionEnabled:NO];
8830 UIView *container = [[[UIView alloc] init] autorelease];
8831 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8833 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8834 [spinner startAnimating];
8835 [container addSubview:spinner];
8837 UILabel *label = [[[UILabel alloc] init] autorelease];
8838 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8839 [label setBackgroundColor:[UIColor clearColor]];
8840 [label setTextColor:[UIColor blackColor]];
8841 [label setShadowColor:[UIColor whiteColor]];
8842 [label setShadowOffset:CGSizeMake(0, 1)];
8843 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8844 [container addSubview:label];
8846 CGSize viewsize = [[tabbar_ view] frame].size;
8847 CGSize spinnersize = [spinner bounds].size;
8848 CGSize textsize = [[label text] sizeWithFont:[label font]];
8849 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8851 CGRect containrect = {
8852 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8853 CGSizeMake(bothwidth, spinnersize.height)
8856 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8864 [container setFrame:containrect];
8865 [spinner setFrame:spinrect];
8866 [label setFrame:textrect];
8867 [[container_ view] addSubview:container];
8872 // Show the initial page
8873 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
8874 [tabbar_ setSelectedIndex:0];
8878 [starturl_ release];
8881 [window_ setUserInteractionEnabled:YES];
8883 // XXX: does this actually slow anything down?
8884 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8885 [container removeFromSuperview];
8888 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8889 if (item != nil && IsWildcat_) {
8890 [sheet showFromBarButtonItem:item animated:YES];
8892 [sheet showInView:window_];
8899 id Alloc_(id self, SEL selector) {
8900 id object = alloc_(self, selector);
8901 lprintf("[%s]A-%p\n", self->isa->name, object);
8906 id Dealloc_(id self, SEL selector) {
8907 id object = dealloc_(self, selector);
8908 lprintf("[%s]D-%p\n", self->isa->name, object);
8912 Class $WebDefaultUIKitDelegate;
8914 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8915 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8916 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8917 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8920 static NSNumber *shouldPlayKeyboardSounds;
8924 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8926 case 1104: // Keyboard Button Clicked
8927 case 1105: // Keyboard Delete Repeated
8928 if (shouldPlayKeyboardSounds == nil) {
8929 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8930 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8933 if (![shouldPlayKeyboardSounds boolValue])
8937 _UIHardware$_playSystemSound$(self, _cmd, sound);
8941 int main(int argc, char *argv[]) { _pooled
8944 if (Class $UIDevice = objc_getClass("UIDevice")) {
8945 UIDevice *device([$UIDevice currentDevice]);
8946 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8950 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8952 /* Library Hacks {{{ */
8953 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8955 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8956 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8957 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8958 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8959 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8962 $UIHardware = objc_getClass("UIHardware");
8963 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8964 if (UIHardware$_playSystemSound$ != NULL) {
8965 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8966 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8969 /* Set Locale {{{ */
8970 Locale_ = CFLocaleCopyCurrent();
8971 Languages_ = [NSLocale preferredLanguages];
8972 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8973 //NSLog(@"%@", [Languages_ description]);
8976 if (Languages_ == nil || [Languages_ count] == 0)
8977 // XXX: consider just setting to C and then falling through?
8980 lang = [[Languages_ objectAtIndex:0] UTF8String];
8981 setenv("LANG", lang, true);
8984 //std::setlocale(LC_ALL, lang);
8985 NSLog(@"Setting Language: %s", lang);
8988 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8990 /* Parse Arguments {{{ */
8991 bool substrate(false);
8997 for (int argi(1); argi != argc; ++argi)
8998 if (strcmp(argv[argi], "--") == 0) {
9000 argv[argi] = argv[0];
9006 for (int argi(1); argi != arge; ++argi)
9007 if (strcmp(args[argi], "--substrate") == 0)
9010 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9014 App_ = [[NSBundle mainBundle] bundlePath];
9015 Home_ = NSHomeDirectory();
9021 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9022 alloc_ = alloc->method_imp;
9023 alloc->method_imp = (IMP) &Alloc_;*/
9025 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9026 dealloc_ = dealloc->method_imp;
9027 dealloc->method_imp = (IMP) &Dealloc_;*/
9029 /* System Information {{{ */
9033 size = sizeof(maxproc);
9034 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9035 perror("sysctlbyname(\"kern.maxproc\", ?)");
9036 else if (maxproc < 64) {
9038 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9039 perror("sysctlbyname(\"kern.maxproc\", #)");
9042 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9043 char *osversion = new char[size];
9044 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9045 perror("sysctlbyname(\"kern.osversion\", ?)");
9047 System_ = [NSString stringWithUTF8String:osversion];
9049 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9050 char *machine = new char[size];
9051 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9052 perror("sysctlbyname(\"hw.machine\", ?)");
9056 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9057 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9058 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9059 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9063 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9064 NSData *data((NSData *) ecid);
9065 size_t length([data length]);
9066 uint8_t bytes[length];
9067 [data getBytes:bytes];
9068 char string[length * 2 + 1];
9069 for (size_t i(0); i != length; ++i)
9070 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9071 ChipID_ = [NSString stringWithUTF8String:string];
9075 IOObjectRelease(service);
9079 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9081 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9082 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9083 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9085 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9086 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9087 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9089 if (mcc != NULL && mnc != NULL)
9090 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9097 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9098 Build_ = [system objectForKey:@"ProductBuildVersion"];
9099 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9100 Product_ = [info objectForKey:@"SafariProductVersion"];
9101 Safari_ = [info objectForKey:@"CFBundleVersion"];
9104 /* Load Database {{{ */
9106 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9108 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9110 if (Metadata_ == NULL)
9111 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9113 Settings_ = [Metadata_ objectForKey:@"Settings"];
9115 Packages_ = [Metadata_ objectForKey:@"Packages"];
9116 Sections_ = [Metadata_ objectForKey:@"Sections"];
9117 Sources_ = [Metadata_ objectForKey:@"Sources"];
9119 Token_ = [Metadata_ objectForKey:@"Token"];
9122 if (Settings_ != nil)
9123 Role_ = [Settings_ objectForKey:@"Role"];
9125 if (Sections_ == nil) {
9126 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9127 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9130 if (Sources_ == nil) {
9131 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9132 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9137 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9140 if (Packages_ != nil) {
9141 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9143 [Metadata_ removeObjectForKey:@"Packages"];
9148 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9150 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9151 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9152 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9153 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9154 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9155 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9157 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9159 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9160 unlink("/tmp/.cydia.fw");
9162 } else if (access("/User", F_OK) != 0 || version < 2) {
9165 system("/usr/libexec/cydia/firmware.sh");
9169 _assert([[NSFileManager defaultManager]
9170 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9171 withIntermediateDirectories:YES
9176 if (access("/tmp/cydia.chk", F_OK) == 0) {
9177 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9178 _assert(errno == ENOENT);
9179 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9180 _assert(errno == ENOENT);
9183 /* APT Initialization {{{ */
9184 _assert(pkgInitConfig(*_config));
9185 _assert(pkgInitSystem(*_config, _system));
9188 _config->Set("APT::Acquire::Translation", lang);
9190 // XXX: this timeout might be important :(
9191 //_config->Set("Acquire::http::Timeout", 15);
9193 _config->Set("Acquire::http::MaxParallel", 3);
9195 /* Color Choices {{{ */
9196 space_ = CGColorSpaceCreateDeviceRGB();
9198 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9199 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9200 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9201 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9202 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9203 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9204 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9205 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9206 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9208 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9209 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9211 /* UIKit Configuration {{{ */
9212 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9213 if ($GSFontSetUseLegacyFontMetrics != NULL)
9214 $GSFontSetUseLegacyFontMetrics(YES);
9216 // XXX: I have a feeling this was important
9217 //UIKeyboardDisableAutomaticAppearance();
9220 Colon_ = UCLocalize("COLON_DELIMITED");
9221 Elision_ = UCLocalize("ELISION");
9222 Error_ = UCLocalize("ERROR");
9223 Warning_ = UCLocalize("WARNING");
9226 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9228 CGColorSpaceRelease(space_);