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;
1451 Cytore::Offset<PackageValue> packages_[1 << 16];
1454 static Cytore::File<MetaValue> MetaFile_;
1456 // Cytore Helper Functions {{{
1457 static PackageValue *PackageFind(const char *name, size_t length) {
1458 SplitHash nhash = { hashlittle(name, length) };
1460 PackageValue *metadata;
1462 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1463 offset: if (offset->IsNull()) {
1464 *offset = MetaFile_.New<PackageValue>(length + 1);
1465 metadata = &MetaFile_.Get(*offset);
1467 memcpy(metadata->name_, name, length + 1);
1468 metadata->nhash_ = nhash.u16[1];
1470 metadata = &MetaFile_.Get(*offset);
1472 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1473 offset = &metadata->next_;
1481 static void PackageImport(const void *key, const void *value, void *context) {
1483 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1484 NSLog(@"failed to import package %@", key);
1488 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1489 NSDictionary *package((NSDictionary *) value);
1491 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1492 if ([subscribed boolValue])
1493 metadata->subscribed_ = true;
1495 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1496 time_t time([date timeIntervalSince1970]);
1497 if (metadata->first_ > time || metadata->first_ == 0)
1498 metadata->first_ = time;
1501 bool versioned(false);
1503 if (NSDate *date = [package objectForKey:@"LastSeen"]) {
1504 time_t time([date timeIntervalSince1970]);
1505 if (metadata->last_ < time || metadata->last_ == 0) {
1506 metadata->last_ = time;
1509 } else if (metadata->last_ == 0) {
1510 metadata->last_ = metadata->first_;
1511 if (metadata->version_[0] == '\0')
1516 if (NSString *version = [package objectForKey:@"LastVersion"])
1517 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1518 size_t length(strlen(buffer));
1519 uint16_t vhash(hashlittle(buffer, length));
1521 size_t capped(std::min<size_t>(8, length));
1522 char *latest(buffer + length - capped);
1524 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1525 metadata->vhash_ = vhash;
1530 /* Source Class {{{ */
1531 @interface Source : NSObject {
1532 CYString depiction_;
1533 CYString description_;
1539 CYString distribution_;
1544 NSString *authority_;
1546 CYString defaultIcon_;
1548 NSDictionary *record_;
1552 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1554 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1556 - (NSString *) depictionForPackage:(NSString *)package;
1557 - (NSString *) supportForPackage:(NSString *)package;
1559 - (NSDictionary *) record;
1563 - (NSString *) distribution;
1564 - (NSString *) type;
1566 - (NSString *) host;
1568 - (NSString *) name;
1569 - (NSString *) description;
1570 - (NSString *) label;
1571 - (NSString *) origin;
1572 - (NSString *) version;
1574 - (NSString *) defaultIcon;
1578 @implementation Source
1582 distribution_.clear();
1585 description_.clear();
1591 defaultIcon_.clear();
1593 if (record_ != nil) {
1603 if (authority_ != nil) {
1604 [authority_ release];
1610 // XXX: this is a very inefficient way to call these deconstructors
1615 + (NSArray *) _attributeKeys {
1616 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1619 - (NSArray *) attributeKeys {
1620 return [[self class] _attributeKeys];
1623 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1624 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1627 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1630 trusted_ = index->IsTrusted();
1632 uri_.set(pool, index->GetURI());
1633 distribution_.set(pool, index->GetDist());
1634 type_.set(pool, index->GetType());
1636 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1637 if (dindex != NULL) {
1639 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1642 pkgTagFile tags(&fd);
1644 pkgTagSection section;
1651 {"default-icon", &defaultIcon_},
1652 {"depiction", &depiction_},
1653 {"description", &description_},
1655 {"origin", &origin_},
1656 {"support", &support_},
1657 {"version", &version_},
1660 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1661 const char *start, *end;
1663 if (section.Find(names[i].name_, start, end)) {
1664 CYString &value(*names[i].value_);
1665 value.set(pool, start, end - start);
1671 record_ = [Sources_ objectForKey:[self key]];
1673 record_ = [record_ retain];
1675 NSURL *url([NSURL URLWithString:uri_]);
1679 host_ = [[host_ lowercaseString] retain];
1684 authority_ = [url path];
1686 if (authority_ != nil)
1687 authority_ = [authority_ retain];
1690 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1691 if ((self = [super init]) != nil) {
1692 [self setMetaIndex:index inPool:pool];
1696 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1697 NSDictionary *lhr = [self record];
1698 NSDictionary *rhr = [source record];
1701 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1703 NSString *lhs = [self name];
1704 NSString *rhs = [source name];
1706 if ([lhs length] != 0 && [rhs length] != 0) {
1707 unichar lhc = [lhs characterAtIndex:0];
1708 unichar rhc = [rhs characterAtIndex:0];
1710 if (isalpha(lhc) && !isalpha(rhc))
1711 return NSOrderedAscending;
1712 else if (!isalpha(lhc) && isalpha(rhc))
1713 return NSOrderedDescending;
1716 return [lhs compare:rhs options:LaxCompareOptions_];
1719 - (NSString *) depictionForPackage:(NSString *)package {
1720 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1723 - (NSString *) supportForPackage:(NSString *)package {
1724 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1727 - (NSDictionary *) record {
1735 - (NSString *) uri {
1739 - (NSString *) distribution {
1740 return distribution_;
1743 - (NSString *) type {
1747 - (NSString *) key {
1748 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1751 - (NSString *) host {
1755 - (NSString *) name {
1756 return origin_.empty() ? authority_ : origin_;
1759 - (NSString *) description {
1760 return description_;
1763 - (NSString *) label {
1764 return label_.empty() ? authority_ : label_;
1767 - (NSString *) origin {
1771 - (NSString *) version {
1775 - (NSString *) defaultIcon {
1776 return defaultIcon_;
1781 /* Relationship Class {{{ */
1782 @interface Relationship : NSObject {
1787 - (NSString *) type;
1789 - (NSString *) name;
1793 @implementation Relationship
1801 - (NSString *) type {
1809 - (NSString *) name {
1816 /* Package Class {{{ */
1817 struct ParsedPackage {
1822 CYString depiction_;
1832 @interface Package : NSObject {
1834 uint32_t essential_ : 1;
1835 uint32_t obsolete_ : 1;
1836 uint32_t ignored_ : 1;
1840 _transient Database *database_;
1842 pkgCache::VerIterator version_;
1843 pkgCache::PkgIterator iterator_;
1844 pkgCache::VerFileIterator file_;
1850 CYString installed_;
1853 _transient NSString *section$_;
1857 PackageValue *metadata_;
1858 ParsedPackage *parsed_;
1860 NSMutableArray *tags_;
1864 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1865 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1867 - (pkgCache::PkgIterator) iterator;
1870 - (NSString *) section;
1871 - (NSString *) simpleSection;
1873 - (NSString *) longSection;
1874 - (NSString *) shortSection;
1878 - (Address *) maintainer;
1880 - (NSString *) longDescription;
1881 - (NSString *) shortDescription;
1884 - (PackageValue *) metadata;
1887 - (bool) subscribed;
1888 - (bool) setSubscribed:(bool)subscribed;
1892 - (NSString *) latest;
1893 - (NSString *) installed;
1894 - (BOOL) uninstalled;
1897 - (BOOL) upgradableAndEssential:(BOOL)essential;
1900 - (BOOL) unfiltered;
1904 - (BOOL) halfConfigured;
1905 - (BOOL) halfInstalled;
1907 - (NSString *) mode;
1910 - (NSString *) name;
1912 - (NSString *) homepage;
1913 - (NSString *) depiction;
1914 - (Address *) author;
1916 - (NSString *) support;
1918 - (NSArray *) files;
1919 - (NSArray *) warnings;
1920 - (NSArray *) applications;
1922 - (Source *) source;
1923 - (NSString *) role;
1925 - (BOOL) matches:(NSString *)text;
1927 - (bool) hasSupportingRole;
1928 - (BOOL) hasTag:(NSString *)tag;
1929 - (NSString *) primaryPurpose;
1930 - (NSArray *) purposes;
1931 - (bool) isCommercial;
1933 - (void) setIndex:(size_t)index;
1935 - (CYString &) cyname;
1937 - (uint32_t) compareBySection:(NSArray *)sections;
1942 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1943 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1944 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1945 - (bool) isVisibleInSection:(NSString *)section;
1946 - (bool) isVisibleInSource:(Source *)source;
1950 uint32_t PackageChangesRadix(Package *self, void *) {
1955 uint32_t timestamp : 30;
1956 uint32_t ignored : 1;
1957 uint32_t upgradable : 1;
1961 bool upgradable([self upgradableAndEssential:YES]);
1962 value.bits.upgradable = upgradable ? 1 : 0;
1965 value.bits.timestamp = 0;
1966 value.bits.ignored = [self ignored] ? 0 : 1;
1967 value.bits.upgradable = 1;
1969 value.bits.timestamp = [self seen] >> 2;
1970 value.bits.ignored = 0;
1971 value.bits.upgradable = 0;
1974 return _not(uint32_t) - value.key;
1977 uint32_t PackagePrefixRadix(Package *self, void *context) {
1978 size_t offset(reinterpret_cast<size_t>(context));
1979 CYString &name([self cyname]);
1981 size_t size(name.size());
1984 char *text(name.data());
1987 if (!isdigit(text[0]))
1991 while (size != digits && isdigit(text[digits]))
1999 if (offset == 0 && zeros != 0) {
2000 memset(data, '0', zeros);
2001 memcpy(data + zeros, text, 4 - zeros);
2003 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2004 if (size <= offset - zeros)
2007 text += offset - zeros;
2008 size -= offset - zeros;
2011 memcpy(data, text, 4);
2013 memcpy(data, text, size);
2014 memset(data + size, 0, 4 - size);
2017 for (size_t i(0); i != 4; ++i)
2018 if (isalpha(data[i]))
2026 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2028 /* XXX: ntohl may be more honest */
2029 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2032 CYString &(*PackageName)(Package *self, SEL sel);
2034 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2035 _profile(PackageNameCompare)
2036 CYString &lhi(PackageName(lhs, @selector(cyname)));
2037 CYString &rhi(PackageName(rhs, @selector(cyname)));
2038 CFStringRef lhn(lhi), rhn(rhi);
2041 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2042 else if (rhn == NULL)
2043 return NSOrderedDescending;
2045 _profile(PackageNameCompare$NumbersLast)
2046 if (!lhi.empty() && !rhi.empty()) {
2047 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2048 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2049 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2050 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2051 return lha ? NSOrderedAscending : NSOrderedDescending;
2055 CFIndex length = CFStringGetLength(lhn);
2057 _profile(PackageNameCompare$Compare)
2058 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2063 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2064 return PackageNameCompare(*lhs, *rhs, context);
2067 struct PackageNameOrdering :
2068 std::binary_function<Package *, Package *, bool>
2070 _finline bool operator ()(Package *lhs, Package *rhs) const {
2071 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2075 @implementation Package
2077 - (NSString *) description {
2078 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2082 if (parsed_ != NULL)
2096 + (NSString *) webScriptNameForSelector:(SEL)selector {
2097 if (selector == @selector(hasTag:))
2103 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2104 return [self webScriptNameForSelector:selector] == nil;
2107 + (NSArray *) _attributeKeys {
2108 return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"longDescription", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"longSection", @"maintainer", @"mode", @"name", @"purposes", @"section", @"shortDescription", @"shortSection", @"simpleSection", @"size", @"source", @"sponsor", @"support", @"warnings", nil];
2111 - (NSArray *) attributeKeys {
2112 return [[self class] _attributeKeys];
2115 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2116 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2120 if (parsed_ != NULL)
2122 @synchronized (database_) {
2123 if ([database_ era] != era_ || file_.end())
2126 ParsedPackage *parsed(new ParsedPackage);
2129 _profile(Package$parse)
2130 pkgRecords::Parser *parser;
2132 _profile(Package$parse$Lookup)
2133 parser = &[database_ records]->Lookup(file_);
2138 _profile(Package$parse$Find)
2143 {"icon", &parsed->icon_},
2144 {"depiction", &parsed->depiction_},
2145 {"homepage", &parsed->homepage_},
2146 {"website", &website},
2147 {"bugs", &parsed->bugs_},
2148 {"support", &parsed->support_},
2149 {"sponsor", &parsed->sponsor_},
2150 {"author", &parsed->author_},
2153 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2154 const char *start, *end;
2156 if (parser->Find(names[i].name_, start, end)) {
2157 CYString &value(*names[i].value_);
2158 _profile(Package$parse$Value)
2159 value.set(pool_, start, end - start);
2165 _profile(Package$parse$Tagline)
2166 const char *start, *end;
2167 if (parser->ShortDesc(start, end)) {
2168 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2171 while (stop != start && stop[-1] == '\r')
2173 parsed->tagline_.set(pool_, start, stop - start);
2177 _profile(Package$parse$Retain)
2178 if (parsed->homepage_.empty())
2179 parsed->homepage_ = website;
2180 if (parsed->homepage_ == parsed->depiction_)
2181 parsed->homepage_.clear();
2186 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2187 if ((self = [super init]) != nil) {
2188 _profile(Package$initWithVersion)
2191 database_ = database;
2192 era_ = [database era];
2196 pkgCache::PkgIterator iterator(version.ParentPkg());
2197 iterator_ = iterator;
2199 _profile(Package$initWithVersion$Version)
2200 if (!version_.end())
2201 file_ = version_.FileList();
2203 pkgCache &cache([database_ cache]);
2204 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2208 _profile(Package$initWithVersion$Cache)
2209 id_.set(NULL, iterator.Name());
2210 name_.set(NULL, iterator.Display());
2212 latest_.set(NULL, StripVersion_(version_.VerStr()));
2214 pkgCache::VerIterator current(iterator.CurrentVer());
2216 installed_.set(NULL, StripVersion_(current.VerStr()));
2219 _profile(Package$initWithVersion$Lower)
2220 // XXX: do not use tolower() as this is not locale-specific? :(
2221 char *data(id_.data());
2222 for (size_t i(0), e(id_.size()); i != e; ++i)
2223 if ((data[i] & 0x20) == 0) {
2232 _profile(Package$initWithVersion$Tags)
2233 pkgCache::TagIterator tag(iterator.TagList());
2235 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2237 const char *name(tag.Name());
2238 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2240 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2241 role_ = (NSString *) CYStringCreate(name + 6);
2243 if (strncmp(name, "cydia::", 7) == 0) {
2244 if (strcmp(name + 7, "essential") == 0)
2246 else if (strcmp(name + 7, "obsolete") == 0)
2251 } while (!tag.end());
2255 _profile(Package$initWithVersion$Metadata)
2256 PackageValue *metadata(PackageFind(id_.data(), id_.size()));
2257 metadata_ = metadata;
2259 const char *latest(version_.VerStr());
2260 size_t length(strlen(latest));
2262 uint16_t vhash(hashlittle(latest, length));
2264 size_t capped(std::min<size_t>(8, length));
2265 latest = latest + length - capped;
2267 if (metadata->first_ == 0)
2268 metadata->first_ = now_;
2270 if (metadata->last_ == 0)
2271 metadata->last_ = metadata->first_;
2273 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2274 if (metadata->version_[0] != '\0')
2275 metadata->last_ = now_;
2276 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2277 metadata->vhash_ = vhash;
2281 _profile(Package$initWithVersion$Section)
2282 section_.set(NULL, iterator.Section());
2285 _profile(Package$initWithVersion$Flags)
2286 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2287 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2292 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2293 pkgCache::VerIterator version;
2295 _profile(Package$packageWithIterator$GetCandidateVer)
2296 version = [database policy]->GetCandidateVer(iterator);
2304 _profile(Package$packageWithIterator$Allocate)
2305 package = [Package allocWithZone:zone];
2308 _profile(Package$packageWithIterator$Initialize)
2310 initWithVersion:version
2317 _profile(Package$packageWithIterator$Autorelease)
2318 package = [package autorelease];
2324 - (pkgCache::PkgIterator) iterator {
2328 - (NSString *) section {
2329 if (section$_ == nil) {
2330 if (section_.empty())
2333 _profile(Package$section)
2334 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2335 NSString *name(section_);
2336 section$_ = [SectionMap_ objectForKey:name] ?: name;
2341 - (NSString *) simpleSection {
2342 if (NSString *section = [self section])
2343 return Simplify(section);
2348 - (NSString *) longSection {
2349 return LocalizeSection([self section]);
2352 - (NSString *) shortSection {
2353 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2356 - (NSString *) uri {
2359 pkgIndexFile *index;
2360 pkgCache::PkgFileIterator file(file_.File());
2361 if (![database_ list].FindIndex(file, index))
2363 return [NSString stringWithUTF8String:iterator_->Path];
2364 //return [NSString stringWithUTF8String:file.Site()];
2365 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2369 - (Address *) maintainer {
2370 @synchronized (database_) {
2371 if ([database_ era] != era_ || file_.end())
2374 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2375 const std::string &maintainer(parser->Maintainer());
2376 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2380 @synchronized (database_) {
2381 if ([database_ era] != era_ || version_.end())
2384 return version_->InstalledSize;
2387 - (NSString *) longDescription {
2388 @synchronized (database_) {
2389 if ([database_ era] != era_ || file_.end())
2392 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2393 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2395 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2396 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2397 if ([lines count] < 2)
2400 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2401 for (size_t i(1), e([lines count]); i != e; ++i) {
2402 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2403 [trimmed addObject:trim];
2406 return [trimmed componentsJoinedByString:@"\n"];
2409 - (NSString *) shortDescription {
2410 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2414 _profile(Package$index)
2415 CFStringRef name((CFStringRef) [self name]);
2416 if (CFStringGetLength(name) == 0)
2418 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2419 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2421 return toupper(character);
2425 - (PackageValue *) metadata {
2430 PackageValue *metadata([self metadata]);
2431 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2434 - (bool) subscribed {
2435 return [self metadata]->subscribed_;
2438 - (bool) setSubscribed:(bool)subscribed {
2439 PackageValue *metadata([self metadata]);
2440 if (metadata->subscribed_ == subscribed)
2442 metadata->subscribed_ = subscribed;
2450 - (NSString *) latest {
2454 - (NSString *) installed {
2458 - (BOOL) uninstalled {
2459 return installed_.empty();
2463 return !version_.end();
2466 - (BOOL) upgradableAndEssential:(BOOL)essential {
2467 _profile(Package$upgradableAndEssential)
2468 pkgCache::VerIterator current(iterator_.CurrentVer());
2470 return essential && essential_;
2472 return !version_.end() && version_ != current;
2476 - (BOOL) essential {
2481 return [database_ cache][iterator_].InstBroken();
2484 - (BOOL) unfiltered {
2485 _profile(Package$unfiltered$obsolete)
2490 _profile(Package$unfiltered$hasSupportingRole)
2491 if (![self hasSupportingRole])
2499 if (![self unfiltered])
2502 NSString *section([self section]);
2504 _profile(Package$visible$isSectionVisible)
2505 if (section != nil && !isSectionVisible(section))
2513 unsigned char current(iterator_->CurrentState);
2514 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2517 - (BOOL) halfConfigured {
2518 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2521 - (BOOL) halfInstalled {
2522 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2526 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2527 return state.Mode != pkgDepCache::ModeKeep;
2530 - (NSString *) mode {
2531 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2533 switch (state.Mode) {
2534 case pkgDepCache::ModeDelete:
2535 if ((state.iFlags & pkgDepCache::Purge) != 0)
2539 case pkgDepCache::ModeKeep:
2540 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2541 return @"REINSTALL";
2542 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2546 case pkgDepCache::ModeInstall:
2547 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2548 return @"REINSTALL";
2549 else*/ switch (state.Status) {
2551 return @"DOWNGRADE";
2557 return @"NEW_INSTALL";
2568 - (NSString *) name {
2569 return name_.empty() ? id_ : name_;
2572 - (UIImage *) icon {
2573 NSString *section = [self simpleSection];
2576 if (parsed_ != NULL)
2577 if (NSString *href = parsed_->icon_)
2578 if ([href hasPrefix:@"file:///"])
2579 // XXX: correct escaping
2580 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2581 if (icon == nil) if (section != nil)
2582 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2583 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2584 if ([dicon hasPrefix:@"file:///"])
2585 // XXX: correct escaping
2586 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2588 icon = [UIImage applicationImageNamed:@"unknown.png"];
2592 - (NSString *) homepage {
2593 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2596 - (NSString *) depiction {
2597 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2600 - (Address *) sponsor {
2601 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2604 - (Address *) author {
2605 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2608 - (NSString *) support {
2609 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2612 - (NSArray *) files {
2613 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2614 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2617 fin.open([path UTF8String]);
2622 while (std::getline(fin, line))
2623 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2628 - (NSArray *) warnings {
2629 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2630 const char *name(iterator_.Name());
2632 size_t length(strlen(name));
2633 if (length < 2) invalid:
2634 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2635 else for (size_t i(0); i != length; ++i)
2637 /* XXX: technically this is not allowed */
2638 (name[i] < 'A' || name[i] > 'Z') &&
2639 (name[i] < 'a' || name[i] > 'z') &&
2640 (name[i] < '0' || name[i] > '9') &&
2641 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2644 if (strcmp(name, "cydia") != 0) {
2647 bool _private = false;
2650 bool repository = [[self section] isEqualToString:@"Repositories"];
2652 if (NSArray *files = [self files])
2653 for (NSString *file in files)
2654 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2656 else if (!user && [file isEqualToString:@"/User"])
2658 else if (!_private && [file isEqualToString:@"/private"])
2660 else if (!stash && [file isEqualToString:@"/var/stash"])
2663 /* XXX: this is not sensitive enough. only some folders are valid. */
2664 if (cydia && !repository)
2665 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2667 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2669 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2671 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2674 return [warnings count] == 0 ? nil : warnings;
2677 - (NSArray *) applications {
2678 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2680 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2682 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2683 if (NSArray *files = [self files])
2684 for (NSString *file in files)
2685 if (application_r(file)) {
2686 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2687 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2688 if ([id isEqualToString:me])
2691 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2693 display = application_r[1];
2695 NSString *bundle([file stringByDeletingLastPathComponent]);
2696 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2697 if (icon == nil || [icon length] == 0)
2699 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2701 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2702 [applications addObject:application];
2704 [application addObject:id];
2705 [application addObject:display];
2706 [application addObject:url];
2709 return [applications count] == 0 ? nil : applications;
2712 - (Source *) source {
2713 if (source_ == nil) {
2714 @synchronized (database_) {
2715 if ([database_ era] != era_ || file_.end())
2716 source_ = (Source *) [NSNull null];
2718 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2722 return source_ == (Source *) [NSNull null] ? nil : source_;
2725 - (NSString *) role {
2729 - (BOOL) matches:(NSString *)text {
2735 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2736 if (range.location != NSNotFound)
2739 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2740 if (range.location != NSNotFound)
2743 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2744 if (range.location != NSNotFound)
2750 - (bool) hasSupportingRole {
2753 if ([role_ isEqualToString:@"enduser"])
2755 if ([Role_ isEqualToString:@"User"])
2757 if ([role_ isEqualToString:@"hacker"])
2759 if ([Role_ isEqualToString:@"Hacker"])
2761 if ([role_ isEqualToString:@"developer"])
2763 if ([Role_ isEqualToString:@"Developer"])
2768 - (BOOL) hasTag:(NSString *)tag {
2769 return tags_ == nil ? NO : [tags_ containsObject:tag];
2772 - (NSString *) primaryPurpose {
2773 for (NSString *tag in tags_)
2774 if ([tag hasPrefix:@"purpose::"])
2775 return [tag substringFromIndex:9];
2779 - (NSArray *) purposes {
2780 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2781 for (NSString *tag in tags_)
2782 if ([tag hasPrefix:@"purpose::"])
2783 [purposes addObject:[tag substringFromIndex:9]];
2784 return [purposes count] == 0 ? nil : purposes;
2787 - (bool) isCommercial {
2788 return [self hasTag:@"cydia::commercial"];
2791 - (void) setIndex:(size_t)index {
2792 if (metadata_->index_ != index)
2793 metadata_->index_ = index;
2796 - (CYString &) cyname {
2797 return name_.empty() ? id_ : name_;
2800 - (uint32_t) compareBySection:(NSArray *)sections {
2801 NSString *section([self section]);
2802 for (size_t i(0), e([sections count]); i != e; ++i) {
2803 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2807 return _not(uint32_t);
2811 @synchronized (database_) {
2812 pkgProblemResolver *resolver = [database_ resolver];
2813 resolver->Clear(iterator_);
2815 pkgCacheFile &cache([database_ cache]);
2816 cache->SetReInstall(iterator_, false);
2817 cache->MarkKeep(iterator_, false);
2821 @synchronized (database_) {
2822 pkgProblemResolver *resolver = [database_ resolver];
2823 resolver->Clear(iterator_);
2824 resolver->Protect(iterator_);
2826 pkgCacheFile &cache([database_ cache]);
2827 cache->SetReInstall(iterator_, false);
2828 cache->MarkInstall(iterator_, false);
2830 pkgDepCache::StateCache &state((*cache)[iterator_]);
2831 if (!state.Install())
2832 cache->SetReInstall(iterator_, true);
2836 @synchronized (database_) {
2837 pkgProblemResolver *resolver = [database_ resolver];
2838 resolver->Clear(iterator_);
2839 resolver->Remove(iterator_);
2840 resolver->Protect(iterator_);
2842 pkgCacheFile &cache([database_ cache]);
2843 cache->SetReInstall(iterator_, false);
2844 cache->MarkDelete(iterator_, true);
2847 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2848 _profile(Package$isUnfilteredAndSearchedForBy)
2851 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2852 value &= [self unfiltered];
2855 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2856 value &= [self matches:search];
2863 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2864 if ([search length] == 0)
2867 _profile(Package$isUnfilteredAndSelectedForBy)
2870 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2871 value &= [self unfiltered];
2874 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2875 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2882 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2883 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2886 - (bool) isVisibleInSection:(NSString *)name {
2887 NSString *section([self section]);
2891 section == nil && [name length] == 0 ||
2892 [name isEqualToString:section]
2893 ) && [self visible];
2896 - (bool) isVisibleInSource:(Source *)source {
2897 return [self source] == source && [self visible];
2902 /* Section Class {{{ */
2903 @interface Section : NSObject {
2908 NSString *localized_;
2911 - (NSComparisonResult) compareByLocalized:(Section *)section;
2912 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2913 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2914 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2915 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2916 - (NSString *) name;
2923 - (void) addToCount;
2925 - (void) setCount:(size_t)count;
2926 - (NSString *) localized;
2930 @implementation Section
2934 if (localized_ != nil)
2935 [localized_ release];
2939 - (NSComparisonResult) compareByLocalized:(Section *)section {
2940 NSString *lhs(localized_);
2941 NSString *rhs([section localized]);
2943 /*if ([lhs length] != 0 && [rhs length] != 0) {
2944 unichar lhc = [lhs characterAtIndex:0];
2945 unichar rhc = [rhs characterAtIndex:0];
2947 if (isalpha(lhc) && !isalpha(rhc))
2948 return NSOrderedAscending;
2949 else if (!isalpha(lhc) && isalpha(rhc))
2950 return NSOrderedDescending;
2953 return [lhs compare:rhs options:LaxCompareOptions_];
2956 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2957 if ((self = [self initWithName:name localize:NO]) != nil) {
2958 if (localized != nil)
2959 localized_ = [localized retain];
2963 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2964 return [self initWithName:name row:0 localize:localize];
2967 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2968 if ((self = [super init]) != nil) {
2969 name_ = [name retain];
2973 localized_ = [LocalizeSection(name_) retain];
2977 /* XXX: localize the index thingees */
2978 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2979 if ((self = [super init]) != nil) {
2980 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2986 - (NSString *) name {
3006 - (void) addToCount {
3010 - (void) setCount:(size_t)count {
3014 - (NSString *) localized {
3021 static NSString *Colon_;
3022 static NSString *Elision_;
3023 static NSString *Error_;
3024 static NSString *Warning_;
3026 /* Database Implementation {{{ */
3027 @implementation Database
3029 + (Database *) sharedInstance {
3030 static Database *instance;
3031 if (instance == nil)
3032 instance = [[Database alloc] init];
3040 - (void) releasePackages {
3041 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3042 CFArrayRemoveAllValues(packages_);
3046 // XXX: actually implement this thing
3048 [self releasePackages];
3049 apr_pool_destroy(pool_);
3050 NSRecycleZone(zone_);
3054 - (void) _readCydia:(NSNumber *)fd { _pooled
3055 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3056 std::istream is(&ib);
3059 static Pcre finish_r("^finish:([^:]*)$");
3061 while (std::getline(is, line)) {
3062 const char *data(line.c_str());
3063 size_t size = line.size();
3064 lprintf("C:%s\n", data);
3066 if (finish_r(data, size)) {
3067 NSString *finish = finish_r[1];
3068 int index = [Finishes_ indexOfObject:finish];
3069 if (index != INT_MAX && index > Finish_)
3077 - (void) _readStatus:(NSNumber *)fd { _pooled
3078 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3079 std::istream is(&ib);
3082 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3083 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3085 while (std::getline(is, line)) {
3086 const char *data(line.c_str());
3087 size_t size(line.size());
3088 lprintf("S:%s\n", data);
3090 if (conffile_r(data, size)) {
3091 [delegate_ setConfigurationData:conffile_r[1]];
3092 } else if (strncmp(data, "status: ", 8) == 0) {
3093 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3094 [delegate_ setProgressTitle:string];
3095 } else if (pmstatus_r(data, size)) {
3096 std::string type([pmstatus_r[1] UTF8String]);
3097 NSString *id = pmstatus_r[2];
3099 float percent([pmstatus_r[3] floatValue]);
3100 [delegate_ setProgressPercent:(percent / 100)];
3102 NSString *string = pmstatus_r[4];
3104 if (type == "pmerror")
3105 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3106 withObject:[NSArray arrayWithObjects:string, id, nil]
3109 else if (type == "pmstatus") {
3110 [delegate_ setProgressTitle:string];
3111 } else if (type == "pmconffile")
3112 [delegate_ setConfigurationData:string];
3114 lprintf("E:unknown pmstatus\n");
3116 lprintf("E:unknown status\n");
3122 - (void) _readOutput:(NSNumber *)fd { _pooled
3123 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3124 std::istream is(&ib);
3127 while (std::getline(is, line)) {
3128 lprintf("O:%s\n", line.c_str());
3129 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3139 - (Package *) packageWithName:(NSString *)name {
3140 @synchronized (self) {
3141 if (static_cast<pkgDepCache *>(cache_) == NULL)
3143 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3144 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3148 if ((self = [super init]) != nil) {
3155 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3156 apr_pool_create(&pool_, NULL);
3158 size_t capacity(MetaFile_->active_);
3164 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3168 _assert(pipe(fds) != -1);
3171 _config->Set("APT::Keep-Fds::", cydiafd_);
3172 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3175 detachNewThreadSelector:@selector(_readCydia:)
3177 withObject:[NSNumber numberWithInt:fds[0]]
3180 _assert(pipe(fds) != -1);
3184 detachNewThreadSelector:@selector(_readStatus:)
3186 withObject:[NSNumber numberWithInt:fds[0]]
3189 _assert(pipe(fds) != -1);
3190 _assert(dup2(fds[0], 0) != -1);
3191 _assert(close(fds[0]) != -1);
3193 input_ = fdopen(fds[1], "a");
3195 _assert(pipe(fds) != -1);
3196 _assert(dup2(fds[1], 1) != -1);
3197 _assert(close(fds[1]) != -1);
3200 detachNewThreadSelector:@selector(_readOutput:)
3202 withObject:[NSNumber numberWithInt:fds[0]]
3207 - (pkgCacheFile &) cache {
3211 - (pkgDepCache::Policy *) policy {
3215 - (pkgRecords *) records {
3219 - (pkgProblemResolver *) resolver {
3223 - (pkgAcquire &) fetcher {
3227 - (pkgSourceList &) list {
3231 - (NSArray *) packages {
3232 return (NSArray *) packages_;
3235 - (NSArray *) sources {
3236 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3237 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3238 [sources addObject:i->second];
3242 - (NSArray *) issues {
3243 if (cache_->BrokenCount() == 0)
3246 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3248 for (Package *package in [self packages]) {
3249 if (![package broken])
3251 pkgCache::PkgIterator pkg([package iterator]);
3253 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3254 [entry addObject:[package name]];
3255 [issues addObject:entry];
3257 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3261 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3262 pkgCache::DepIterator start;
3263 pkgCache::DepIterator end;
3264 dep.GlobOr(start, end); // ++dep
3266 if (!cache_->IsImportantDep(end))
3268 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3271 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3272 [entry addObject:failure];
3273 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3275 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3276 if (Package *package = [self packageWithName:name])
3277 name = [package name];
3278 [failure addObject:name];
3280 pkgCache::PkgIterator target(start.TargetPkg());
3281 if (target->ProvidesList != 0)
3282 [failure addObject:@"?"];
3284 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3286 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3287 else if (!cache_[target].CandidateVerIter(cache_).end())
3288 [failure addObject:@"-"];
3289 else if (target->ProvidesList == 0)
3290 [failure addObject:@"!"];
3292 [failure addObject:@"%"];
3296 if (start.TargetVer() != 0)
3297 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3308 - (bool) popErrorWithTitle:(NSString *)title {
3310 std::string message;
3312 while (!_error->empty()) {
3314 bool warning(!_error->PopMessage(error));
3318 size_t size(error.size());
3319 if (size == 0 || error[size - 1] != '\n')
3321 error.resize(size - 1);
3323 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3325 if (!message.empty())
3330 if (fatal && !message.empty())
3331 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3336 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3337 return [self popErrorWithTitle:title] || !success;
3340 - (void) reloadData { CYPoolStart() {
3341 @synchronized (self) {
3344 [self releasePackages];
3365 apr_pool_clear(pool_);
3366 NSRecycleZone(zone_);
3368 int chk(creat("/tmp/cydia.chk", 0644));
3372 NSString *title(UCLocalize("DATABASE"));
3375 if (!cache_.Open(progress_, true)) { pop:
3377 bool warning(!_error->PopMessage(error));
3378 lprintf("cache_.Open():[%s]\n", error.c_str());
3380 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3381 [delegate_ repairWithSelector:@selector(configure)];
3382 else if (error == "The package lists or status file could not be parsed or opened.")
3383 [delegate_ repairWithSelector:@selector(update)];
3384 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3385 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3386 // else if (error == "The list of sources could not be read.")
3388 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3397 unlink("/tmp/cydia.chk");
3399 now_ = [[NSDate date] timeIntervalSince1970];
3401 policy_ = new pkgDepCache::Policy();
3402 records_ = new pkgRecords(cache_);
3403 resolver_ = new pkgProblemResolver(cache_);
3404 fetcher_ = new pkgAcquire(&status_);
3407 list_ = new pkgSourceList();
3408 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3411 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3412 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3416 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3419 if (cache_->BrokenCount() != 0) {
3420 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3423 if (cache_->BrokenCount() != 0) {
3424 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3428 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3432 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3433 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3434 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3435 // XXX: this could be more intelligent
3436 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3437 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3439 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3444 /*std::vector<Package *> packages;
3445 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3446 [packages_ release];
3451 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3452 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3453 //packages.push_back(package);
3454 CFArrayAppendValue(packages_, [package retain]);
3458 /*if (packages.empty())
3459 packages_ = [[NSArray alloc] init];
3461 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3464 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3465 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3466 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3474 /*if (!packages.empty())
3475 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3476 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3478 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3480 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3482 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3486 size_t count(CFArrayGetCount(packages_));
3487 MetaFile_->active_ = count;
3489 for (size_t index(0); index != count; ++index)
3490 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3494 } } CYPoolEnd() _trace(); }
3497 @synchronized (self) {
3499 resolver_ = new pkgProblemResolver(cache_);
3501 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3502 if (!cache_[iterator].Keep()) {
3503 cache_->MarkKeep(iterator, false);
3504 cache_->SetReInstall(iterator, false);
3509 - (void) configure {
3510 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3511 system([dpkg UTF8String]);
3515 // XXX: I don't remember this condition
3520 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3522 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3524 if ([self popErrorWithTitle:title])
3528 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3531 public pkgArchiveCleaner
3534 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3539 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3546 fetcher_->Shutdown();
3548 pkgRecords records(cache_);
3550 lock_ = new FileFd();
3551 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3553 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3555 if ([self popErrorWithTitle:title])
3559 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3562 manager_ = (_system->CreatePM(cache_));
3563 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3570 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3572 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3574 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3576 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3577 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3580 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3585 bool failed = false;
3586 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3587 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3589 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3592 std::string uri = (*item)->DescURI();
3593 std::string error = (*item)->ErrorText;
3595 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3598 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3599 withObject:[NSArray arrayWithObjects:
3600 [NSString stringWithUTF8String:error.c_str()],
3612 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3614 if (_error->PendingError()) {
3619 if (result == pkgPackageManager::Failed) {
3624 if (result != pkgPackageManager::Completed) {
3629 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3631 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3633 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3634 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3637 if (![before isEqualToArray:after])
3642 NSString *title(UCLocalize("UPGRADE"));
3643 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3649 [self updateWithStatus:status_];
3652 - (void) updateWithStatus:(Status &)status {
3653 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3654 NSString *title(UCLocalize("REFRESHING_DATA"));
3657 if (!list.ReadMainList())
3658 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3661 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3662 if ([self popErrorWithTitle:title])
3665 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3666 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3667 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3669 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3673 - (void) setDelegate:(id)delegate {
3674 delegate_ = delegate;
3675 status_.setDelegate(delegate);
3676 progress_.setDelegate(delegate);
3679 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3680 SourceMap::const_iterator i(sources_.find(file->ID));
3681 return i == sources_.end() ? nil : i->second;
3687 /* Confirmation Controller {{{ */
3688 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3689 if (!iterator.end())
3690 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3691 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3693 pkgCache::PkgIterator package(dep.TargetPkg());
3696 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3704 /* Web Scripting {{{ */
3705 @interface CydiaObject : NSObject {
3707 _transient id delegate_;
3710 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3713 @implementation CydiaObject
3716 [indirect_ release];
3720 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3721 if ((self = [super init]) != nil) {
3722 indirect_ = [indirect retain];
3726 - (void) setDelegate:(id)delegate {
3727 delegate_ = delegate;
3730 + (NSArray *) _attributeKeys {
3731 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3734 - (NSArray *) attributeKeys {
3735 return [[self class] _attributeKeys];
3738 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3739 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3742 - (NSString *) device {
3743 return [[UIDevice currentDevice] uniqueIdentifier];
3746 #if 0 // XXX: implement!
3747 - (NSString *) mac {
3748 if (![indirect_ promptForSensitive:@"Mac Address"])
3752 - (NSString *) serial {
3753 if (![indirect_ promptForSensitive:@"Serial #"])
3757 - (NSString *) firewire {
3758 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3762 - (NSString *) imei {
3763 if (![indirect_ promptForSensitive:@"IMEI"])
3768 + (NSString *) webScriptNameForSelector:(SEL)selector {
3769 if (selector == @selector(close))
3771 else if (selector == @selector(getInstalledPackages))
3772 return @"getInstalledPackages";
3773 else if (selector == @selector(getPackageById:))
3774 return @"getPackageById";
3775 else if (selector == @selector(installPackages:))
3776 return @"installPackages";
3777 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3778 return @"setButtonImage";
3779 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3780 return @"setButtonTitle";
3781 else if (selector == @selector(setPopupHook:))
3782 return @"setPopupHook";
3783 else if (selector == @selector(setSpecial:))
3784 return @"setSpecial";
3785 else if (selector == @selector(setToken:))
3787 else if (selector == @selector(setViewportWidth:))
3788 return @"setViewportWidth";
3789 else if (selector == @selector(supports:))
3791 else if (selector == @selector(stringWithFormat:arguments:))
3793 else if (selector == @selector(localizedStringForKey:value:table:))
3795 else if (selector == @selector(du:))
3797 else if (selector == @selector(statfs:))
3803 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3804 return [self webScriptNameForSelector:selector] == nil;
3807 - (BOOL) supports:(NSString *)feature {
3808 return [feature isEqualToString:@"window.open"];
3811 - (NSArray *) getInstalledPackages {
3812 NSArray *packages([[Database sharedInstance] packages]);
3813 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3814 for (Package *package in packages)
3815 if ([package installed] != nil)
3816 [installed addObject:package];
3820 - (Package *) getPackageById:(NSString *)id {
3821 Package *package([[Database sharedInstance] packageWithName:id]);
3826 - (NSArray *) statfs:(NSString *)path {
3829 if (path == nil || statfs([path UTF8String], &stat) == -1)
3832 return [NSArray arrayWithObjects:
3833 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3834 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3835 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3839 - (NSNumber *) du:(NSString *)path {
3840 NSNumber *value(nil);
3843 _assert(pipe(fds) != -1);
3845 pid_t pid(ExecFork());
3847 _assert(dup2(fds[1], 1) != -1);
3848 _assert(close(fds[0]) != -1);
3849 _assert(close(fds[1]) != -1);
3850 /* XXX: this should probably not use du */
3851 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3856 _assert(close(fds[1]) != -1);
3858 if (FILE *du = fdopen(fds[0], "r")) {
3860 while (fgets(line, sizeof(line), du) != NULL) {
3861 size_t length(strlen(line));
3862 while (length != 0 && line[length - 1] == '\n')
3863 line[--length] = '\0';
3864 if (char *tab = strchr(line, '\t')) {
3866 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3871 } else _assert(close(fds[0]));
3875 if (waitpid(pid, &status, 0) == -1)
3878 else _assert(false);
3887 - (void) installPackages:(NSArray *)packages {
3888 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3891 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3892 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3895 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3896 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3899 - (void) setSpecial:(id)function {
3900 [indirect_ setSpecial:function];
3903 - (void) setToken:(NSString *)token {
3906 Token_ = [token retain];
3908 [Metadata_ setObject:Token_ forKey:@"Token"];
3912 - (void) setPopupHook:(id)function {
3913 [indirect_ setPopupHook:function];
3916 - (void) setViewportWidth:(float)width {
3917 [indirect_ setViewportWidth:width];
3920 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3921 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3922 unsigned count([arguments count]);
3924 for (unsigned i(0); i != count; ++i)
3925 values[i] = [arguments objectAtIndex:i];
3926 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3929 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3930 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3932 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3934 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3940 /* Cydia Browser Controller {{{ */
3941 @interface CYBrowserController : BrowserController {
3942 CydiaObject *cydia_;
3947 @implementation CYBrowserController
3954 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3957 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3958 [super webView:view didClearWindowObject:window forFrame:frame];
3960 WebDataSource *source([frame dataSource]);
3961 NSURLResponse *response([source response]);
3962 NSURL *url([response URL]);
3963 NSString *scheme([url scheme]);
3965 NSHTTPURLResponse *http;
3966 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3967 http = (NSHTTPURLResponse *) response;
3971 NSDictionary *headers([http allHeaderFields]);
3972 NSString *host([url host]);
3973 [self setHeaders:headers forHost:host];
3976 [host isEqualToString:@"cydia.saurik.com"] ||
3977 [host hasSuffix:@".cydia.saurik.com"] ||
3978 [scheme isEqualToString:@"file"]
3980 [window setValue:cydia_ forKey:@"cydia"];
3983 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3984 if (System_ != NULL)
3985 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3986 if (Machine_ != NULL)
3987 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3989 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3991 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3994 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3995 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3996 [self _setMoreHeaders:copy];
4000 - (void) setDelegate:(id)delegate {
4001 [super setDelegate:delegate];
4002 [cydia_ setDelegate:delegate];
4006 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4007 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4009 WebView *webview([[webview_ _documentView] webView]);
4011 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4013 NSString *application = package == nil ? @"Cydia" : [NSString
4014 stringWithFormat:@"Cydia/%@",
4019 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4021 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4022 if (Product_ != nil)
4023 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4025 [webview setApplicationNameForUserAgent:application];
4032 /* Confirmation {{{ */
4033 @protocol ConfirmationControllerDelegate
4034 - (void) cancelAndClear:(bool)clear;
4035 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4039 @interface ConfirmationController : CYBrowserController {
4040 _transient Database *database_;
4041 UIAlertView *essential_;
4048 - (id) initWithDatabase:(Database *)database;
4052 @implementation ConfirmationController
4059 if (essential_ != nil)
4060 [essential_ release];
4064 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4065 NSString *context([alert context]);
4067 if ([context isEqualToString:@"remove"]) {
4068 if (button == [alert cancelButtonIndex]) {
4069 [self dismissModalViewControllerAnimated:YES];
4070 } else if (button == [alert firstOtherButtonIndex]) {
4073 [delegate_ confirmWithNavigationController:[self navigationController]];
4076 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4077 } else if ([context isEqualToString:@"unable"]) {
4078 [self dismissModalViewControllerAnimated:YES];
4079 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4081 [super alertView:alert clickedButtonAtIndex:button];
4085 - (void) _doContinue {
4086 [self dismissModalViewControllerAnimated:YES];
4087 [delegate_ cancelAndClear:NO];
4090 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4091 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4095 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4096 [super webView:view didClearWindowObject:window forFrame:frame];
4097 [window setValue:changes_ forKey:@"changes"];
4098 [window setValue:issues_ forKey:@"issues"];
4099 [window setValue:sizes_ forKey:@"sizes"];
4100 [window setValue:self forKey:@"queue"];
4103 - (id) initWithDatabase:(Database *)database {
4104 if ((self = [super init]) != nil) {
4105 database_ = database;
4107 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4109 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4110 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4111 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4112 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4113 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4117 pkgDepCache::Policy *policy([database_ policy]);
4119 pkgCacheFile &cache([database_ cache]);
4120 NSArray *packages = [database_ packages];
4121 for (Package *package in packages) {
4122 pkgCache::PkgIterator iterator = [package iterator];
4123 pkgDepCache::StateCache &state(cache[iterator]);
4125 NSString *name([package name]);
4127 if (state.NewInstall())
4128 [installing addObject:name];
4129 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4130 [reinstalling addObject:name];
4131 else if (state.Upgrade())
4132 [upgrading addObject:name];
4133 else if (state.Downgrade())
4134 [downgrading addObject:name];
4135 else if (state.Delete()) {
4136 if ([package essential])
4138 [removing addObject:name];
4141 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4142 substrate_ |= DepSubstrate(iterator.CurrentVer());
4147 else if (Advanced_) {
4148 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4150 essential_ = [[UIAlertView alloc]
4151 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4152 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4154 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4155 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4158 [essential_ setContext:@"remove"];
4160 essential_ = [[UIAlertView alloc]
4161 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4162 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4164 cancelButtonTitle:UCLocalize("OKAY")
4165 otherButtonTitles:nil
4168 [essential_ setContext:@"unable"];
4171 changes_ = [[NSArray alloc] initWithObjects:
4179 issues_ = [database_ issues];
4181 issues_ = [issues_ retain];
4183 sizes_ = [[NSArray alloc] initWithObjects:
4184 SizeString([database_ fetcher].FetchNeeded()),
4185 SizeString([database_ fetcher].PartialPresent()),
4188 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4190 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4191 initWithTitle:UCLocalize("CANCEL")
4192 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4193 style:UIBarButtonItemStylePlain
4195 action:@selector(cancelButtonClicked)
4200 - (void) applyRightButton {
4201 #if !AlwaysReload && !IgnoreInstall
4202 if (issues_ == nil && ![self isLoading])
4203 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4204 initWithTitle:UCLocalize("CONFIRM")
4205 style:UIBarButtonItemStylePlain
4207 action:@selector(confirmButtonClicked)
4210 [super applyRightButton];
4212 [[self navigationItem] setRightBarButtonItem:nil];
4216 - (void) cancelButtonClicked {
4217 [self dismissModalViewControllerAnimated:YES];
4218 [delegate_ cancelAndClear:YES];
4222 - (void) confirmButtonClicked {
4226 if (essential_ != nil)
4231 [delegate_ confirmWithNavigationController:[self navigationController]];
4239 /* Progress Data {{{ */
4240 @interface ProgressData : NSObject {
4242 // XXX: should these really both be _transient?
4243 _transient id target_;
4244 _transient id object_;
4247 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4254 @implementation ProgressData
4256 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4257 if ((self = [super init]) != nil) {
4258 selector_ = selector;
4278 /* Progress Controller {{{ */
4279 @interface ProgressController : CYViewController <
4280 ConfigurationDelegate,
4283 _transient Database *database_;
4284 UIProgressBar *progress_;
4285 UITextView *output_;
4286 UITextLabel *status_;
4287 UIPushButton *close_;
4289 SHA1SumValue springlist_;
4290 SHA1SumValue notifyconf_;
4294 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4296 - (void) _retachThread;
4297 - (void) _detachNewThreadData:(ProgressData *)data;
4298 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4304 @protocol ProgressControllerDelegate
4305 - (void) progressControllerIsComplete:(ProgressController *)sender;
4308 @implementation ProgressController
4311 [database_ setDelegate:nil];
4312 [progress_ release];
4321 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4322 if ((self = [super init]) != nil) {
4323 database_ = database;
4324 [database_ setDelegate:self];
4325 delegate_ = delegate;
4327 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4329 progress_ = [[UIProgressBar alloc] init];
4330 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4331 [progress_ setStyle:0];
4333 status_ = [[UITextLabel alloc] init];
4334 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4335 [status_ setColor:[UIColor whiteColor]];
4336 [status_ setBackgroundColor:[UIColor clearColor]];
4337 [status_ setCentersHorizontally:YES];
4338 //[status_ setFont:font];
4340 output_ = [[UITextView alloc] init];
4342 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4343 //[output_ setTextFont:@"Courier New"];
4344 [output_ setFont:[[output_ font] fontWithSize:12]];
4345 [output_ setTextColor:[UIColor whiteColor]];
4346 [output_ setBackgroundColor:[UIColor clearColor]];
4347 [output_ setMarginTop:0];
4348 [output_ setAllowsRubberBanding:YES];
4349 [output_ setEditable:NO];
4350 [[self view] addSubview:output_];
4352 close_ = [[UIPushButton alloc] init];
4353 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4354 [close_ setAutosizesToFit:NO];
4355 [close_ setDrawsShadow:YES];
4356 [close_ setStretchBackground:YES];
4357 [close_ setEnabled:YES];
4358 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4359 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4360 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4361 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4365 - (void) positionViews {
4366 CGRect bounds = [[self view] bounds];
4367 CGSize prgsize = [UIProgressBar defaultSize];
4370 (bounds.size.width - prgsize.width) / 2,
4371 bounds.size.height - prgsize.height - 20
4374 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4376 [progress_ setFrame:prgrect];
4377 [status_ setFrame:CGRectMake(
4379 bounds.size.height - prgsize.height - 50,
4380 bounds.size.width - 20,
4383 [output_ setFrame:CGRectMake(
4386 bounds.size.width - 20,
4387 bounds.size.height - 62
4389 [close_ setFrame:CGRectMake(
4390 (bounds.size.width - closewidth) / 2,
4391 bounds.size.height - prgsize.height - 50,
4397 - (void) viewWillAppear:(BOOL)animated {
4398 [super viewDidAppear:animated];
4399 [[self navigationItem] setHidesBackButton:YES];
4400 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4402 [self positionViews];
4405 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4406 [self positionViews];
4409 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4410 NSString *context([alert context]);
4412 if ([context isEqualToString:@"conffile"]) {
4413 FILE *input = [database_ input];
4414 if (button == [alert cancelButtonIndex])
4415 fprintf(input, "N\n");
4416 else if (button == [alert firstOtherButtonIndex])
4417 fprintf(input, "Y\n");
4422 - (void) closeButtonPushed {
4425 UpdateExternalStatus(0);
4429 [self dismissModalViewControllerAnimated:YES];
4433 [delegate_ terminateWithSuccess];
4434 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4435 [delegate_ suspendWithAnimation:YES];
4437 [delegate_ suspend];*/
4441 system("launchctl stop com.apple.SpringBoard");
4445 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4454 - (void) _retachThread {
4455 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4457 [[self view] addSubview:close_];
4458 [progress_ removeFromSuperview];
4459 [status_ removeFromSuperview];
4461 [database_ popErrorWithTitle:title_];
4462 [delegate_ progressControllerIsComplete:self];
4466 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4469 MMap mmap(file, MMap::ReadOnly);
4471 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4472 if (!(notifyconf_ == sha1.Result()))
4479 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4482 MMap mmap(file, MMap::ReadOnly);
4484 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4485 if (!(springlist_ == sha1.Result()))
4491 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4492 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4493 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4494 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4495 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4498 system("su -c /usr/bin/uicache mobile");
4500 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4502 [delegate_ setStatusBarShowsProgress:NO];
4505 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4506 [[data target] performSelector:[data selector] withObject:[data object]];
4507 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4510 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4511 UpdateExternalStatus(1);
4518 title_ = [title retain];
4520 [[self navigationItem] setTitle:title_];
4522 [status_ setText:nil];
4523 [output_ setText:@""];
4524 [progress_ setProgress:0];
4526 [close_ removeFromSuperview];
4527 [[self view] addSubview:progress_];
4528 [[self view] addSubview:status_];
4530 [delegate_ setStatusBarShowsProgress:YES];
4535 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4538 MMap mmap(file, MMap::ReadOnly);
4540 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4541 notifyconf_ = sha1.Result();
4547 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4550 MMap mmap(file, MMap::ReadOnly);
4552 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4553 springlist_ = sha1.Result();
4558 detachNewThreadSelector:@selector(_detachNewThreadData:)
4560 withObject:[[[ProgressData alloc]
4561 initWithSelector:selector
4568 - (void) repairWithSelector:(SEL)selector {
4570 detachNewThreadSelector:selector
4573 title:UCLocalize("REPAIRING")
4577 - (void) setConfigurationData:(NSString *)data {
4579 performSelectorOnMainThread:@selector(_setConfigurationData:)
4585 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4586 CYActionSheet *sheet([[[CYActionSheet alloc]
4588 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4589 defaultButtonIndex:0
4592 [sheet setMessage:error];
4593 [sheet yieldToPopupAlertAnimated:YES];
4597 - (void) setProgressTitle:(NSString *)title {
4599 performSelectorOnMainThread:@selector(_setProgressTitle:)
4605 - (void) setProgressPercent:(float)percent {
4607 performSelectorOnMainThread:@selector(_setProgressPercent:)
4608 withObject:[NSNumber numberWithFloat:percent]
4613 - (void) startProgress {
4616 - (void) addProgressOutput:(NSString *)output {
4618 performSelectorOnMainThread:@selector(_addProgressOutput:)
4624 - (bool) isCancelling:(size_t)received {
4628 - (void) _setConfigurationData:(NSString *)data {
4629 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4631 if (!conffile_r(data)) {
4632 lprintf("E:invalid conffile\n");
4636 NSString *ofile = conffile_r[1];
4637 //NSString *nfile = conffile_r[2];
4639 UIAlertView *alert = [[[UIAlertView alloc]
4640 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4641 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4643 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4644 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4645 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4649 [alert setContext:@"conffile"];
4653 - (void) _setProgressTitle:(NSString *)title {
4654 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4655 for (size_t i(0), e([words count]); i != e; ++i) {
4656 NSString *word([words objectAtIndex:i]);
4657 if (Package *package = [database_ packageWithName:word])
4658 [words replaceObjectAtIndex:i withObject:[package name]];
4661 [status_ setText:[words componentsJoinedByString:@" "]];
4664 - (void) _setProgressPercent:(NSNumber *)percent {
4665 [progress_ setProgress:[percent floatValue]];
4668 - (void) _addProgressOutput:(NSString *)output {
4669 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4670 CGSize size = [output_ contentSize];
4671 CGRect rect = {{0, size.height}, {size.width, 0}};
4672 [output_ scrollRectToVisible:rect animated:YES];
4675 - (BOOL) isRunning {
4682 /* Cell Content View {{{ */
4683 @protocol ContentDelegate
4684 - (void) drawContentRect:(CGRect)rect;
4687 @interface ContentView : UIView {
4688 _transient id<ContentDelegate> delegate_;
4693 @implementation ContentView
4695 - (id) initWithFrame:(CGRect)frame {
4696 if ((self = [super initWithFrame:frame]) != nil) {
4697 [self setNeedsDisplayOnBoundsChange:YES];
4701 - (void) setDelegate:(id<ContentDelegate>)delegate {
4702 delegate_ = delegate;
4705 - (void) drawRect:(CGRect)rect {
4706 [super drawRect:rect];
4707 [delegate_ drawContentRect:rect];
4712 /* Cydia TableView Cell {{{ */
4713 @interface CYTableViewCell : UITableViewCell {
4714 ContentView *content_;
4720 @implementation CYTableViewCell
4727 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4728 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4730 if (view == content_) {
4731 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4732 highlighted_ = highlighted;
4735 [super _updateHighlightColorsForView:view highlighted:highlighted];
4738 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4739 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4740 highlighted_ = selected;
4742 [super setSelected:selected animated:animated];
4743 [content_ setNeedsDisplay];
4748 /* Package Cell {{{ */
4749 @interface PackageCell : CYTableViewCell <
4754 NSString *description_;
4762 - (PackageCell *) init;
4763 - (void) setPackage:(Package *)package;
4765 + (int) heightForPackage:(Package *)package;
4766 - (void) drawContentRect:(CGRect)rect;
4770 @implementation PackageCell
4772 - (void) clearPackage {
4783 if (description_ != nil) {
4784 [description_ release];
4788 if (source_ != nil) {
4793 if (badge_ != nil) {
4798 if (placard_ != nil) {
4808 [self clearPackage];
4812 - (PackageCell *) init {
4813 CGRect frame(CGRectMake(0, 0, 320, 74));
4814 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4815 UIView *content([self contentView]);
4816 CGRect bounds([content bounds]);
4818 content_ = [[ContentView alloc] initWithFrame:bounds];
4819 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4820 [content addSubview:content_];
4822 [content_ setDelegate:self];
4823 [content_ setOpaque:YES];
4827 - (void) _setBackgroundColor {
4829 if (NSString *mode = [package_ mode]) {
4830 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4831 color = remove ? RemovingColor_ : InstallingColor_;
4833 color = [UIColor whiteColor];
4835 [content_ setBackgroundColor:color];
4836 [self setNeedsDisplay];
4839 - (void) setPackage:(Package *)package {
4840 [self clearPackage];
4843 Source *source = [package source];
4845 icon_ = [[package icon] retain];
4846 name_ = [[package name] retain];
4849 description_ = [package longDescription];
4850 if (description_ == nil)
4851 description_ = [package shortDescription];
4852 if (description_ != nil)
4853 description_ = [description_ retain];
4855 commercial_ = [package isCommercial];
4857 package_ = [package retain];
4859 NSString *label = nil;
4860 bool trusted = false;
4862 if (source != nil) {
4863 label = [source label];
4864 trusted = [source trusted];
4865 } else if ([[package id] isEqualToString:@"firmware"])
4866 label = UCLocalize("APPLE");
4868 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4870 NSString *from(label);
4872 NSString *section = [package simpleSection];
4873 if (section != nil && ![section isEqualToString:label]) {
4874 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4875 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4878 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4879 source_ = [from retain];
4881 if (NSString *purpose = [package primaryPurpose])
4882 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4883 badge_ = [badge_ retain];
4885 if ([package installed] != nil)
4886 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4887 placard_ = [placard_ retain];
4889 [self _setBackgroundColor];
4890 [content_ setNeedsDisplay];
4893 - (void) drawContentRect:(CGRect)rect {
4894 bool highlighted(highlighted_);
4895 float width([self bounds].size.width);
4898 CGContextRef context(UIGraphicsGetCurrentContext());
4899 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4900 CGContextFillRect(context, rect);
4905 rect.size = [icon_ size];
4907 rect.size.width /= 2;
4908 rect.size.height /= 2;
4910 rect.origin.x = 25 - rect.size.width / 2;
4911 rect.origin.y = 25 - rect.size.height / 2;
4913 [icon_ drawInRect:rect];
4916 if (badge_ != nil) {
4917 CGSize size = [badge_ size];
4919 [badge_ drawAtPoint:CGPointMake(
4920 36 - size.width / 2,
4921 36 - size.height / 2
4929 UISetColor(commercial_ ? Purple_ : Black_);
4930 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4931 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4934 UISetColor(commercial_ ? Purplish_ : Gray_);
4935 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4937 if (placard_ != nil)
4938 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4941 + (int) heightForPackage:(Package *)package {
4947 /* Section Cell {{{ */
4948 @interface SectionCell : CYTableViewCell <
4960 - (void) setSection:(Section *)section editing:(BOOL)editing;
4964 @implementation SectionCell
4966 - (void) clearSection {
4967 if (basic_ != nil) {
4972 if (section_ != nil) {
4982 if (count_ != nil) {
4989 [self clearSection];
4995 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4996 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4997 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4998 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4999 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5001 UIView *content([self contentView]);
5002 CGRect bounds([content bounds]);
5004 content_ = [[ContentView alloc] initWithFrame:bounds];
5005 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5006 [content addSubview:content_];
5007 [content_ setBackgroundColor:[UIColor whiteColor]];
5009 [content_ setDelegate:self];
5013 - (void) onSwitch:(id)sender {
5014 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5015 if (metadata == nil) {
5016 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5017 [Sections_ setObject:metadata forKey:basic_];
5020 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5024 - (void) setSection:(Section *)section editing:(BOOL)editing {
5025 if (editing != editing_) {
5027 [switch_ removeFromSuperview];
5029 [self addSubview:switch_];
5033 [self clearSection];
5035 if (section == nil) {
5036 name_ = [UCLocalize("ALL_PACKAGES") retain];
5039 basic_ = [section name];
5041 basic_ = [basic_ retain];
5043 section_ = [section localized];
5044 if (section_ != nil)
5045 section_ = [section_ retain];
5047 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5048 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5051 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5054 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5055 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5057 [content_ setNeedsDisplay];
5060 - (void) setFrame:(CGRect)frame {
5061 [super setFrame:frame];
5063 CGRect rect([switch_ frame]);
5064 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5067 - (void) drawContentRect:(CGRect)rect {
5068 bool highlighted(highlighted_);
5070 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5075 float width(rect.size.width);
5081 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5083 CGSize size = [count_ sizeWithFont:Font14_];
5087 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5093 /* File Table {{{ */
5094 @interface FileTable : CYViewController <
5095 UITableViewDataSource,
5098 _transient Database *database_;
5101 NSMutableArray *files_;
5105 - (id) initWithDatabase:(Database *)database;
5106 - (void) setPackage:(Package *)package;
5110 @implementation FileTable
5113 if (package_ != nil)
5122 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5123 return files_ == nil ? 0 : [files_ count];
5126 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5130 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5131 static NSString *reuseIdentifier = @"Cell";
5133 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5135 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5136 [cell setFont:[UIFont systemFontOfSize:16]];
5138 [cell setText:[files_ objectAtIndex:indexPath.row]];
5139 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5144 - (id) initWithDatabase:(Database *)database {
5145 if ((self = [super init]) != nil) {
5146 database_ = database;
5148 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5150 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5152 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5153 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5154 [list_ setRowHeight:24.0f];
5155 [[self view] addSubview:list_];
5157 [list_ setDataSource:self];
5158 [list_ setDelegate:self];
5162 - (void) setPackage:(Package *)package {
5163 if (package_ != nil) {
5164 [package_ autorelease];
5173 [files_ removeAllObjects];
5175 if (package != nil) {
5176 package_ = [package retain];
5177 name_ = [[package id] retain];
5179 if (NSArray *files = [package files])
5180 [files_ addObjectsFromArray:files];
5182 if ([files_ count] != 0) {
5183 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5184 [files_ removeObjectAtIndex:0];
5185 [files_ sortUsingSelector:@selector(compareByPath:)];
5187 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5188 [stack addObject:@"/"];
5190 for (int i(0), e([files_ count]); i != e; ++i) {
5191 NSString *file = [files_ objectAtIndex:i];
5192 while (![file hasPrefix:[stack lastObject]])
5193 [stack removeLastObject];
5194 NSString *directory = [stack lastObject];
5195 [stack addObject:[file stringByAppendingString:@"/"]];
5196 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5197 ([stack count] - 2) * 3, "",
5198 [file substringFromIndex:[directory length]]
5207 - (void) reloadData {
5208 [self setPackage:[database_ packageWithName:name_]];
5213 /* Package Controller {{{ */
5214 @interface PackageController : CYBrowserController <
5215 UIActionSheetDelegate
5217 _transient Database *database_;
5221 NSMutableArray *buttons_;
5222 UIBarButtonItem *button_;
5225 - (id) initWithDatabase:(Database *)database;
5226 - (void) setPackage:(Package *)package;
5230 @implementation PackageController
5233 if (package_ != nil)
5247 if ([self retainCount] == 1)
5248 [delegate_ setPackageController:self];
5252 /* XXX: this is not safe at all... localization of /fail/ */
5253 - (void) _clickButtonWithName:(NSString *)name {
5254 if ([name isEqualToString:UCLocalize("CLEAR")])
5255 [delegate_ clearPackage:package_];
5256 else if ([name isEqualToString:UCLocalize("INSTALL")])
5257 [delegate_ installPackage:package_];
5258 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5259 [delegate_ installPackage:package_];
5260 else if ([name isEqualToString:UCLocalize("REMOVE")])
5261 [delegate_ removePackage:package_];
5262 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5263 [delegate_ installPackage:package_];
5264 else _assert(false);
5267 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5268 NSString *context([sheet context]);
5270 if ([context isEqualToString:@"modify"]) {
5271 if (button != [sheet cancelButtonIndex]) {
5272 NSString *buttonName = [buttons_ objectAtIndex:button];
5273 [self _clickButtonWithName:buttonName];
5276 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5280 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5281 [super webView:view didClearWindowObject:window forFrame:frame];
5282 [window setValue:package_ forKey:@"package"];
5285 - (bool) _allowJavaScriptPanel {
5290 - (void) _customButtonClicked {
5291 int count([buttons_ count]);
5296 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5298 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5299 [buttons addObjectsFromArray:buttons_];
5301 UIActionSheet *sheet = [[[UIActionSheet alloc]
5304 cancelButtonTitle:nil
5305 destructiveButtonTitle:nil
5306 otherButtonTitles:nil
5309 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5311 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5312 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5314 [sheet setContext:@"modify"];
5316 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5320 // We don't want to allow non-commercial packages to do custom things to the install button,
5321 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5322 - (void) customButtonClicked {
5324 [super customButtonClicked];
5326 [self _customButtonClicked];
5329 - (void) reloadButtonClicked {
5330 // Don't reload a package view by clicking the button.
5333 - (void) applyLoadingTitle {
5334 // Don't show "Loading" as the title. Ever.
5337 - (UIBarButtonItem *) rightButton {
5342 - (id) initWithDatabase:(Database *)database {
5343 if ((self = [super init]) != nil) {
5344 database_ = database;
5345 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5346 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5350 - (void) setPackage:(Package *)package {
5351 if (package_ != nil) {
5352 [package_ autorelease];
5361 [buttons_ removeAllObjects];
5363 if (package != nil) {
5366 package_ = [package retain];
5367 name_ = [[package id] retain];
5368 commercial_ = [package isCommercial];
5370 if ([package_ mode] != nil)
5371 [buttons_ addObject:UCLocalize("CLEAR")];
5372 if ([package_ source] == nil);
5373 else if ([package_ upgradableAndEssential:NO])
5374 [buttons_ addObject:UCLocalize("UPGRADE")];
5375 else if ([package_ uninstalled])
5376 [buttons_ addObject:UCLocalize("INSTALL")];
5378 [buttons_ addObject:UCLocalize("REINSTALL")];
5379 if (![package_ uninstalled])
5380 [buttons_ addObject:UCLocalize("REMOVE")];
5387 switch ([buttons_ count]) {
5388 case 0: title = nil; break;
5389 case 1: title = [buttons_ objectAtIndex:0]; break;
5390 default: title = UCLocalize("MODIFY"); break;
5393 button_ = [[UIBarButtonItem alloc]
5395 style:UIBarButtonItemStylePlain
5397 action:@selector(customButtonClicked)
5403 - (bool) isLoading {
5404 return commercial_ ? [super isLoading] : false;
5407 - (void) reloadData {
5408 [self setPackage:[database_ packageWithName:name_]];
5413 /* Package Table {{{ */
5414 @interface PackageTable : UIView <
5415 UITableViewDataSource,
5418 _transient Database *database_;
5419 NSMutableArray *packages_;
5420 NSMutableArray *sections_;
5422 NSMutableArray *index_;
5423 NSMutableDictionary *indices_;
5424 // XXX: this target_ seems to be delegate_. :(
5425 _transient id target_;
5427 // XXX: why do we even have this delegate_?
5428 _transient id delegate_;
5431 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5433 - (void) setDelegate:(id)delegate;
5435 - (void) reloadData;
5436 - (void) resetCursor;
5438 - (UITableView *) list;
5440 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5442 - (void) deselectWithAnimation:(BOOL)animated;
5446 @implementation PackageTable
5449 [packages_ release];
5450 [sections_ release];
5458 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5459 NSInteger count([sections_ count]);
5460 return count == 0 ? 1 : count;
5463 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5464 if ([sections_ count] == 0)
5466 return [[sections_ objectAtIndex:section] name];
5469 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5470 if ([sections_ count] == 0)
5472 return [[sections_ objectAtIndex:section] count];
5475 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5476 Section *section([sections_ objectAtIndex:[path section]]);
5477 NSInteger row([path row]);
5478 Package *package([packages_ objectAtIndex:([section row] + row)]);
5482 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5483 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5485 cell = [[[PackageCell alloc] init] autorelease];
5486 [cell setPackage:[self packageAtIndexPath:path]];
5490 - (void) deselectWithAnimation:(BOOL)animated {
5491 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5494 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5495 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5498 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5499 Package *package([self packageAtIndexPath:path]);
5500 package = [database_ packageWithName:[package id]];
5501 [target_ performSelector:action_ withObject:package];
5505 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5506 return [packages_ count] > 20 ? index_ : nil;
5509 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5513 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5514 if ((self = [super initWithFrame:frame]) != nil) {
5515 database_ = database;
5520 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5521 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5523 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5524 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5526 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5527 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5528 [list_ setRowHeight:73.0f];
5529 [self addSubview:list_];
5531 [list_ setDataSource:self];
5532 [list_ setDelegate:self];
5536 - (void) setDelegate:(id)delegate {
5537 delegate_ = delegate;
5540 - (bool) hasPackage:(Package *)package {
5544 - (void) reloadData {
5545 NSArray *packages = [database_ packages];
5547 [packages_ removeAllObjects];
5548 [sections_ removeAllObjects];
5550 _profile(PackageTable$reloadData$Filter)
5551 for (Package *package in packages)
5552 if ([self hasPackage:package])
5553 [packages_ addObject:package];
5556 [index_ removeAllObjects];
5557 [indices_ removeAllObjects];
5559 Section *section = nil;
5561 _profile(PackageTable$reloadData$Section)
5562 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5566 _profile(PackageTable$reloadData$Section$Package)
5567 package = [packages_ objectAtIndex:offset];
5568 index = [package index];
5571 if (section == nil || [section index] != index) {
5572 _profile(PackageTable$reloadData$Section$Allocate)
5573 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5576 [index_ addObject:[section name]];
5577 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5579 _profile(PackageTable$reloadData$Section$Add)
5580 [sections_ addObject:section];
5584 [section addToCount];
5588 _profile(PackageTable$reloadData$List)
5593 - (void) resetCursor {
5594 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5597 - (UITableView *) list {
5601 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5602 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5607 /* Filtered Package Table {{{ */
5608 @interface FilteredPackageTable : PackageTable {
5614 - (void) setObject:(id)object;
5615 - (void) setObject:(id)object forFilter:(SEL)filter;
5617 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5621 @implementation FilteredPackageTable
5629 - (void) setFilter:(SEL)filter {
5632 /* XXX: this is an unsafe optimization of doomy hell */
5633 Method method(class_getInstanceMethod([Package class], filter));
5634 _assert(method != NULL);
5635 imp_ = method_getImplementation(method);
5636 _assert(imp_ != NULL);
5639 - (void) setObject:(id)object {
5645 object_ = [object retain];
5648 - (void) setObject:(id)object forFilter:(SEL)filter {
5649 [self setFilter:filter];
5650 [self setObject:object];
5653 - (bool) hasPackage:(Package *)package {
5654 _profile(FilteredPackageTable$hasPackage)
5655 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5659 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5660 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5661 [self setFilter:filter];
5662 object_ = [object retain];
5670 /* Filtered Package Controller {{{ */
5671 @interface FilteredPackageController : CYViewController {
5672 _transient Database *database_;
5673 FilteredPackageTable *packages_;
5677 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5681 @implementation FilteredPackageController
5684 [packages_ release];
5690 - (void) viewDidAppear:(BOOL)animated {
5691 [super viewDidAppear:animated];
5692 [packages_ deselectWithAnimation:animated];
5695 - (void) didSelectPackage:(Package *)package {
5696 PackageController *view([delegate_ packageController]);
5697 [view setPackage:package];
5698 [view setDelegate:delegate_];
5699 [[self navigationController] pushViewController:view animated:YES];
5702 - (NSString *) title { return title_; }
5704 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5705 if ((self = [super init]) != nil) {
5706 database_ = database;
5707 title_ = [title copy];
5708 [[self navigationItem] setTitle:title_];
5710 packages_ = [[FilteredPackageTable alloc]
5711 initWithFrame:[[self view] bounds]
5714 action:@selector(didSelectPackage:)
5719 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5720 [[self view] addSubview:packages_];
5724 - (void) reloadData {
5725 [packages_ reloadData];
5728 - (void) setDelegate:(id)delegate {
5729 [super setDelegate:delegate];
5730 [packages_ setDelegate:delegate];
5737 /* Add Source Controller {{{ */
5738 @interface AddSourceController : CYViewController {
5739 _transient Database *database_;
5742 - (id) initWithDatabase:(Database *)database;
5746 @implementation AddSourceController
5748 - (id) initWithDatabase:(Database *)database {
5749 if ((self = [super init]) != nil) {
5750 database_ = database;
5756 /* Source Cell {{{ */
5757 @interface SourceCell : CYTableViewCell <
5762 NSString *description_;
5766 - (void) setSource:(Source *)source;
5770 @implementation SourceCell
5772 - (void) clearSource {
5775 [description_ release];
5784 - (void) setSource:(Source *)source {
5788 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5790 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5791 icon_ = [icon_ retain];
5793 origin_ = [[source name] retain];
5794 label_ = [[source uri] retain];
5795 description_ = [[source description] retain];
5797 [content_ setNeedsDisplay];
5805 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5806 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5807 UIView *content([self contentView]);
5808 CGRect bounds([content bounds]);
5810 content_ = [[ContentView alloc] initWithFrame:bounds];
5811 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5812 [content_ setBackgroundColor:[UIColor whiteColor]];
5813 [content addSubview:content_];
5815 [content_ setDelegate:self];
5816 [content_ setOpaque:YES];
5820 - (void) drawContentRect:(CGRect)rect {
5821 bool highlighted(highlighted_);
5822 float width(rect.size.width);
5825 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5832 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5836 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5840 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5845 /* Source Table {{{ */
5846 @interface SourceTable : CYViewController <
5847 UITableViewDataSource,
5850 _transient Database *database_;
5852 NSMutableArray *sources_;
5856 UIProgressHUD *hud_;
5859 //NSURLConnection *installer_;
5860 NSURLConnection *trivial_;
5861 NSURLConnection *trivial_bz2_;
5862 NSURLConnection *trivial_gz_;
5863 //NSURLConnection *automatic_;
5868 - (id) initWithDatabase:(Database *)database;
5870 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5874 @implementation SourceTable
5876 - (void) _releaseConnection:(NSURLConnection *)connection {
5877 if (connection != nil) {
5878 [connection cancel];
5879 //[connection setDelegate:nil];
5880 [connection release];
5892 //[self _releaseConnection:installer_];
5893 [self _releaseConnection:trivial_];
5894 [self _releaseConnection:trivial_gz_];
5895 [self _releaseConnection:trivial_bz2_];
5896 //[self _releaseConnection:automatic_];
5903 - (void) viewDidAppear:(BOOL)animated {
5904 [super viewDidAppear:animated];
5905 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5908 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5909 return offset_ == 0 ? 1 : 2;
5912 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5913 switch (section + (offset_ == 0 ? 1 : 0)) {
5914 case 0: return UCLocalize("ENTERED_BY_USER");
5915 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5921 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5922 int count = [sources_ count];
5924 case 0: return (offset_ == 0 ? count : offset_);
5925 case 1: return count - offset_;
5931 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5933 switch (indexPath.section) {
5934 case 0: idx = indexPath.row; break;
5935 case 1: idx = indexPath.row + offset_; break;
5939 return [sources_ objectAtIndex:idx];
5942 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5943 Source *source = [self sourceAtIndexPath:indexPath];
5944 return [source description] == nil ? 56 : 73;
5947 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5948 static NSString *cellIdentifier = @"SourceCell";
5950 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5951 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5952 [cell setSource:[self sourceAtIndexPath:indexPath]];
5957 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5958 return UITableViewCellAccessoryDisclosureIndicator;
5961 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5962 Source *source = [self sourceAtIndexPath:indexPath];
5964 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5965 initWithDatabase:database_
5966 title:[source label]
5967 filter:@selector(isVisibleInSource:)
5971 [packages setDelegate:delegate_];
5973 [[self navigationController] pushViewController:packages animated:YES];
5976 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5977 Source *source = [self sourceAtIndexPath:indexPath];
5978 return [source record] != nil;
5981 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5982 Source *source = [self sourceAtIndexPath:indexPath];
5983 [Sources_ removeObjectForKey:[source key]];
5984 [delegate_ syncData];
5988 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5991 @"./", @"Distribution",
5992 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5994 [delegate_ syncData];
5997 - (NSString *) getWarning {
5998 NSString *href(href_);
5999 NSRange colon([href rangeOfString:@"://"]);
6000 if (colon.location != NSNotFound)
6001 href = [href substringFromIndex:(colon.location + 3)];
6002 href = [href stringByAddingPercentEscapes];
6003 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
6004 href = [href stringByCachingURLWithCurrentCDN];
6006 NSURL *url([NSURL URLWithString:href]);
6008 NSStringEncoding encoding;
6009 NSError *error(nil);
6011 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
6012 return [warning length] == 0 ? nil : warning;
6016 - (void) _endConnection:(NSURLConnection *)connection {
6017 // XXX: the memory management in this method is horribly awkward
6019 NSURLConnection **field = NULL;
6020 if (connection == trivial_)
6022 else if (connection == trivial_bz2_)
6023 field = &trivial_bz2_;
6024 else if (connection == trivial_gz_)
6025 field = &trivial_gz_;
6026 _assert(field != NULL);
6027 [connection release];
6032 trivial_bz2_ == nil &&
6038 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6041 UIAlertView *alert = [[[UIAlertView alloc]
6042 initWithTitle:UCLocalize("SOURCE_WARNING")
6045 cancelButtonTitle:UCLocalize("CANCEL")
6046 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6049 [alert setContext:@"warning"];
6050 [alert setNumberOfRows:1];
6054 } else if (error_ != nil) {
6055 UIAlertView *alert = [[[UIAlertView alloc]
6056 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6057 message:[error_ localizedDescription]
6059 cancelButtonTitle:UCLocalize("OK")
6060 otherButtonTitles:nil
6063 [alert setContext:@"urlerror"];
6066 UIAlertView *alert = [[[UIAlertView alloc]
6067 initWithTitle:UCLocalize("NOT_REPOSITORY")
6068 message:UCLocalize("NOT_REPOSITORY_EX")
6070 cancelButtonTitle:UCLocalize("OK")
6071 otherButtonTitles:nil
6074 [alert setContext:@"trivial"];
6078 [delegate_ setStatusBarShowsProgress:NO];
6079 [delegate_ removeProgressHUD:hud_];
6089 if (error_ != nil) {
6096 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6097 switch ([response statusCode]) {
6103 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6104 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6106 error_ = [error retain];
6107 [self _endConnection:connection];
6110 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6111 [self _endConnection:connection];
6114 - (NSString *) title { return UCLocalize("SOURCES"); }
6116 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6117 NSMutableURLRequest *request = [NSMutableURLRequest
6118 requestWithURL:[NSURL URLWithString:href]
6119 cachePolicy:NSURLRequestUseProtocolCachePolicy
6120 timeoutInterval:120.0
6123 [request setHTTPMethod:method];
6125 if (Machine_ != NULL)
6126 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6127 if (UniqueID_ != nil)
6128 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6130 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6132 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6135 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6136 NSString *context([alert context]);
6138 if ([context isEqualToString:@"source"]) {
6141 NSString *href = [[alert textField] text];
6143 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6145 if (![href hasSuffix:@"/"])
6146 href_ = [href stringByAppendingString:@"/"];
6149 href_ = [href_ retain];
6151 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6152 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6153 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6154 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6158 // XXX: this is stupid
6159 hud_ = [[delegate_ addProgressHUD] retain];
6160 [hud_ setText:UCLocalize("VERIFYING_URL")];
6169 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6170 } else if ([context isEqualToString:@"trivial"])
6171 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6172 else if ([context isEqualToString:@"urlerror"])
6173 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6174 else if ([context isEqualToString:@"warning"]) {
6189 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6193 - (id) initWithDatabase:(Database *)database {
6194 if ((self = [super init]) != nil) {
6195 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6196 [self updateButtonsForEditingStatus:NO animated:NO];
6198 database_ = database;
6199 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6201 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6202 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6203 [[self view] addSubview:list_];
6205 [list_ setDataSource:self];
6206 [list_ setDelegate:self];
6212 - (void) reloadData {
6214 if (!list.ReadMainList())
6217 [sources_ removeAllObjects];
6218 [sources_ addObjectsFromArray:[database_ sources]];
6220 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6223 int count([sources_ count]);
6225 for (int i = 0; i != count; i++) {
6226 if ([[sources_ objectAtIndex:i] record] == nil)
6231 [list_ setEditing:NO];
6232 [self updateButtonsForEditingStatus:NO animated:NO];
6236 - (void) addButtonClicked {
6237 /*[book_ pushPage:[[[AddSourceController alloc]
6242 UIAlertView *alert = [[[UIAlertView alloc]
6243 initWithTitle:UCLocalize("ENTER_APT_URL")
6246 cancelButtonTitle:UCLocalize("CANCEL")
6247 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6250 [alert setContext:@"source"];
6251 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6253 [alert setNumberOfRows:1];
6254 [alert addTextFieldWithValue:@"http://" label:@""];
6256 UITextInputTraits *traits = [[alert textField] textInputTraits];
6257 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6258 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6259 [traits setKeyboardType:UIKeyboardTypeURL];
6260 // XXX: UIReturnKeyDone
6261 [traits setReturnKeyType:UIReturnKeyNext];
6266 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6267 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6268 initWithTitle:UCLocalize("ADD")
6269 style:UIBarButtonItemStylePlain
6271 action:@selector(addButtonClicked)
6272 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6274 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6275 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6276 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6278 action:@selector(editButtonClicked)
6279 ] autorelease] animated:animated];
6281 if (IsWildcat_ && !editing)
6282 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6283 initWithTitle:UCLocalize("SETTINGS")
6284 style:UIBarButtonItemStylePlain
6286 action:@selector(settingsButtonClicked)
6290 - (void) settingsButtonClicked {
6291 [delegate_ showSettings];
6294 - (void) editButtonClicked {
6295 [list_ setEditing:![list_ isEditing] animated:YES];
6297 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6303 /* Installed Controller {{{ */
6304 @interface InstalledController : FilteredPackageController {
6308 - (id) initWithDatabase:(Database *)database;
6310 - (void) updateRoleButton;
6311 - (void) queueStatusDidChange;
6315 @implementation InstalledController
6321 - (NSString *) title { return UCLocalize("INSTALLED"); }
6323 - (id) initWithDatabase:(Database *)database {
6324 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6325 [self updateRoleButton];
6326 [self queueStatusDidChange];
6331 - (void) queueButtonClicked {
6336 - (void) queueStatusDidChange {
6340 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6341 initWithTitle:UCLocalize("QUEUE")
6342 style:UIBarButtonItemStyleDone
6344 action:@selector(queueButtonClicked)
6347 [[self navigationItem] setLeftBarButtonItem:nil];
6353 - (void) reloadData {
6354 [packages_ reloadData];
6357 - (void) updateRoleButton {
6358 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6359 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6360 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6361 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6363 action:@selector(roleButtonClicked)
6367 - (void) roleButtonClicked {
6368 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6369 [packages_ reloadData];
6372 [self updateRoleButton];
6375 - (void) setDelegate:(id)delegate {
6376 [super setDelegate:delegate];
6377 [packages_ setDelegate:delegate];
6383 /* Home Controller {{{ */
6384 @interface HomeController : CYBrowserController {
6389 @implementation HomeController
6391 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6392 [super _setMoreHeaders:request];
6395 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6396 if (UniqueID_ != nil)
6397 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6399 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6402 - (void) aboutButtonClicked {
6403 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6405 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6406 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6407 [alert setCancelButtonIndex:0];
6410 @"Copyright (C) 2008-2010\n"
6411 "Jay Freeman (saurik)\n"
6412 "saurik@saurik.com\n"
6413 "http://www.saurik.com/"
6419 - (void) viewWillAppear:(BOOL)animated {
6420 [super viewWillAppear:animated];
6421 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6424 - (void) viewWillDisappear:(BOOL)animated {
6425 [super viewWillDisappear:animated];
6426 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6430 if ((self = [super init]) != nil) {
6431 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6432 initWithTitle:UCLocalize("ABOUT")
6433 style:UIBarButtonItemStylePlain
6435 action:@selector(aboutButtonClicked)
6442 /* Manage Controller {{{ */
6443 @interface ManageController : CYBrowserController {
6446 - (void) queueStatusDidChange;
6449 @implementation ManageController
6452 if ((self = [super init]) != nil) {
6453 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6455 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6456 initWithTitle:UCLocalize("SETTINGS")
6457 style:UIBarButtonItemStylePlain
6459 action:@selector(settingsButtonClicked)
6462 [self queueStatusDidChange];
6466 - (void) settingsButtonClicked {
6467 [delegate_ showSettings];
6471 - (void) queueButtonClicked {
6475 - (void) applyLoadingTitle {
6476 // No "Loading" title.
6479 - (void) applyRightButton {
6484 - (void) queueStatusDidChange {
6486 if (!IsWildcat_ && Queuing_) {
6487 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6488 initWithTitle:UCLocalize("QUEUE")
6489 style:UIBarButtonItemStyleDone
6491 action:@selector(queueButtonClicked)
6494 [[self navigationItem] setRightBarButtonItem:nil];
6499 - (bool) isLoading {
6506 /* Refresh Bar {{{ */
6507 @interface RefreshBar : UINavigationBar {
6508 UIProgressIndicator *indicator_;
6509 UITextLabel *prompt_;
6510 UIProgressBar *progress_;
6511 UINavigationButton *cancel_;
6516 @implementation RefreshBar
6519 [indicator_ release];
6521 [progress_ release];
6526 - (void) positionViews {
6527 CGRect frame = [cancel_ frame];
6528 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6529 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6530 [cancel_ setFrame:frame];
6532 CGSize prgsize = {75, 100};
6534 [self frame].size.width - prgsize.width - 10,
6535 ([self frame].size.height - prgsize.height) / 2
6537 [progress_ setFrame:prgrect];
6539 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6540 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6541 CGRect indrect = {{indoffset, indoffset}, indsize};
6542 [indicator_ setFrame:indrect];
6544 CGSize prmsize = {215, indsize.height + 4};
6546 indoffset * 2 + indsize.width,
6547 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6549 [prompt_ setFrame:prmrect];
6552 - (void)setFrame:(CGRect)frame {
6553 [super setFrame:frame];
6555 [self positionViews];
6558 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6559 if ((self = [super initWithFrame:frame])) {
6560 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6562 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6563 [self setBarStyle:UIBarStyleBlack];
6565 UIBarStyle barstyle([self _barStyle:NO]);
6566 bool ugly(barstyle == UIBarStyleDefault);
6568 UIProgressIndicatorStyle style = ugly ?
6569 UIProgressIndicatorStyleMediumBrown :
6570 UIProgressIndicatorStyleMediumWhite;
6572 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6573 [indicator_ setStyle:style];
6574 [indicator_ startAnimation];
6575 [self addSubview:indicator_];
6577 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6578 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6579 [prompt_ setBackgroundColor:[UIColor clearColor]];
6580 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6581 [self addSubview:prompt_];
6583 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6584 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6585 [progress_ setStyle:0];
6586 [self addSubview:progress_];
6588 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6589 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6590 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6591 [cancel_ setBarStyle:barstyle];
6593 [self positionViews];
6598 [cancel_ removeFromSuperview];
6602 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6603 [progress_ setProgress:0];
6604 [self addSubview:cancel_];
6608 [cancel_ removeFromSuperview];
6611 - (void) setPrompt:(NSString *)prompt {
6612 [prompt_ setText:prompt];
6615 - (void) setProgress:(float)progress {
6616 [progress_ setProgress:progress];
6622 @class CYNavigationController;
6624 /* Cydia Tab Bar Controller {{{ */
6625 @interface CYTabBarController : UITabBarController <
6628 _transient Database *database_;
6629 RefreshBar *refreshbar_;
6633 // XXX: ok, "updatedelegate_"?...
6634 _transient NSObject<CydiaDelegate> *updatedelegate_;
6639 - (void) dropBar:(BOOL)animated;
6640 - (void) beginUpdate;
6641 - (void) raiseBar:(BOOL)animated;
6646 @implementation CYTabBarController
6648 /* XXX: some logic should probably go here related to
6649 freeing the view controllers on tab change */
6651 - (void) reloadData {
6652 size_t count([[self viewControllers] count]);
6653 for (size_t i(0); i != count; ++i) {
6654 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6659 - (id) initWithDatabase:(Database *)database {
6660 if ((self = [super init]) != nil) {
6661 database_ = database;
6663 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6664 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6666 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6670 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6671 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
6674 - (void) setUpdate:(NSDate *)date {
6678 - (void) beginUpdate {
6680 [refreshbar_ start];
6685 detachNewThreadSelector:@selector(performUpdate)
6691 - (void) performUpdate { _pooled
6693 status.setDelegate(self);
6694 [database_ updateWithStatus:status];
6697 performSelectorOnMainThread:@selector(completeUpdate)
6703 - (void) completeUpdate {
6708 [self raiseBar:YES];
6710 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6713 - (void) cancelUpdate {
6715 [self raiseBar:YES];
6717 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
6720 - (void) cancelPressed {
6721 [self cancelUpdate];
6728 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6729 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6732 - (void) startProgress {
6735 - (void) setProgressTitle:(NSString *)title {
6737 performSelectorOnMainThread:@selector(_setProgressTitle:)
6743 - (bool) isCancelling:(size_t)received {
6747 - (void) setProgressPercent:(float)percent {
6749 performSelectorOnMainThread:@selector(_setProgressPercent:)
6750 withObject:[NSNumber numberWithFloat:percent]
6755 - (void) addProgressOutput:(NSString *)output {
6757 performSelectorOnMainThread:@selector(_addProgressOutput:)
6763 - (void) _setProgressTitle:(NSString *)title {
6764 [refreshbar_ setPrompt:title];
6767 - (void) _setProgressPercent:(NSNumber *)percent {
6768 [refreshbar_ setProgress:[percent floatValue]];
6771 - (void) _addProgressOutput:(NSString *)output {
6774 - (void) setUpdateDelegate:(id)delegate {
6775 updatedelegate_ = delegate;
6778 - (CGFloat) statusBarHeight {
6779 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6780 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6782 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6786 - (UIView *) transitionView {
6787 if ([self respondsToSelector:@selector(_transitionView)])
6788 return [self _transitionView];
6790 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6793 - (void) dropBar:(BOOL)animated {
6798 UIView *transition([self transitionView]);
6799 [[self view] addSubview:refreshbar_];
6801 CGRect barframe([refreshbar_ frame]);
6803 if (false) // XXX: _UIApplicationLinkedOnOrAfter(4)
6804 barframe.origin.y = [self statusBarHeight];
6806 barframe.origin.y = 0;
6808 [refreshbar_ setFrame:barframe];
6811 [UIView beginAnimations:nil context:NULL];
6813 CGRect viewframe = [transition frame];
6814 viewframe.origin.y += barframe.size.height;
6815 viewframe.size.height -= barframe.size.height;
6816 [transition setFrame:viewframe];
6819 [UIView commitAnimations];
6821 // Ensure bar has the proper width for our view, it might have changed
6822 barframe.size.width = viewframe.size.width;
6823 [refreshbar_ setFrame:barframe];
6825 // XXX: fix Apple's layout bug
6826 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6829 - (void) raiseBar:(BOOL)animated {
6834 UIView *transition([self transitionView]);
6835 [refreshbar_ removeFromSuperview];
6837 CGRect barframe([refreshbar_ frame]);
6840 [UIView beginAnimations:nil context:NULL];
6842 CGRect viewframe = [transition frame];
6843 viewframe.origin.y -= barframe.size.height;
6844 viewframe.size.height += barframe.size.height;
6845 [transition setFrame:viewframe];
6848 [UIView commitAnimations];
6850 // XXX: fix Apple's layout bug
6851 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6855 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6856 // XXX: fix Apple's layout bug
6857 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6861 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6862 bool dropped(dropped_);
6867 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6872 // XXX: fix Apple's layout bug
6873 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6876 - (void) statusBarFrameChanged:(NSNotification *)notification {
6884 [refreshbar_ release];
6885 [[NSNotificationCenter defaultCenter] removeObserver:self];
6892 /* Cydia Navigation Controller {{{ */
6893 @interface CYNavigationController : UINavigationController {
6894 _transient Database *database_;
6895 _transient id<UINavigationControllerDelegate> delegate_;
6898 - (id) initWithDatabase:(Database *)database;
6899 - (void) reloadData;
6904 @implementation CYNavigationController
6906 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6907 // Inherit autorotation settings for modal parents.
6908 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6909 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6911 return [super shouldAutorotateToInterfaceOrientation:orientation];
6919 - (void) reloadData {
6920 size_t count([[self viewControllers] count]);
6921 for (size_t i(0); i != count; ++i) {
6922 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6927 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6928 delegate_ = delegate;
6931 - (id) initWithDatabase:(Database *)database {
6932 if ((self = [super init]) != nil) {
6933 database_ = database;
6939 /* Cydia:// Protocol {{{ */
6940 @interface CydiaURLProtocol : NSURLProtocol {
6945 @implementation CydiaURLProtocol
6947 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6948 NSURL *url([request URL]);
6951 NSString *scheme([[url scheme] lowercaseString]);
6952 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6957 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6961 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6962 id<NSURLProtocolClient> client([self client]);
6964 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6966 NSData *data(UIImagePNGRepresentation(icon));
6968 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6969 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6970 [client URLProtocol:self didLoadData:data];
6971 [client URLProtocolDidFinishLoading:self];
6975 - (void) startLoading {
6976 id<NSURLProtocolClient> client([self client]);
6977 NSURLRequest *request([self request]);
6979 NSURL *url([request URL]);
6980 NSString *href([url absoluteString]);
6982 NSString *path([href substringFromIndex:8]);
6983 NSRange slash([path rangeOfString:@"/"]);
6986 if (slash.location == NSNotFound) {
6990 command = [path substringToIndex:slash.location];
6991 path = [path substringFromIndex:(slash.location + 1)];
6994 Database *database([Database sharedInstance]);
6996 if ([command isEqualToString:@"package-icon"]) {
6999 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7000 Package *package([database packageWithName:path]);
7003 UIImage *icon([package icon]);
7004 [self _returnPNGWithImage:icon forRequest:request];
7005 } else if ([command isEqualToString:@"source-icon"]) {
7008 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7009 NSString *source(Simplify(path));
7010 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7012 icon = [UIImage applicationImageNamed:@"unknown.png"];
7013 [self _returnPNGWithImage:icon forRequest:request];
7014 } else if ([command isEqualToString:@"uikit-image"]) {
7017 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7018 UIImage *icon(_UIImageWithName(path));
7019 [self _returnPNGWithImage:icon forRequest:request];
7020 } else if ([command isEqualToString:@"section-icon"]) {
7023 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7024 NSString *section(Simplify(path));
7025 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7027 icon = [UIImage applicationImageNamed:@"unknown.png"];
7028 [self _returnPNGWithImage:icon forRequest:request];
7030 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7034 - (void) stopLoading {
7040 /* Sections Controller {{{ */
7041 @interface SectionsController : CYViewController <
7042 UITableViewDataSource,
7045 _transient Database *database_;
7046 NSMutableArray *sections_;
7047 NSMutableArray *filtered_;
7053 - (id) initWithDatabase:(Database *)database;
7054 - (void) reloadData;
7057 - (void) editButtonClicked;
7061 @implementation SectionsController
7064 [list_ setDataSource:nil];
7065 [list_ setDelegate:nil];
7067 [sections_ release];
7068 [filtered_ release];
7070 [accessory_ release];
7074 - (void) viewDidAppear:(BOOL)animated {
7075 [super viewDidAppear:animated];
7076 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7079 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7080 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7084 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7085 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7088 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7092 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7093 static NSString *reuseIdentifier = @"SectionCell";
7095 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7097 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7099 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7104 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7108 Section *section = [self sectionAtIndexPath:indexPath];
7109 NSString *name = [section name];
7112 if ([indexPath row] == 0) {
7115 title = UCLocalize("ALL_PACKAGES");
7118 name = [NSString stringWithString:name];
7119 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7122 title = UCLocalize("NO_SECTION");
7126 FilteredPackageController *table = [[[FilteredPackageController alloc]
7127 initWithDatabase:database_
7129 filter:@selector(isVisibleInSection:)
7133 [table setDelegate:delegate_];
7135 [[self navigationController] pushViewController:table animated:YES];
7138 - (NSString *) title { return UCLocalize("SECTIONS"); }
7140 - (id) initWithDatabase:(Database *)database {
7141 if ((self = [super init]) != nil) {
7142 database_ = database;
7144 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7146 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7147 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7149 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7150 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7151 [list_ setRowHeight:45.0f];
7152 [[self view] addSubview:list_];
7154 [list_ setDataSource:self];
7155 [list_ setDelegate:self];
7161 - (void) reloadData {
7162 NSArray *packages = [database_ packages];
7164 [sections_ removeAllObjects];
7165 [filtered_ removeAllObjects];
7167 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7170 for (Package *package in packages) {
7171 NSString *name([package section]);
7172 NSString *key(name == nil ? @"" : name);
7176 _profile(SectionsView$reloadData$Section)
7177 section = [sections objectForKey:key];
7178 if (section == nil) {
7179 _profile(SectionsView$reloadData$Section$Allocate)
7180 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
7181 [sections setObject:section forKey:key];
7186 [section addToCount];
7188 _profile(SectionsView$reloadData$Filter)
7189 if (![package valid] || ![package visible])
7197 [sections_ addObjectsFromArray:[sections allValues]];
7199 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7201 for (Section *section in sections_) {
7202 size_t count([section row]);
7206 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7207 [section setCount:count];
7208 [filtered_ addObject:section];
7211 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7212 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
7213 style:UIBarButtonItemStylePlain
7215 action:@selector(editButtonClicked)
7216 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7222 - (void) resetView {
7224 [self editButtonClicked];
7227 - (void) editButtonClicked {
7228 if ((editing_ = !editing_))
7231 [delegate_ updateData];
7233 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7234 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
7235 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
7238 - (UIView *) accessoryView {
7244 /* Changes Controller {{{ */
7245 @interface ChangesController : CYViewController <
7246 UITableViewDataSource,
7249 _transient Database *database_;
7250 CFMutableArrayRef packages_;
7251 NSMutableArray *sections_;
7254 BOOL hasSentFirstLoad_;
7257 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
7258 - (void) reloadData;
7262 @implementation ChangesController
7265 [list_ setDelegate:nil];
7266 [list_ setDataSource:nil];
7268 CFRelease(packages_);
7270 [sections_ release];
7275 - (void) viewDidAppear:(BOOL)animated {
7276 [super viewDidAppear:animated];
7277 if (!hasSentFirstLoad_) {
7278 hasSentFirstLoad_ = YES;
7279 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7281 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7285 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7286 NSInteger count([sections_ count]);
7287 return count == 0 ? 1 : count;
7290 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7291 if ([sections_ count] == 0)
7293 return [[sections_ objectAtIndex:section] name];
7296 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7297 if ([sections_ count] == 0)
7299 return [[sections_ objectAtIndex:section] count];
7302 - (Package *) packageAtIndex:(NSUInteger)index {
7303 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7306 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7307 Section *section([sections_ objectAtIndex:[path section]]);
7308 NSInteger row([path row]);
7309 return [self packageAtIndex:([section row] + row)];
7312 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7313 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7315 cell = [[[PackageCell alloc] init] autorelease];
7316 [cell setPackage:[self packageAtIndexPath:path]];
7320 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7321 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7324 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7325 Package *package([self packageAtIndexPath:path]);
7326 PackageController *view([delegate_ packageController]);
7327 [view setDelegate:delegate_];
7328 [view setPackage:package];
7329 [[self navigationController] pushViewController:view animated:YES];
7333 - (void) refreshButtonClicked {
7334 [delegate_ beginUpdate];
7335 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7338 - (void) upgradeButtonClicked {
7339 [delegate_ distUpgrade];
7342 - (NSString *) title { return UCLocalize("CHANGES"); }
7344 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7345 if ((self = [super init]) != nil) {
7346 database_ = database;
7347 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7349 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7351 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7353 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7354 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7355 [list_ setRowHeight:73.0f];
7356 [[self view] addSubview:list_];
7358 [list_ setDataSource:self];
7359 [list_ setDelegate:self];
7361 delegate_ = delegate;
7365 - (void) _reloadPackages:(NSArray *)packages {
7367 for (Package *package in packages)
7368 if ([package upgradableAndEssential:YES] || [package visible])
7369 CFArrayAppendValue(packages_, package);
7372 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7376 - (void) reloadData {
7377 NSArray *packages = [database_ packages];
7379 CFArrayRemoveAllValues(packages_);
7381 [sections_ removeAllObjects];
7384 UIProgressHUD *hud([delegate_ addProgressHUD]);
7385 [hud setText:UCLocalize("LOADING")];
7386 //NSLog(@"HUD:%@::%@", delegate_, hud);
7387 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7388 [delegate_ removeProgressHUD:hud];
7390 [self _reloadPackages:packages];
7393 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7394 Section *ignored = nil;
7395 Section *section = nil;
7399 bool unseens = false;
7401 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7403 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7404 Package *package = [self packageAtIndex:offset];
7406 BOOL uae = [package upgradableAndEssential:YES];
7410 time_t seen([package seen]);
7412 if (section == nil || last != seen) {
7416 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7419 _profile(ChangesController$reloadData$Allocate)
7420 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7421 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7422 [sections_ addObject:section];
7426 [section addToCount];
7427 } else if ([package ignored]) {
7428 if (ignored == nil) {
7429 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7431 [ignored addToCount];
7434 [upgradable addToCount];
7439 CFRelease(formatter);
7442 Section *last = [sections_ lastObject];
7443 size_t count = [last count];
7444 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7445 [sections_ removeLastObject];
7448 if ([ignored count] != 0)
7449 [sections_ insertObject:ignored atIndex:0];
7451 [sections_ insertObject:upgradable atIndex:0];
7456 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7457 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7458 style:UIBarButtonItemStylePlain
7460 action:@selector(upgradeButtonClicked)
7463 if (![delegate_ updating])
7464 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7465 initWithTitle:UCLocalize("REFRESH")
7466 style:UIBarButtonItemStylePlain
7468 action:@selector(refreshButtonClicked)
7474 /* Search Controller {{{ */
7475 @interface SearchController : FilteredPackageController <
7478 UISearchBar *search_;
7481 - (id) initWithDatabase:(Database *)database;
7482 - (void) reloadData;
7486 @implementation SearchController
7493 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7494 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7495 [search_ resignFirstResponder];
7499 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7500 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7504 - (NSString *) title { return nil; }
7506 - (id) initWithDatabase:(Database *)database {
7507 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7510 - (void)viewDidAppear:(BOOL)animated {
7511 [super viewDidAppear:animated];
7513 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7514 [search_ layoutSubviews];
7515 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7517 UITextField *textField;
7518 if ([search_ respondsToSelector:@selector(searchField)])
7519 textField = [search_ searchField];
7521 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7523 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7524 [search_ setDelegate:self];
7525 [textField setEnablesReturnKeyAutomatically:NO];
7526 [[self navigationItem] setTitleView:textField];
7530 - (void) _reloadData {
7533 - (void) reloadData {
7534 _profile(SearchController$reloadData)
7535 [packages_ reloadData];
7538 [packages_ resetCursor];
7541 - (void) didSelectPackage:(Package *)package {
7542 [search_ resignFirstResponder];
7543 [super didSelectPackage:package];
7548 /* Settings Controller {{{ */
7549 @interface SettingsController : CYViewController <
7550 UITableViewDataSource,
7553 _transient Database *database_;
7556 UITableView *table_;
7557 UISwitch *subscribedSwitch_;
7558 UISwitch *ignoredSwitch_;
7559 UITableViewCell *subscribedCell_;
7560 UITableViewCell *ignoredCell_;
7563 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7567 @implementation SettingsController
7571 if (package_ != nil)
7574 [subscribedSwitch_ release];
7575 [ignoredSwitch_ release];
7576 [subscribedCell_ release];
7577 [ignoredCell_ release];
7582 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7583 if (package_ == nil)
7589 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7590 if (package_ == nil)
7596 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7597 return UCLocalize("SHOW_ALL_CHANGES_EX");
7600 - (void) onSubscribed:(id)control {
7601 bool value([control isOn]);
7602 if (package_ == nil)
7604 if ([package_ setSubscribed:value])
7605 [delegate_ updateData];
7608 - (void) onIgnored:(id)control {
7609 // TODO: set Held state - possibly call out to dpkg, etc.
7612 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7613 if (package_ == nil)
7616 switch ([indexPath row]) {
7617 case 0: return subscribedCell_;
7618 case 1: return ignoredCell_;
7626 - (NSString *) title { return UCLocalize("SETTINGS"); }
7628 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7629 if ((self = [super init])) {
7630 database_ = database;
7631 name_ = [package retain];
7633 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7635 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7636 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7637 [[self view] addSubview:table_];
7639 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7640 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7641 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7643 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7644 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7645 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7647 subscribedCell_ = [[UITableViewCell alloc] init];
7648 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7649 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7650 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7652 ignoredCell_ = [[UITableViewCell alloc] init];
7653 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7654 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7655 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7657 [table_ setDataSource:self];
7658 [table_ setDelegate:self];
7663 - (void) reloadData {
7664 if (package_ != nil)
7665 [package_ autorelease];
7666 package_ = [database_ packageWithName:name_];
7667 if (package_ != nil) {
7669 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7670 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7673 [table_ reloadData];
7678 /* Signature Controller {{{ */
7679 @interface SignatureController : CYBrowserController {
7680 _transient Database *database_;
7684 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7688 @implementation SignatureController
7695 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7697 [super webView:view didClearWindowObject:window forFrame:frame];
7700 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7701 if ((self = [super init]) != nil) {
7702 database_ = database;
7703 package_ = [package retain];
7708 - (void) reloadData {
7709 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7715 /* Role Controller {{{ */
7716 @interface RoleController : CYViewController <
7717 UITableViewDataSource,
7720 _transient Database *database_;
7721 // XXX: ok, "roledelegate_"?...
7722 _transient id roledelegate_;
7723 UITableView *table_;
7724 UISegmentedControl *segment_;
7728 - (void) showDoneButton;
7729 - (void) resizeSegmentedControl;
7733 @implementation RoleController
7737 [container_ release];
7742 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7743 if ((self = [super init])) {
7744 database_ = database;
7745 roledelegate_ = delegate;
7747 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7749 NSArray *items = [NSArray arrayWithObjects:
7751 UCLocalize("HACKER"),
7752 UCLocalize("DEVELOPER"),
7754 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7755 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7756 [container_ addSubview:segment_];
7759 if ([Role_ isEqualToString:@"User"]) index = 0;
7760 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7761 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7763 [segment_ setSelectedSegmentIndex:index];
7764 [self showDoneButton];
7767 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7768 [self resizeSegmentedControl];
7770 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7771 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7772 [table_ setDelegate:self];
7773 [table_ setDataSource:self];
7774 [[self view] addSubview:table_];
7775 [table_ reloadData];
7779 - (void) resizeSegmentedControl {
7780 CGFloat width = [[self view] frame].size.width;
7781 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7784 - (void) viewWillAppear:(BOOL)animated {
7785 [super viewWillAppear:animated];
7787 [self resizeSegmentedControl];
7790 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7791 [self resizeSegmentedControl];
7794 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7795 [self resizeSegmentedControl];
7799 NSString *role(nil);
7801 switch ([segment_ selectedSegmentIndex]) {
7802 case 0: role = @"User"; break;
7803 case 1: role = @"Hacker"; break;
7804 case 2: role = @"Developer"; break;
7809 if (![role isEqualToString:Role_]) {
7810 bool rolling(Role_ == nil);
7813 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7817 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7821 [roledelegate_ loadData];
7823 [roledelegate_ updateData];
7827 - (void) segmentChanged:(UISegmentedControl *)control {
7828 [self showDoneButton];
7831 - (void) saveAndClose {
7834 [[self navigationItem] setRightBarButtonItem:nil];
7835 [[self navigationController] dismissModalViewControllerAnimated:YES];
7838 - (void) doneButtonClicked {
7839 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7840 [spinner startAnimating];
7841 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7842 [[self navigationItem] setRightBarButtonItem:spinItem];
7844 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7847 - (void) showDoneButton {
7848 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7849 initWithTitle:UCLocalize("DONE")
7850 style:UIBarButtonItemStyleDone
7852 action:@selector(doneButtonClicked)
7853 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7856 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7857 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7861 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7865 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7866 return nil; // This method is required by the protocol.
7869 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7871 return UCLocalize("ROLE_EX");
7873 return [NSString stringWithFormat:
7874 @"%@: %@\n%@: %@\n%@: %@",
7875 UCLocalize("USER"), UCLocalize("USER_EX"),
7876 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7877 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7882 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7883 return section == 3 ? 44.0f : 0;
7886 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7887 return section == 3 ? container_ : nil;
7892 /* Stash Controller {{{ */
7893 @interface CYStashController : CYViewController {
7894 // XXX: just delete these things
7895 _transient UIActivityIndicatorView *spinner_;
7896 _transient UILabel *status_;
7897 _transient UILabel *caption_;
7901 @implementation CYStashController
7903 if ((self = [super init])) {
7904 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7906 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7907 CGRect spinrect = [spinner_ frame];
7908 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7909 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7910 [spinner_ setFrame:spinrect];
7911 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7912 [[self view] addSubview:spinner_];
7913 [spinner_ startAnimating];
7916 captrect.size.width = [[self view] frame].size.width;
7917 captrect.size.height = 40.0f;
7918 captrect.origin.x = 0;
7919 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7920 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7921 [caption_ setText:@"Initializing Filesystem"];
7922 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7923 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7924 [caption_ setTextColor:[UIColor whiteColor]];
7925 [caption_ setBackgroundColor:[UIColor clearColor]];
7926 [caption_ setShadowColor:[UIColor blackColor]];
7927 [caption_ setTextAlignment:UITextAlignmentCenter];
7928 [[self view] addSubview:caption_];
7931 statusrect.size.width = [[self view] frame].size.width;
7932 statusrect.size.height = 30.0f;
7933 statusrect.origin.x = 0;
7934 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7935 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7936 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7937 [status_ setText:@"(Cydia will exit when complete.)"];
7938 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7939 [status_ setTextColor:[UIColor whiteColor]];
7940 [status_ setBackgroundColor:[UIColor clearColor]];
7941 [status_ setShadowColor:[UIColor blackColor]];
7942 [status_ setTextAlignment:UITextAlignmentCenter];
7943 [[self view] addSubview:status_];
7947 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7948 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7963 @interface Cydia : UIApplication <
7964 ConfirmationControllerDelegate,
7965 ProgressControllerDelegate,
7967 UINavigationControllerDelegate,
7968 UITabBarControllerDelegate
7970 // XXX: evaluate all fields for _transient
7973 CYTabBarController *tabbar_;
7975 NSMutableArray *essential_;
7976 NSMutableArray *broken_;
7978 Database *database_;
7984 SectionsController *sections_;
7985 ChangesController *changes_;
7986 ManageController *manage_;
7987 SearchController *search_;
7988 SourceTable *sources_;
7989 InstalledController *installed_;
7992 CYStashController *stash_;
7997 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7998 - (void) setPage:(CYViewController *)page;
8001 // XXX: I hate prototypes
8002 - (id) queueBadgeController;
8006 static _finline void _setHomePage(Cydia *self) {
8007 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
8010 @implementation Cydia
8012 - (void) beginUpdate {
8013 [tabbar_ beginUpdate];
8017 return [tabbar_ updating];
8020 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8025 if ([broken_ count] != 0) {
8026 int count = [broken_ count];
8028 UIAlertView *alert = [[[UIAlertView alloc]
8029 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8030 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8032 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8033 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8036 [alert setContext:@"fixhalf"];
8038 } else if (!Ignored_ && [essential_ count] != 0) {
8039 int count = [essential_ count];
8041 UIAlertView *alert = [[[UIAlertView alloc]
8042 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8043 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8045 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8046 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8049 [alert setContext:@"upgrade"];
8054 - (void) _saveConfig {
8060 NSString *error(nil);
8062 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8064 NSError *error(nil);
8065 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8066 NSLog(@"failure to save metadata data: %@", error);
8071 NSLog(@"failure to serialize metadata: %@", error);
8076 - (void) _updateData {
8079 /* XXX: this is just stupid */
8080 if (tag_ != 1 && sections_ != nil)
8081 [sections_ reloadData];
8082 if (tag_ != 2 && changes_ != nil)
8083 [changes_ reloadData];
8084 if (tag_ != 4 && search_ != nil)
8085 [search_ reloadData];
8087 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8089 [queueDelegate_ queueStatusDidChange];
8090 [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8093 - (int)indexOfTabWithTag:(int)tag {
8095 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8096 if ([[controller tabBarItem] tag] == tag)
8104 - (void) _refreshIfPossible {
8105 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8107 bool recently = false;
8108 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8109 if (update != nil) {
8110 NSTimeInterval interval([update timeIntervalSinceNow]);
8111 if (interval <= 0 && interval > -(15*60))
8115 // Don't automatic refresh if:
8116 // - We already refreshed recently.
8117 // - We already auto-refreshed this launch.
8118 // - Auto-refresh is disabled.
8119 if (recently || loaded_ || ManualRefresh) {
8120 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8122 // If we are cancelling due to ManualRefresh or a recent refresh
8123 // we need to make sure it knows it's already loaded.
8127 // We are going to load, so remember that.
8131 SCNetworkReachabilityFlags flags; {
8132 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8133 SCNetworkReachabilityGetFlags(reachability, &flags);
8134 CFRelease(reachability);
8137 // XXX: this elaborate mess is what Apple is using to determine this? :(
8138 // XXX: do we care if the user has to intervene? maybe that's ok?
8140 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8141 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8142 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8143 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8144 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8145 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8149 // If we can reach the server, auto-refresh!
8151 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8156 - (void) refreshIfPossible {
8157 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8160 - (void) _reloadData {
8161 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8162 [hud setText:UCLocalize("RELOADING_DATA")];
8164 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8167 [self removeProgressHUD:hud];
8171 [essential_ removeAllObjects];
8172 [broken_ removeAllObjects];
8174 NSArray *packages([database_ packages]);
8175 for (Package *package in packages) {
8177 [broken_ addObject:package];
8178 if ([package upgradableAndEssential:NO]) {
8179 if ([package essential])
8180 [essential_ addObject:package];
8185 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8187 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8188 [changesItem setBadgeValue:badge];
8189 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8191 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8192 [self setApplicationBadge:badge];
8194 [self setApplicationBadgeString:badge];
8196 [changesItem setBadgeValue:nil];
8197 [changesItem setAnimatedBadge:NO];
8199 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8200 [self removeApplicationBadge];
8201 else // XXX: maybe use setApplicationBadgeString also?
8202 [self setApplicationIconBadgeNumber:0];
8207 [self refreshIfPossible];
8210 - (void) updateData {
8219 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8220 _assert(file != NULL);
8222 for (NSString *key in [Sources_ allKeys]) {
8223 NSDictionary *source([Sources_ objectForKey:key]);
8225 fprintf(file, "%s %s %s\n",
8226 [[source objectForKey:@"Type"] UTF8String],
8227 [[source objectForKey:@"URI"] UTF8String],
8228 [[source objectForKey:@"Distribution"] UTF8String]
8236 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8237 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8239 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8240 [tabbar_ presentModalViewController:navigation animated:YES];
8243 detachNewThreadSelector:@selector(update_)
8246 title:UCLocalize("UPDATING_SOURCES")
8250 - (void) reloadData {
8251 @synchronized (self) {
8257 pkgProblemResolver *resolver = [database_ resolver];
8259 resolver->InstallProtect();
8260 if (!resolver->Resolve(true))
8264 - (CGRect) popUpBounds {
8265 return [[tabbar_ view] bounds];
8269 if (![database_ prepare])
8272 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8273 [page setDelegate:self];
8274 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8275 [confirm_ setDelegate:self];
8278 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8279 [tabbar_ presentModalViewController:confirm_ animated:YES];
8285 @synchronized (self) {
8290 - (void) clearPackage:(Package *)package {
8291 @synchronized (self) {
8298 - (void) installPackages:(NSArray *)packages {
8299 @synchronized (self) {
8300 for (Package *package in packages)
8307 - (void) installPackage:(Package *)package {
8308 @synchronized (self) {
8315 - (void) removePackage:(Package *)package {
8316 @synchronized (self) {
8323 - (void) distUpgrade {
8324 @synchronized (self) {
8325 if (![database_ upgrade])
8332 @synchronized (self) {
8337 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8340 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8342 if (navigation != nil) {
8343 [navigation pushViewController:progress animated:YES];
8345 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8347 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8348 [tabbar_ presentModalViewController:navigation animated:YES];
8352 detachNewThreadSelector:@selector(perform)
8355 title:UCLocalize("RUNNING")
8359 - (void) progressControllerIsComplete:(ProgressController *)progress {
8363 - (void) setPage:(CYViewController *)page {
8364 [page setDelegate:self];
8366 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8367 [navController setViewControllers:[NSArray arrayWithObject:page]];
8368 for (CYNavigationController *page in [tabbar_ viewControllers])
8369 if (page != navController)
8370 [page setViewControllers:nil];
8373 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8374 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8375 [browser loadURL:url];
8379 - (SectionsController *) sectionsController {
8380 if (sections_ == nil)
8381 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8385 - (ChangesController *) changesController {
8386 if (changes_ == nil)
8387 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8391 - (ManageController *) manageController {
8392 if (manage_ == nil) {
8393 manage_ = (ManageController *) [[self
8394 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8395 withClass:[ManageController class]
8398 queueDelegate_ = manage_;
8403 - (SearchController *) searchController {
8405 search_ = [[SearchController alloc] initWithDatabase:database_];
8409 - (SourceTable *) sourcesController {
8410 if (sources_ == nil)
8411 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8415 - (InstalledController *) installedController {
8416 if (installed_ == nil) {
8417 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8419 queueDelegate_ = installed_;
8424 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8425 int tag = [[viewController tabBarItem] tag];
8427 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8429 } else if (tag_ == 1) {
8430 [[self sectionsController] resetView];
8434 case kCydiaTag: _setHomePage(self); break;
8436 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8437 case kChangesTag: [self setPage:[self changesController]]; break;
8438 case kManageTag: [self setPage:[self manageController]]; break;
8439 case kInstalledTag: [self setPage:[self installedController]]; break;
8440 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8441 case kSearchTag: [self setPage:[self searchController]]; break;
8449 - (void) showSettings {
8450 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8451 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8453 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8454 [tabbar_ presentModalViewController:nav animated:YES];
8457 - (void) setPackageController:(PackageController *)view {
8459 [view setPackage:nil];
8463 - (PackageController *) _packageController {
8464 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8467 - (PackageController *) packageController {
8468 return [self _packageController];
8471 // Returns the navigation controller for the queuing badge.
8472 - (id) queueBadgeController {
8473 int index = [self indexOfTabWithTag:kManageTag];
8475 index = [self indexOfTabWithTag:kInstalledTag];
8477 return [[tabbar_ viewControllers] objectAtIndex:index];
8480 - (void) cancelAndClear:(bool)clear {
8481 @synchronized (self) {
8493 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8494 NSString *context([alert context]);
8496 if ([context isEqualToString:@"fixhalf"]) {
8497 if (button == [alert firstOtherButtonIndex]) {
8498 @synchronized (self) {
8499 for (Package *broken in broken_) {
8502 NSString *id = [broken id];
8503 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8504 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8505 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8506 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8512 } else if (button == [alert cancelButtonIndex]) {
8513 [broken_ removeAllObjects];
8517 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8518 } else if ([context isEqualToString:@"upgrade"]) {
8519 if (button == [alert firstOtherButtonIndex]) {
8520 @synchronized (self) {
8521 for (Package *essential in essential_)
8522 [essential install];
8527 } else if (button == [alert firstOtherButtonIndex] + 1) {
8529 } else if (button == [alert cancelButtonIndex]) {
8533 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8537 - (void) system:(NSString *)command { _pooled
8538 system([command UTF8String]);
8541 - (void) applicationWillSuspend {
8543 [super applicationWillSuspend];
8546 - (BOOL) hudIsShowing {
8547 return (hudcount_ > 0);
8550 - (void) applicationSuspend:(__GSEvent *)event {
8551 // Use external process status API internally.
8552 // This is probably a really bad idea.
8553 uint64_t status = 0;
8555 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8556 notify_get_state(notify_token, &status);
8557 notify_cancel(notify_token);
8560 if (![self hudIsShowing] && status == 0)
8561 [super applicationSuspend:event];
8564 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8565 if (![self hudIsShowing])
8566 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8569 - (void) _setSuspended:(BOOL)value {
8570 if (![self hudIsShowing])
8571 [super _setSuspended:value];
8574 - (UIProgressHUD *) addProgressHUD {
8575 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8576 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8578 [window_ setUserInteractionEnabled:NO];
8581 UIViewController *target = tabbar_;
8582 while ([target modalViewController] != nil) target = [target modalViewController];
8583 [[target view] addSubview:hud];
8589 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8591 [hud removeFromSuperview];
8592 [window_ setUserInteractionEnabled:YES];
8596 - (CYViewController *) pageForPackage:(NSString *)name {
8597 if (Package *package = [database_ packageWithName:name]) {
8598 PackageController *view([self packageController]);
8599 [view setPackage:package];
8602 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8603 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8604 return [self _pageForURL:url withClass:[CYBrowserController class]];
8608 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8612 NSString *href([url absoluteString]);
8613 if ([href hasPrefix:@"apptapp://package/"])
8614 return [self pageForPackage:[href substringFromIndex:18]];
8616 NSString *scheme([[url scheme] lowercaseString]);
8617 if (![scheme isEqualToString:@"cydia"])
8619 NSString *path([url absoluteString]);
8620 if ([path length] < 8)
8622 path = [path substringFromIndex:8];
8623 if (![path hasPrefix:@"/"])
8624 path = [@"/" stringByAppendingString:path];
8626 if ([path isEqualToString:@"/add-source"])
8627 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8628 else if ([path isEqualToString:@"/storage"])
8629 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8630 else if ([path isEqualToString:@"/sources"])
8631 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8632 else if ([path isEqualToString:@"/packages"])
8633 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8634 else if ([path hasPrefix:@"/url/"])
8635 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8636 else if ([path hasPrefix:@"/launch/"])
8637 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8638 else if ([path hasPrefix:@"/package-settings/"])
8639 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8640 else if ([path hasPrefix:@"/package-signature/"])
8641 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8642 else if ([path hasPrefix:@"/package/"])
8643 return [self pageForPackage:[path substringFromIndex:9]];
8644 else if ([path hasPrefix:@"/files/"]) {
8645 NSString *name = [path substringFromIndex:7];
8647 if (Package *package = [database_ packageWithName:name]) {
8648 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8649 [files setPackage:package];
8657 - (BOOL) openCydiaURL:(NSURL *)url {
8658 CYViewController *page = nil;
8661 NSLog(@"open url: %@", url);
8663 if ((page = [self pageForURL:url hasTag:&tag])) {
8664 [self setPage:page];
8666 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8672 - (void) applicationOpenURL:(NSURL *)url {
8673 [super applicationOpenURL:url];
8674 NSLog(@"first: %@", url);
8675 if (!loaded_) starturl_ = [url retain];
8676 else [self openCydiaURL:url];
8679 - (void) applicationWillResignActive:(UIApplication *)application {
8680 // Stop refreshing if you get a phone call or lock the device.
8681 if ([tabbar_ updating])
8682 [tabbar_ cancelUpdate];
8684 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8685 [super applicationWillResignActive:application];
8688 - (void) addStashController {
8689 stash_ = [[CYStashController alloc] init];
8690 [window_ addSubview:[stash_ view]];
8693 - (void) removeStashController {
8694 [[stash_ view] removeFromSuperview];
8699 [self setIdleTimerDisabled:YES];
8701 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8702 [self setStatusBarShowsProgress:YES];
8703 UpdateExternalStatus(1);
8705 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8707 UpdateExternalStatus(0);
8708 [self setStatusBarShowsProgress:NO];
8710 [self removeStashController];
8712 if (ExecFork() == 0) {
8713 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8714 perror("launchctl stop");
8718 - (void) setupTabBarController {
8719 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8720 [tabbar_ setDelegate:self];
8722 NSMutableArray *items([NSMutableArray arrayWithObjects:
8723 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8724 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8725 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8726 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8730 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8731 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8733 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8736 NSMutableArray *controllers([NSMutableArray array]);
8738 for (UITabBarItem *item in items) {
8739 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8740 [controller setTabBarItem:item];
8741 [controllers addObject:controller];
8744 [tabbar_ setViewControllers:controllers];
8747 - (void) applicationDidFinishLaunching:(id)unused {
8749 [CYBrowserController _initialize];
8751 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8753 Font12_ = [[UIFont systemFontOfSize:12] retain];
8754 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8755 Font14_ = [[UIFont systemFontOfSize:14] retain];
8756 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8757 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8761 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8762 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8764 UIScreen *screen([UIScreen mainScreen]);
8766 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8767 [window_ orderFront:self];
8768 [window_ makeKey:self];
8769 [window_ setHidden:NO];
8772 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8773 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8774 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8775 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8776 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8777 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8778 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8779 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8780 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8783 [self addStashController];
8784 // XXX: this would be much cleaner as a yieldToSelector:
8785 // that way the removeStashController could happen right here inline
8786 // we also could no longer require the useless stash_ field anymore
8787 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8791 database_ = [Database sharedInstance];
8793 [self setupTabBarController];
8794 [tabbar_ setUpdateDelegate:self];
8795 [window_ addSubview:[tabbar_ view]];
8797 // Show pinstripes while loading data.
8798 [[tabbar_ view] setBackgroundColor:[UIColor pinStripeColor]];
8800 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8807 [self showSettings];
8811 [window_ setUserInteractionEnabled:NO];
8813 UIView *container = [[[UIView alloc] init] autorelease];
8814 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8816 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8817 [spinner startAnimating];
8818 [container addSubview:spinner];
8820 UILabel *label = [[[UILabel alloc] init] autorelease];
8821 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8822 [label setBackgroundColor:[UIColor clearColor]];
8823 [label setTextColor:[UIColor blackColor]];
8824 [label setShadowColor:[UIColor whiteColor]];
8825 [label setShadowOffset:CGSizeMake(0, 1)];
8826 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8827 [container addSubview:label];
8829 CGSize viewsize = [[tabbar_ view] frame].size;
8830 CGSize spinnersize = [spinner bounds].size;
8831 CGSize textsize = [[label text] sizeWithFont:[label font]];
8832 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8834 CGRect containrect = {
8835 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8836 CGSizeMake(bothwidth, spinnersize.height)
8839 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8847 [container setFrame:containrect];
8848 [spinner setFrame:spinrect];
8849 [label setFrame:textrect];
8850 [[tabbar_ view] addSubview:container];
8855 // Show the initial page
8856 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
8857 [tabbar_ setSelectedIndex:0];
8861 [starturl_ release];
8864 [window_ setUserInteractionEnabled:YES];
8866 // XXX: does this actually slow anything down?
8867 [[tabbar_ view] setBackgroundColor:[UIColor clearColor]];
8868 [container removeFromSuperview];
8871 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8872 if (item != nil && IsWildcat_) {
8873 [sheet showFromBarButtonItem:item animated:YES];
8875 [sheet showInView:window_];
8882 id Alloc_(id self, SEL selector) {
8883 id object = alloc_(self, selector);
8884 lprintf("[%s]A-%p\n", self->isa->name, object);
8889 id Dealloc_(id self, SEL selector) {
8890 id object = dealloc_(self, selector);
8891 lprintf("[%s]D-%p\n", self->isa->name, object);
8895 Class $WebDefaultUIKitDelegate;
8897 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8898 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8899 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8900 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8903 static NSNumber *shouldPlayKeyboardSounds;
8907 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8909 case 1104: // Keyboard Button Clicked
8910 case 1105: // Keyboard Delete Repeated
8911 if (shouldPlayKeyboardSounds == nil) {
8912 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8913 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8916 if (![shouldPlayKeyboardSounds boolValue])
8920 _UIHardware$_playSystemSound$(self, _cmd, sound);
8924 int main(int argc, char *argv[]) { _pooled
8927 if (Class $UIDevice = objc_getClass("UIDevice")) {
8928 UIDevice *device([$UIDevice currentDevice]);
8929 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8933 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8935 /* Library Hacks {{{ */
8936 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8938 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8939 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8940 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8941 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8942 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8945 $UIHardware = objc_getClass("UIHardware");
8946 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8947 if (UIHardware$_playSystemSound$ != NULL) {
8948 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8949 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8952 /* Set Locale {{{ */
8953 Locale_ = CFLocaleCopyCurrent();
8954 Languages_ = [NSLocale preferredLanguages];
8955 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8956 //NSLog(@"%@", [Languages_ description]);
8959 if (Languages_ == nil || [Languages_ count] == 0)
8960 // XXX: consider just setting to C and then falling through?
8963 lang = [[Languages_ objectAtIndex:0] UTF8String];
8964 setenv("LANG", lang, true);
8967 //std::setlocale(LC_ALL, lang);
8968 NSLog(@"Setting Language: %s", lang);
8971 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8973 /* Parse Arguments {{{ */
8974 bool substrate(false);
8980 for (int argi(1); argi != argc; ++argi)
8981 if (strcmp(argv[argi], "--") == 0) {
8983 argv[argi] = argv[0];
8989 for (int argi(1); argi != arge; ++argi)
8990 if (strcmp(args[argi], "--substrate") == 0)
8993 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8997 App_ = [[NSBundle mainBundle] bundlePath];
8998 Home_ = NSHomeDirectory();
9004 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9005 alloc_ = alloc->method_imp;
9006 alloc->method_imp = (IMP) &Alloc_;*/
9008 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9009 dealloc_ = dealloc->method_imp;
9010 dealloc->method_imp = (IMP) &Dealloc_;*/
9012 /* System Information {{{ */
9016 size = sizeof(maxproc);
9017 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9018 perror("sysctlbyname(\"kern.maxproc\", ?)");
9019 else if (maxproc < 64) {
9021 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9022 perror("sysctlbyname(\"kern.maxproc\", #)");
9025 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9026 char *osversion = new char[size];
9027 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9028 perror("sysctlbyname(\"kern.osversion\", ?)");
9030 System_ = [NSString stringWithUTF8String:osversion];
9032 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9033 char *machine = new char[size];
9034 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9035 perror("sysctlbyname(\"hw.machine\", ?)");
9039 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9040 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9041 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9042 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9046 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9047 NSData *data((NSData *) ecid);
9048 size_t length([data length]);
9049 uint8_t bytes[length];
9050 [data getBytes:bytes];
9051 char string[length * 2 + 1];
9052 for (size_t i(0); i != length; ++i)
9053 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9054 ChipID_ = [NSString stringWithUTF8String:string];
9058 IOObjectRelease(service);
9062 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9064 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9065 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9066 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9068 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9069 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9070 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9072 if (mcc != NULL && mnc != NULL)
9073 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9080 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9081 Build_ = [system objectForKey:@"ProductBuildVersion"];
9082 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9083 Product_ = [info objectForKey:@"SafariProductVersion"];
9084 Safari_ = [info objectForKey:@"CFBundleVersion"];
9087 /* Load Database {{{ */
9089 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9091 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9093 if (Metadata_ == NULL)
9094 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9096 Settings_ = [Metadata_ objectForKey:@"Settings"];
9098 Packages_ = [Metadata_ objectForKey:@"Packages"];
9099 Sections_ = [Metadata_ objectForKey:@"Sections"];
9100 Sources_ = [Metadata_ objectForKey:@"Sources"];
9102 Token_ = [Metadata_ objectForKey:@"Token"];
9105 if (Settings_ != nil)
9106 Role_ = [Settings_ objectForKey:@"Role"];
9108 if (Sections_ == nil) {
9109 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9110 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9113 if (Sources_ == nil) {
9114 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9115 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9120 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9123 if (Packages_ != nil) {
9124 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9126 [Metadata_ removeObjectForKey:@"Packages"];
9131 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9133 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9134 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9135 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9136 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9137 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9138 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9140 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9142 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9143 unlink("/tmp/.cydia.fw");
9145 } else if (access("/User", F_OK) != 0 || version < 2) {
9148 system("/usr/libexec/cydia/firmware.sh");
9152 _assert([[NSFileManager defaultManager]
9153 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9154 withIntermediateDirectories:YES
9159 if (access("/tmp/cydia.chk", F_OK) == 0) {
9160 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9161 _assert(errno == ENOENT);
9162 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9163 _assert(errno == ENOENT);
9166 /* APT Initialization {{{ */
9167 _assert(pkgInitConfig(*_config));
9168 _assert(pkgInitSystem(*_config, _system));
9171 _config->Set("APT::Acquire::Translation", lang);
9173 // XXX: this timeout might be important :(
9174 //_config->Set("Acquire::http::Timeout", 15);
9176 _config->Set("Acquire::http::MaxParallel", 3);
9178 /* Color Choices {{{ */
9179 space_ = CGColorSpaceCreateDeviceRGB();
9181 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9182 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9183 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9184 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9185 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9186 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9187 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9188 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9189 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9191 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9192 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9194 /* UIKit Configuration {{{ */
9195 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9196 if ($GSFontSetUseLegacyFontMetrics != NULL)
9197 $GSFontSetUseLegacyFontMetrics(YES);
9199 // XXX: I have a feeling this was important
9200 //UIKeyboardDisableAutomaticAppearance();
9203 Colon_ = UCLocalize("COLON_DELIMITED");
9204 Elision_ = UCLocalize("ELISION");
9205 Error_ = UCLocalize("ERROR");
9206 Warning_ = UCLocalize("WARNING");
9209 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9211 CGColorSpaceRelease(space_);