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 <ext/hash_map>
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 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
209 void NSLogPoint(const char *fix, const CGPoint &point) {
210 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
213 void NSLogRect(const char *fix, const CGRect &rect) {
214 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
217 static _finline NSString *CydiaURL(NSString *path) {
219 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
220 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
221 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
222 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
223 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
224 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
227 static _finline void UpdateExternalStatus(uint64_t newStatus) {
229 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
230 notify_set_state(notify_token, newStatus);
231 notify_cancel(notify_token);
233 notify_post("com.saurik.Cydia.status");
236 /* [NSObject yieldToSelector:(withObject:)] {{{*/
237 @interface NSObject (Cydia)
238 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
239 - (id) yieldToSelector:(SEL)selector;
242 @implementation NSObject (Cydia)
247 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
248 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
249 id object([[context objectAtIndex:1] nonretainedObjectValue]);
250 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
252 /* XXX: deal with exceptions */
253 id value([self performSelector:selector withObject:object]);
255 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
256 [context removeAllObjects];
257 if ([signature methodReturnLength] != 0 && value != nil)
258 [context addObject:value];
263 performSelectorOnMainThread:@selector(doNothing)
269 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
270 /*return [self performSelector:selector withObject:object];*/
272 volatile bool stopped(false);
274 NSMutableArray *context([NSMutableArray arrayWithObjects:
275 [NSValue valueWithPointer:selector],
276 [NSValue valueWithNonretainedObject:object],
277 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
280 NSThread *thread([[[NSThread alloc]
282 selector:@selector(_yieldToContext:)
288 NSRunLoop *loop([NSRunLoop currentRunLoop]);
289 NSDate *future([NSDate distantFuture]);
291 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
293 return [context count] == 0 ? nil : [context objectAtIndex:0];
296 - (id) yieldToSelector:(SEL)selector {
297 return [self yieldToSelector:selector withObject:nil];
303 /* Cydia Action Sheet {{{ */
304 @interface CYActionSheet : UIAlertView {
308 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
311 @implementation CYActionSheet
313 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
314 if ((self = [super init])) {
315 [self setTitle:title];
316 [self setDelegate:self];
317 for (NSString *button in buttons) [self addButtonWithTitle:button];
318 [self setCancelButtonIndex:index];
322 - (void) _updateFrameForDisplay {
323 [super _updateFrameForDisplay];
324 if ([self cancelButtonIndex] == -1) {
325 NSArray *buttons = [self buttons];
326 if ([buttons count]) {
327 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
328 for (UIThreePartButton *button in buttons)
329 [button setBackground:background forState:0];
334 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
335 button_ = buttonIndex + 1;
339 [self dismissWithClickedButtonIndex:-1 animated:YES];
342 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
343 [self setRunsModal:YES];
352 /* NSForcedOrderingSearch doesn't work on the iPhone */
353 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
354 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
355 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
357 /* Information Dictionaries {{{ */
358 @interface NSMutableArray (Cydia)
359 - (void) addInfoDictionary:(NSDictionary *)info;
362 @implementation NSMutableArray (Cydia)
364 - (void) addInfoDictionary:(NSDictionary *)info {
365 [self addObject:info];
370 @interface NSMutableDictionary (Cydia)
371 - (void) addInfoDictionary:(NSDictionary *)info;
374 @implementation NSMutableDictionary (Cydia)
376 - (void) addInfoDictionary:(NSDictionary *)info {
377 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
383 #define lprintf(args...) fprintf(stderr, args)
386 #define TraceLogging (1 && !ForRelease)
387 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
388 #define ProfileTimes (0 && !ForRelease)
389 #define ForSaurik (0 && !ForRelease)
390 #define LogBrowser (0 && !ForRelease)
391 #define TrackResize (0 && !ForRelease)
392 #define ManualRefresh (1 && !ForRelease)
393 #define ShowInternals (0 && !ForRelease)
394 #define IgnoreInstall (0 && !ForRelease)
395 #define AlwaysReload (0 && !ForRelease)
399 #define _trace(args...)
404 #define _profile(name) {
407 #define PrintTimes() do {} while (false)
411 typedef uint32_t (*SKRadixFunction)(id, void *);
413 @interface NSMutableArray (Radix)
414 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
415 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
423 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
424 struct RadixItem_ *lhs(swap), *rhs(swap + count);
426 static const size_t width = 32;
427 static const size_t bits = 11;
428 static const size_t slots = 1 << bits;
429 static const size_t passes = (width + (bits - 1)) / bits;
431 size_t *hist(new size_t[slots]);
433 for (size_t pass(0); pass != passes; ++pass) {
434 memset(hist, 0, sizeof(size_t) * slots);
436 for (size_t i(0); i != count; ++i) {
437 uint32_t key(lhs[i].key);
439 key &= _not(uint32_t) >> width - bits;
444 for (size_t i(0); i != slots; ++i) {
445 size_t local(offset);
450 for (size_t i(0); i != count; ++i) {
451 uint32_t key(lhs[i].key);
453 key &= _not(uint32_t) >> width - bits;
454 rhs[hist[key]++] = lhs[i];
457 RadixItem_ *tmp(lhs);
464 const void **values(new const void *[count]);
465 for (size_t i(0); i != count; ++i)
466 values[i] = [self objectAtIndex:lhs[i].index];
467 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
473 @implementation NSMutableArray (Radix)
475 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
476 size_t count([self count]);
481 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
482 [invocation setSelector:selector];
483 [invocation setArgument:&object atIndex:2];
485 /* XXX: this is an unsafe optimization of doomy hell */
486 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
487 _assert(method != NULL);
488 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
489 _assert(imp != NULL);
492 struct RadixItem_ *swap(new RadixItem_[count * 2]);
494 for (size_t i(0); i != count; ++i) {
495 RadixItem_ &item(swap[i]);
498 id object([self objectAtIndex:i]);
501 [invocation setTarget:object];
503 [invocation getReturnValue:&item.key];
505 item.key = imp(object, selector, object);
509 RadixSort_(self, count, swap);
512 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
513 size_t count([self count]);
514 struct RadixItem_ *swap(new RadixItem_[count * 2]);
516 for (size_t i(0); i != count; ++i) {
517 RadixItem_ &item(swap[i]);
520 id object([self objectAtIndex:i]);
521 item.key = function(object, argument);
524 RadixSort_(self, count, swap);
529 /* Insertion Sort {{{ */
531 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
532 const char *ptr = (const char *)list;
534 CFIndex half = count / 2;
535 const char *probe = ptr + elementSize * half;
536 CFComparisonResult cr = comparator(element, probe, context);
537 if (0 == cr) return (probe - (const char *)list) / elementSize;
538 ptr = (cr < 0) ? ptr : probe + elementSize;
539 count = (cr < 0) ? half : (half + (count & 1) - 1);
541 return (ptr - (const char *)list) / elementSize;
544 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
545 const char *ptr = (const char *)list;
547 CFIndex half = count / 2;
548 const char *probe = ptr + elementSize * half;
549 CFComparisonResult cr = comparator(element, probe, context);
550 if (0 == cr) return (probe - (const char *)list) / elementSize;
551 ptr = (cr < 0) ? ptr : probe + elementSize;
552 count = (cr < 0) ? half : (half + (count & 1) - 1);
554 return (ptr - (const char *)list) / elementSize;
557 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
558 if (range.length == 0)
560 const void **values(new const void *[range.length]);
561 CFArrayGetValues(array, range, values);
563 #if HistogramInsertionSort > 0
564 uint32_t total(0), *offsets(new uint32_t[range.length]);
567 for (CFIndex index(1); index != range.length; ++index) {
568 const void *value(values[index]);
569 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
570 CFIndex correct(index);
571 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
572 #if HistogramInsertionSort > 1
573 NSLog(@"%@ < %@", value, values[correct - 1]);
578 if (correct != index) {
579 size_t offset(index - correct);
580 #if HistogramInsertionSort
584 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
586 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
587 values[correct] = value;
591 CFArrayReplaceValues(array, range, values, range.length);
594 #if HistogramInsertionSort > 0
595 for (CFIndex index(0); index != range.length; ++index)
596 if (offsets[index] != 0)
597 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
598 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
605 /* Apple Bug Fixes {{{ */
606 @implementation UIWebDocumentView (Cydia)
608 - (void) _setScrollerOffset:(CGPoint)offset {
609 UIScroller *scroller([self _scroller]);
611 CGSize size([scroller contentSize]);
612 CGSize bounds([scroller bounds].size);
615 max.x = size.width - bounds.width;
616 max.y = size.height - bounds.height;
624 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
625 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
627 [scroller setOffset:offset];
633 @implementation WebScriptObject (NSFastEnumeration)
635 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
636 size_t length([self count] - state->state);
639 else if (length > count)
641 for (size_t i(0); i != length; ++i)
642 objects[i] = [self objectAtIndex:state->state++];
643 state->itemsPtr = objects;
644 state->mutationsPtr = (unsigned long *) self;
650 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
651 size_t length([self length] - state->state);
654 else if (length > count)
656 for (size_t i(0); i != length; ++i)
657 objects[i] = [self item:state->state++];
658 state->itemsPtr = objects;
659 state->mutationsPtr = (unsigned long *) self;
663 /* Cydia NSString Additions {{{ */
664 @interface NSString (Cydia)
665 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
666 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
667 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
668 - (NSComparisonResult) compareByPath:(NSString *)other;
669 - (NSString *) stringByCachingURLWithCurrentCDN;
670 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
673 @implementation NSString (Cydia)
675 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
676 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
679 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
680 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
681 memcpy(data, bytes, length);
682 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
685 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
686 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
689 - (NSComparisonResult) compareByPath:(NSString *)other {
690 NSString *prefix = [self commonPrefixWithString:other options:0];
691 size_t length = [prefix length];
693 NSRange lrange = NSMakeRange(length, [self length] - length);
694 NSRange rrange = NSMakeRange(length, [other length] - length);
696 lrange = [self rangeOfString:@"/" options:0 range:lrange];
697 rrange = [other rangeOfString:@"/" options:0 range:rrange];
699 NSComparisonResult value;
701 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
702 value = NSOrderedSame;
703 else if (lrange.location == NSNotFound)
704 value = NSOrderedAscending;
705 else if (rrange.location == NSNotFound)
706 value = NSOrderedDescending;
708 value = NSOrderedSame;
710 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
711 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
712 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
713 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
715 NSComparisonResult result = [lpath compare:rpath];
716 return result == NSOrderedSame ? value : result;
719 - (NSString *) stringByCachingURLWithCurrentCDN {
721 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
722 withString:@"://cache.cydia.saurik.com/"
726 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
727 return [(id)CFURLCreateStringByAddingPercentEscapes(
732 kCFStringEncodingUTF8
739 /* C++ NSString Wrapper Cache {{{ */
746 _finline void clear_() {
747 if (cache_ != NULL) {
754 _finline bool empty() const {
758 _finline size_t size() const {
762 _finline char *data() const {
766 _finline void clear() {
771 _finline CYString() :
778 _finline ~CYString() {
782 void operator =(const CYString &rhs) {
786 if (rhs.cache_ == nil)
789 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
792 void set(apr_pool_t *pool, const char *data, size_t size) {
798 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
799 memcpy(temp, data, size);
806 _finline void set(apr_pool_t *pool, const char *data) {
807 set(pool, data, data == NULL ? 0 : strlen(data));
810 _finline void set(apr_pool_t *pool, const std::string &rhs) {
811 set(pool, rhs.data(), rhs.size());
814 bool operator ==(const CYString &rhs) const {
815 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
818 operator CFStringRef() {
819 if (cache_ == NULL) {
822 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
824 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
828 _finline operator id() {
829 return (NSString *) static_cast<CFStringRef>(*this);
833 /* C++ NSString Algorithm Adapters {{{ */
835 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
838 struct NSStringMapHash :
839 std::unary_function<NSString *, size_t>
841 _finline size_t operator ()(NSString *value) const {
842 return CFStringHashNSString((CFStringRef) value);
846 struct NSStringMapLess :
847 std::binary_function<NSString *, NSString *, bool>
849 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
850 return [lhs compare:rhs] == NSOrderedAscending;
854 struct NSStringMapEqual :
855 std::binary_function<NSString *, NSString *, bool>
857 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
858 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
859 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
860 //[lhs isEqualToString:rhs];
865 /* Perl-Compatible RegEx {{{ */
875 Pcre(const char *regex) :
880 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
883 lprintf("%d:%s\n", offset, error);
887 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
888 matches_ = new int[(capture_ + 1) * 3];
896 NSString *operator [](size_t match) {
897 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
900 bool operator ()(NSString *data) {
901 // XXX: length is for characters, not for bytes
902 return operator ()([data UTF8String], [data length]);
905 bool operator ()(const char *data, size_t size) {
907 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
911 /* Mime Addresses {{{ */
912 @interface Address : NSObject {
918 - (NSString *) address;
920 - (void) setAddress:(NSString *)address;
922 + (Address *) addressWithString:(NSString *)string;
923 - (Address *) initWithString:(NSString *)string;
926 @implementation Address
935 - (NSString *) name {
939 - (NSString *) address {
943 - (void) setAddress:(NSString *)address {
945 [address_ autorelease];
949 address_ = [address retain];
952 + (Address *) addressWithString:(NSString *)string {
953 return [[[Address alloc] initWithString:string] autorelease];
956 + (NSArray *) _attributeKeys {
957 return [NSArray arrayWithObjects:@"address", @"name", nil];
960 - (NSArray *) attributeKeys {
961 return [[self class] _attributeKeys];
964 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
965 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
968 - (Address *) initWithString:(NSString *)string {
969 if ((self = [super init]) != nil) {
970 const char *data = [string UTF8String];
971 size_t size = [string length];
973 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
975 if (address_r(data, size)) {
976 name_ = [address_r[1] retain];
977 address_ = [address_r[2] retain];
979 name_ = [string retain];
987 /* CoreGraphics Primitives {{{ */
998 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1001 Set(space, red, green, blue, alpha);
1006 CGColorRelease(color_);
1013 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1015 float color[] = {red, green, blue, alpha};
1016 color_ = CGColorCreate(space, (CGFloat *) color);
1019 operator CGColorRef() {
1025 /* Random Global Variables {{{ */
1026 static const int PulseInterval_ = 50000;
1027 static const int ButtonBarWidth_ = 60;
1028 static const int ButtonBarHeight_ = 48;
1029 static const float KeyboardTime_ = 0.3f;
1032 static NSArray *Finishes_;
1034 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1035 #define NotifyConfig_ "/etc/notify.conf"
1037 static bool Queuing_;
1039 static CYColor Blue_;
1040 static CYColor Blueish_;
1041 static CYColor Black_;
1042 static CYColor Off_;
1043 static CYColor White_;
1044 static CYColor Gray_;
1045 static CYColor Green_;
1046 static CYColor Purple_;
1047 static CYColor Purplish_;
1049 static UIColor *InstallingColor_;
1050 static UIColor *RemovingColor_;
1052 static NSString *App_;
1053 static NSString *Home_;
1055 static BOOL Advanced_;
1056 static BOOL Ignored_;
1058 static UIFont *Font12_;
1059 static UIFont *Font12Bold_;
1060 static UIFont *Font14_;
1061 static UIFont *Font18Bold_;
1062 static UIFont *Font22Bold_;
1064 static const char *Machine_ = NULL;
1065 static NSString *System_ = nil;
1066 static NSString *SerialNumber_ = nil;
1067 static NSString *ChipID_ = nil;
1068 static NSString *Token_ = nil;
1069 static NSString *UniqueID_ = nil;
1070 static NSString *PLMN_ = nil;
1071 static NSString *Build_ = nil;
1072 static NSString *Product_ = nil;
1073 static NSString *Safari_ = nil;
1075 static CFLocaleRef Locale_;
1076 static NSArray *Languages_;
1077 static CGColorSpaceRef space_;
1079 static NSDictionary *SectionMap_;
1080 static NSMutableDictionary *Metadata_;
1081 static _transient NSMutableDictionary *Settings_;
1082 static _transient NSString *Role_;
1083 static _transient NSMutableDictionary *Packages_;
1084 static _transient NSMutableDictionary *Sections_;
1085 static _transient NSMutableDictionary *Sources_;
1086 static bool Changed_;
1087 static NSDate *now_;
1089 static bool IsWildcat_;
1092 /* Display Helpers {{{ */
1093 inline float Interpolate(float begin, float end, float fraction) {
1094 return (end - begin) * fraction + begin;
1097 /* XXX: localize this! */
1098 NSString *SizeString(double size) {
1099 bool negative = size < 0;
1104 while (size > 1024) {
1109 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1111 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1114 static _finline CFStringRef CFCString(const char *value) {
1115 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1118 const char *StripVersion_(const char *version) {
1119 const char *colon(strchr(version, ':'));
1121 version = colon + 1;
1125 CFStringRef StripVersion(const char *version) {
1126 const char *colon(strchr(version, ':'));
1128 version = colon + 1;
1129 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1131 return CFCString(version);
1134 NSString *LocalizeSection(NSString *section) {
1135 static Pcre title_r("^(.*?) \\((.*)\\)$");
1136 if (title_r(section)) {
1137 NSString *parent(title_r[1]);
1138 NSString *child(title_r[2]);
1140 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1141 LocalizeSection(parent),
1142 LocalizeSection(child)
1146 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1149 NSString *Simplify(NSString *title) {
1150 const char *data = [title UTF8String];
1151 size_t size = [title length];
1153 static Pcre square_r("^\\[(.*)\\]$");
1154 if (square_r(data, size))
1155 return Simplify(square_r[1]);
1157 static Pcre paren_r("^\\((.*)\\)$");
1158 if (paren_r(data, size))
1159 return Simplify(paren_r[1]);
1161 static Pcre title_r("^(.*?) \\((.*)\\)$");
1162 if (title_r(data, size))
1163 return Simplify(title_r[1]);
1169 NSString *GetLastUpdate() {
1170 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1173 return UCLocalize("NEVER_OR_UNKNOWN");
1175 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1176 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1178 CFRelease(formatter);
1180 return [(NSString *) formatted autorelease];
1183 bool isSectionVisible(NSString *section) {
1184 NSDictionary *metadata([Sections_ objectForKey:section]);
1185 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1186 return hidden == nil || ![hidden boolValue];
1191 /* Delegate Prototypes {{{ */
1195 @interface NSObject (ProgressDelegate)
1198 @protocol ProgressDelegate
1199 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1200 - (void) setProgressTitle:(NSString *)title;
1201 - (void) setProgressPercent:(float)percent;
1202 - (void) startProgress;
1203 - (void) addProgressOutput:(NSString *)output;
1204 - (bool) isCancelling:(size_t)received;
1207 @protocol ConfigurationDelegate
1208 - (void) repairWithSelector:(SEL)selector;
1209 - (void) setConfigurationData:(NSString *)data;
1212 @class PackageController;
1214 @protocol CydiaDelegate
1215 - (void) setPackageController:(PackageController *)view;
1216 - (void) clearPackage:(Package *)package;
1217 - (void) installPackage:(Package *)package;
1218 - (void) installPackages:(NSArray *)packages;
1219 - (void) removePackage:(Package *)package;
1220 - (void) beginUpdate;
1222 - (void) distUpgrade;
1224 - (void) updateData;
1226 - (void) showSettings;
1227 - (UIProgressHUD *) addProgressHUD;
1228 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1229 - (CYViewController *) pageForPackage:(NSString *)name;
1230 - (PackageController *) packageController;
1231 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1235 /* Status Delegation {{{ */
1237 public pkgAcquireStatus
1240 _transient NSObject<ProgressDelegate> *delegate_;
1248 void setDelegate(id delegate) {
1249 delegate_ = delegate;
1252 NSObject<ProgressDelegate> *getDelegate() const {
1256 virtual bool MediaChange(std::string media, std::string drive) {
1260 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1263 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1264 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1265 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1268 virtual void Done(pkgAcquire::ItemDesc &item) {
1271 virtual void Fail(pkgAcquire::ItemDesc &item) {
1273 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1274 item.Owner->Status == pkgAcquire::Item::StatDone
1278 std::string &error(item.Owner->ErrorText);
1282 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1283 NSArray *fields([description componentsSeparatedByString:@" "]);
1284 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1286 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1287 withObject:[NSArray arrayWithObjects:
1288 [NSString stringWithUTF8String:error.c_str()],
1295 virtual bool Pulse(pkgAcquire *Owner) {
1296 bool value = pkgAcquireStatus::Pulse(Owner);
1299 double(CurrentBytes + CurrentItems) /
1300 double(TotalBytes + TotalItems)
1303 [delegate_ setProgressPercent:percent];
1304 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1307 virtual void Start() {
1308 [delegate_ startProgress];
1311 virtual void Stop() {
1315 /* Progress Delegation {{{ */
1320 _transient id<ProgressDelegate> delegate_;
1324 virtual void Update() {
1325 /*if (abs(Percent - percent_) > 2)
1326 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1330 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1331 [delegate_ setProgressPercent:(Percent / 100)];*/
1341 void setDelegate(id delegate) {
1342 delegate_ = delegate;
1345 id getDelegate() const {
1349 virtual void Done() {
1351 //[delegate_ setProgressPercent:1];
1356 /* Database Interface {{{ */
1357 typedef std::map< unsigned long, _H<Source> > SourceMap;
1359 @interface Database : NSObject {
1365 pkgCacheFile cache_;
1366 pkgDepCache::Policy *policy_;
1367 pkgRecords *records_;
1368 pkgProblemResolver *resolver_;
1369 pkgAcquire *fetcher_;
1371 SPtr<pkgPackageManager> manager_;
1372 pkgSourceList *list_;
1375 NSMutableArray *packages_;
1377 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1386 + (Database *) sharedInstance;
1389 - (void) _readCydia:(NSNumber *)fd;
1390 - (void) _readStatus:(NSNumber *)fd;
1391 - (void) _readOutput:(NSNumber *)fd;
1395 - (Package *) packageWithName:(NSString *)name;
1397 - (pkgCacheFile &) cache;
1398 - (pkgDepCache::Policy *) policy;
1399 - (pkgRecords *) records;
1400 - (pkgProblemResolver *) resolver;
1401 - (pkgAcquire &) fetcher;
1402 - (pkgSourceList &) list;
1403 - (NSArray *) packages;
1404 - (NSArray *) sources;
1405 - (void) reloadData;
1413 - (void) setVisible;
1415 - (void) updateWithStatus:(Status &)status;
1417 - (void) setDelegate:(id)delegate;
1418 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1421 /* Delegate Helpers {{{ */
1422 @implementation NSObject (ProgressDelegate)
1424 - (void) _setProgressErrorPackage:(NSArray *)args {
1425 [self performSelector:@selector(setProgressError:forPackage:)
1426 withObject:[args objectAtIndex:0]
1427 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1431 - (void) _setProgressErrorTitle:(NSArray *)args {
1432 [self performSelector:@selector(setProgressError:withTitle:)
1433 withObject:[args objectAtIndex:0]
1434 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1438 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1439 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1440 withObject:[NSArray arrayWithObjects:error, title, nil]
1445 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1446 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1448 [self performSelector:@selector(setProgressError:withTitle:)
1450 withObject:(package == nil ? id : [package name])
1457 /* Source Class {{{ */
1458 @interface Source : NSObject {
1459 CYString depiction_;
1460 CYString description_;
1466 CYString distribution_;
1471 NSString *authority_;
1473 CYString defaultIcon_;
1475 NSDictionary *record_;
1479 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1481 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1483 - (NSString *) depictionForPackage:(NSString *)package;
1484 - (NSString *) supportForPackage:(NSString *)package;
1486 - (NSDictionary *) record;
1490 - (NSString *) distribution;
1491 - (NSString *) type;
1493 - (NSString *) host;
1495 - (NSString *) name;
1496 - (NSString *) description;
1497 - (NSString *) label;
1498 - (NSString *) origin;
1499 - (NSString *) version;
1501 - (NSString *) defaultIcon;
1505 @implementation Source
1509 distribution_.clear();
1512 description_.clear();
1518 defaultIcon_.clear();
1520 if (record_ != nil) {
1530 if (authority_ != nil) {
1531 [authority_ release];
1541 + (NSArray *) _attributeKeys {
1542 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1545 - (NSArray *) attributeKeys {
1546 return [[self class] _attributeKeys];
1549 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1550 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1553 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1556 trusted_ = index->IsTrusted();
1558 uri_.set(pool, index->GetURI());
1559 distribution_.set(pool, index->GetDist());
1560 type_.set(pool, index->GetType());
1562 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1563 if (dindex != NULL) {
1565 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1568 pkgTagFile tags(&fd);
1570 pkgTagSection section;
1577 {"default-icon", &defaultIcon_},
1578 {"depiction", &depiction_},
1579 {"description", &description_},
1581 {"origin", &origin_},
1582 {"support", &support_},
1583 {"version", &version_},
1586 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1587 const char *start, *end;
1589 if (section.Find(names[i].name_, start, end)) {
1590 CYString &value(*names[i].value_);
1591 value.set(pool, start, end - start);
1597 record_ = [Sources_ objectForKey:[self key]];
1599 record_ = [record_ retain];
1601 NSURL *url([NSURL URLWithString:uri_]);
1605 host_ = [[host_ lowercaseString] retain];
1610 authority_ = [url path];
1612 if (authority_ != nil)
1613 authority_ = [authority_ retain];
1616 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1617 if ((self = [super init]) != nil) {
1618 [self setMetaIndex:index inPool:pool];
1622 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1623 NSDictionary *lhr = [self record];
1624 NSDictionary *rhr = [source record];
1627 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1629 NSString *lhs = [self name];
1630 NSString *rhs = [source name];
1632 if ([lhs length] != 0 && [rhs length] != 0) {
1633 unichar lhc = [lhs characterAtIndex:0];
1634 unichar rhc = [rhs characterAtIndex:0];
1636 if (isalpha(lhc) && !isalpha(rhc))
1637 return NSOrderedAscending;
1638 else if (!isalpha(lhc) && isalpha(rhc))
1639 return NSOrderedDescending;
1642 return [lhs compare:rhs options:LaxCompareOptions_];
1645 - (NSString *) depictionForPackage:(NSString *)package {
1646 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1649 - (NSString *) supportForPackage:(NSString *)package {
1650 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1653 - (NSDictionary *) record {
1661 - (NSString *) uri {
1665 - (NSString *) distribution {
1666 return distribution_;
1669 - (NSString *) type {
1673 - (NSString *) key {
1674 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1677 - (NSString *) host {
1681 - (NSString *) name {
1682 return origin_.empty() ? authority_ : origin_;
1685 - (NSString *) description {
1686 return description_;
1689 - (NSString *) label {
1690 return label_.empty() ? authority_ : label_;
1693 - (NSString *) origin {
1697 - (NSString *) version {
1701 - (NSString *) defaultIcon {
1702 return defaultIcon_;
1707 /* Relationship Class {{{ */
1708 @interface Relationship : NSObject {
1713 - (NSString *) type;
1715 - (NSString *) name;
1719 @implementation Relationship
1727 - (NSString *) type {
1735 - (NSString *) name {
1742 /* Package Class {{{ */
1743 @interface Package : NSObject {
1747 pkgCache::VerIterator version_;
1748 pkgCache::PkgIterator iterator_;
1749 _transient Database *database_;
1750 pkgCache::VerFileIterator file_;
1757 NSString *section$_;
1764 CYString installed_;
1770 CYString depiction_;
1781 NSMutableArray *tags_;
1784 NSArray *relationships_;
1786 NSMutableDictionary *metadata_;
1787 _transient NSDate *firstSeen_;
1788 _transient NSDate *lastSeen_;
1792 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1793 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1795 - (pkgCache::PkgIterator) iterator;
1798 - (NSString *) section;
1799 - (NSString *) simpleSection;
1801 - (NSString *) longSection;
1802 - (NSString *) shortSection;
1806 - (Address *) maintainer;
1808 - (NSString *) longDescription;
1809 - (NSString *) shortDescription;
1812 - (NSMutableDictionary *) metadata;
1814 - (BOOL) subscribed;
1817 - (NSString *) latest;
1818 - (NSString *) installed;
1819 - (BOOL) uninstalled;
1822 - (BOOL) upgradableAndEssential:(BOOL)essential;
1825 - (BOOL) unfiltered;
1829 - (BOOL) halfConfigured;
1830 - (BOOL) halfInstalled;
1832 - (NSString *) mode;
1834 - (void) setVisible;
1837 - (NSString *) name;
1839 - (NSString *) homepage;
1840 - (NSString *) depiction;
1841 - (Address *) author;
1843 - (NSString *) support;
1845 - (NSArray *) files;
1846 - (NSArray *) relationships;
1847 - (NSArray *) warnings;
1848 - (NSArray *) applications;
1850 - (Source *) source;
1851 - (NSString *) role;
1853 - (BOOL) matches:(NSString *)text;
1855 - (bool) hasSupportingRole;
1856 - (BOOL) hasTag:(NSString *)tag;
1857 - (NSString *) primaryPurpose;
1858 - (NSArray *) purposes;
1859 - (bool) isCommercial;
1861 - (CYString &) cyname;
1863 - (uint32_t) compareBySection:(NSArray *)sections;
1865 - (uint32_t) compareForChanges;
1870 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1871 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1872 - (bool) isInstalledAndVisible:(NSNumber *)number;
1873 - (bool) isVisibleInSection:(NSString *)section;
1874 - (bool) isVisibleInSource:(Source *)source;
1878 uint32_t PackageChangesRadix(Package *self, void *) {
1883 uint32_t timestamp : 30;
1884 uint32_t ignored : 1;
1885 uint32_t upgradable : 1;
1889 bool upgradable([self upgradableAndEssential:YES]);
1890 value.bits.upgradable = upgradable ? 1 : 0;
1893 value.bits.timestamp = 0;
1894 value.bits.ignored = [self ignored] ? 0 : 1;
1895 value.bits.upgradable = 1;
1897 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1898 value.bits.ignored = 0;
1899 value.bits.upgradable = 0;
1902 return _not(uint32_t) - value.key;
1905 _finline static void Stifle(uint8_t &value) {
1908 uint32_t PackagePrefixRadix(Package *self, void *context) {
1909 size_t offset(reinterpret_cast<size_t>(context));
1910 CYString &name([self cyname]);
1912 size_t size(name.size());
1915 char *text(name.data());
1918 if (!isdigit(text[0]))
1922 while (size != digits && isdigit(text[digits]))
1932 if (offset == 0 && zeros != 0) {
1933 memset(data, '0', zeros);
1934 memcpy(data + zeros, text, 4 - zeros);
1936 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1937 if (size <= offset - zeros)
1940 text += offset - zeros;
1941 size -= offset - zeros;
1944 memcpy(data, text, 4);
1946 memcpy(data, text, size);
1947 memset(data + size, 0, 4 - size);
1950 for (size_t i(0); i != 4; ++i)
1951 if (isalpha(data[i]))
1959 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1961 /* XXX: ntohl may be more honest */
1962 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1965 CYString &(*PackageName)(Package *self, SEL sel);
1967 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1968 _profile(PackageNameCompare)
1969 CYString &lhi(PackageName(lhs, @selector(cyname)));
1970 CYString &rhi(PackageName(rhs, @selector(cyname)));
1971 CFStringRef lhn(lhi), rhn(rhi);
1974 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1975 else if (rhn == NULL)
1976 return NSOrderedDescending;
1978 _profile(PackageNameCompare$NumbersLast)
1979 if (!lhi.empty() && !rhi.empty()) {
1980 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1981 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1982 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1983 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1984 return lha ? NSOrderedAscending : NSOrderedDescending;
1988 CFIndex length = CFStringGetLength(lhn);
1990 _profile(PackageNameCompare$Compare)
1991 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1996 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1997 return PackageNameCompare(*lhs, *rhs, context);
2000 struct PackageNameOrdering :
2001 std::binary_function<Package *, Package *, bool>
2003 _finline bool operator ()(Package *lhs, Package *rhs) const {
2004 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2008 @implementation Package
2010 - (NSString *) description {
2011 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2017 if (section$_ != nil)
2018 [section$_ release];
2023 if (sponsor$_ != nil)
2024 [sponsor$_ release];
2025 if (author$_ != nil)
2032 if (relationships_ != nil)
2033 [relationships_ release];
2034 if (metadata_ != nil)
2035 [metadata_ release];
2040 + (NSString *) webScriptNameForSelector:(SEL)selector {
2041 if (selector == @selector(hasTag:))
2047 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2048 return [self webScriptNameForSelector:selector] == nil;
2051 + (NSArray *) _attributeKeys {
2052 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];
2055 - (NSArray *) attributeKeys {
2056 return [[self class] _attributeKeys];
2059 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2060 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2070 _profile(Package$parse)
2071 pkgRecords::Parser *parser;
2073 _profile(Package$parse$Lookup)
2074 parser = &[database_ records]->Lookup(file_);
2079 _profile(Package$parse$Find)
2085 {"depiction", &depiction_},
2086 {"homepage", &homepage_},
2087 {"website", &website},
2089 {"support", &support_},
2090 {"sponsor", &sponsor_},
2091 {"author", &author_},
2094 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2095 const char *start, *end;
2097 if (parser->Find(names[i].name_, start, end)) {
2098 CYString &value(*names[i].value_);
2099 _profile(Package$parse$Value)
2100 value.set(pool_, start, end - start);
2106 _profile(Package$parse$Tagline)
2107 const char *start, *end;
2108 if (parser->ShortDesc(start, end)) {
2109 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2112 while (stop != start && stop[-1] == '\r')
2114 tagline_.set(pool_, start, stop - start);
2118 _profile(Package$parse$Retain)
2119 if (homepage_.empty())
2120 homepage_ = website;
2121 if (homepage_ == depiction_)
2127 - (void) setVisible {
2128 visible_ = required_ && [self unfiltered];
2131 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2132 if ((self = [super init]) != nil) {
2133 _profile(Package$initWithVersion)
2134 era_ = [database era];
2138 iterator_ = version.ParentPkg();
2139 database_ = database;
2141 _profile(Package$initWithVersion$Latest)
2142 latest_ = (NSString *) StripVersion(version_.VerStr());
2145 pkgCache::VerIterator current;
2146 _profile(Package$initWithVersion$Versions)
2147 current = iterator_.CurrentVer();
2149 installed_.set(pool_, StripVersion_(current.VerStr()));
2151 if (!version_.end())
2152 file_ = version_.FileList();
2154 pkgCache &cache([database_ cache]);
2155 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2159 _profile(Package$initWithVersion$Name)
2160 id_.set(pool_, iterator_.Name());
2161 name_.set(pool, iterator_.Display());
2164 _profile(Package$lowercaseString)
2165 char *data(id_.data());
2166 for (size_t i(0), e(id_.size()); i != e; ++i)
2167 // XXX: do not use tolower() as this is not locale-specific? :(
2172 _profile(Package$initWithVersion$Source)
2173 source_ = [database_ getSource:file_.File()];
2182 _profile(Package$initWithVersion$Tags)
2183 pkgCache::TagIterator tag(iterator_.TagList());
2185 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2187 const char *name(tag.Name());
2188 [tags_ addObject:(NSString *)CFCString(name)];
2189 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2190 role_ = (NSString *) CFCString(name + 6);
2191 if (required_ && strncmp(name, "require::", 9) == 0 && (
2196 } while (!tag.end());
2200 bool changed(false);
2202 _profile(Package$initWithVersion$Metadata)
2203 metadata_ = [Packages_ objectForKey:id_];
2205 if (metadata_ == nil) {
2208 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2209 firstSeen_, @"FirstSeen",
2210 latest_, @"LastVersion",
2215 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2216 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2218 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2219 subscribed_ = [subscribed boolValue];
2221 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2223 if (firstSeen_ == nil) {
2224 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2225 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2229 if (version == nil) {
2230 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2232 } else if (![version isEqualToString:latest_]) {
2233 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2235 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2240 metadata_ = [metadata_ retain];
2243 [Packages_ setObject:metadata_ forKey:id_];
2248 _profile(Package$initWithVersion$Section)
2249 section_.set(pool_, iterator_.Section());
2252 obsolete_ = [self hasTag:@"cydia::obsolete"];
2253 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2258 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2259 pkgCache::VerIterator version;
2261 _profile(Package$packageWithIterator$GetCandidateVer)
2262 version = [database policy]->GetCandidateVer(iterator);
2268 return [[[Package alloc]
2269 initWithVersion:version
2276 - (pkgCache::PkgIterator) iterator {
2280 - (NSString *) section {
2281 if (section$_ == nil) {
2282 if (section_.empty())
2285 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2286 NSString *name(section_);
2289 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2290 if (NSString *rename = [value objectForKey:@"Rename"]) {
2295 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2299 - (NSString *) simpleSection {
2300 if (NSString *section = [self section])
2301 return Simplify(section);
2306 - (NSString *) longSection {
2307 return LocalizeSection([self section]);
2310 - (NSString *) shortSection {
2311 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2314 - (NSString *) uri {
2317 pkgIndexFile *index;
2318 pkgCache::PkgFileIterator file(file_.File());
2319 if (![database_ list].FindIndex(file, index))
2321 return [NSString stringWithUTF8String:iterator_->Path];
2322 //return [NSString stringWithUTF8String:file.Site()];
2323 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2327 - (Address *) maintainer {
2330 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2331 const std::string &maintainer(parser->Maintainer());
2332 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2336 return version_.end() ? 0 : version_->InstalledSize;
2339 - (NSString *) longDescription {
2340 @synchronized (database_) {
2341 if ([database_ era] != era_ || file_.end())
2344 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2345 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2347 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2348 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2349 if ([lines count] < 2)
2352 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2353 for (size_t i(1), e([lines count]); i != e; ++i) {
2354 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2355 [trimmed addObject:trim];
2358 return [trimmed componentsJoinedByString:@"\n"];
2361 - (NSString *) shortDescription {
2366 _profile(Package$index)
2367 CFStringRef name((CFStringRef) [self name]);
2368 if (CFStringGetLength(name) == 0)
2370 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2371 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2373 return toupper(character);
2377 - (NSMutableDictionary *) metadata {
2382 if (subscribed_ && lastSeen_ != nil)
2387 - (BOOL) subscribed {
2392 NSDictionary *metadata([self metadata]);
2393 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2394 return [ignored boolValue];
2399 - (NSString *) latest {
2403 - (NSString *) installed {
2407 - (BOOL) uninstalled {
2408 return installed_.empty();
2412 return !version_.end();
2415 - (BOOL) upgradableAndEssential:(BOOL)essential {
2416 _profile(Package$upgradableAndEssential)
2417 pkgCache::VerIterator current(iterator_.CurrentVer());
2419 return essential && essential_ && visible_;
2421 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2425 - (BOOL) essential {
2430 return [database_ cache][iterator_].InstBroken();
2433 - (BOOL) unfiltered {
2434 NSString *section([self section]);
2435 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2443 unsigned char current(iterator_->CurrentState);
2444 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2447 - (BOOL) halfConfigured {
2448 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2451 - (BOOL) halfInstalled {
2452 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2456 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2457 return state.Mode != pkgDepCache::ModeKeep;
2460 - (NSString *) mode {
2461 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2463 switch (state.Mode) {
2464 case pkgDepCache::ModeDelete:
2465 if ((state.iFlags & pkgDepCache::Purge) != 0)
2469 case pkgDepCache::ModeKeep:
2470 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2471 return @"REINSTALL";
2472 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2476 case pkgDepCache::ModeInstall:
2477 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2478 return @"REINSTALL";
2479 else*/ switch (state.Status) {
2481 return @"DOWNGRADE";
2487 return @"NEW_INSTALL";
2498 - (NSString *) name {
2499 return name_.empty() ? id_ : name_;
2502 - (UIImage *) icon {
2503 NSString *section = [self simpleSection];
2507 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2508 // XXX: correct escaping
2509 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2510 if (icon == nil) if (section != nil)
2511 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2512 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2513 if ([dicon hasPrefix:@"file:///"])
2514 // XXX: correct escaping
2515 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2517 icon = [UIImage applicationImageNamed:@"unknown.png"];
2521 - (NSString *) homepage {
2525 - (NSString *) depiction {
2526 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2529 - (Address *) sponsor {
2530 if (sponsor$_ == nil) {
2531 if (sponsor_.empty())
2533 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2537 - (Address *) author {
2538 if (author$_ == nil) {
2539 if (author_.empty())
2541 author$_ = [[Address addressWithString:author_] retain];
2545 - (NSString *) support {
2546 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2549 - (NSArray *) files {
2550 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2551 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2554 fin.open([path UTF8String]);
2559 while (std::getline(fin, line))
2560 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2565 - (NSArray *) relationships {
2566 return relationships_;
2569 - (NSArray *) warnings {
2570 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2571 const char *name(iterator_.Name());
2573 size_t length(strlen(name));
2574 if (length < 2) invalid:
2575 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2576 else for (size_t i(0); i != length; ++i)
2578 /* XXX: technically this is not allowed */
2579 (name[i] < 'A' || name[i] > 'Z') &&
2580 (name[i] < 'a' || name[i] > 'z') &&
2581 (name[i] < '0' || name[i] > '9') &&
2582 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2585 if (strcmp(name, "cydia") != 0) {
2588 bool _private = false;
2591 bool repository = [[self section] isEqualToString:@"Repositories"];
2593 if (NSArray *files = [self files])
2594 for (NSString *file in files)
2595 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2597 else if (!user && [file isEqualToString:@"/User"])
2599 else if (!_private && [file isEqualToString:@"/private"])
2601 else if (!stash && [file isEqualToString:@"/var/stash"])
2604 /* XXX: this is not sensitive enough. only some folders are valid. */
2605 if (cydia && !repository)
2606 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2608 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2610 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2612 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2615 return [warnings count] == 0 ? nil : warnings;
2618 - (NSArray *) applications {
2619 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2621 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2623 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2624 if (NSArray *files = [self files])
2625 for (NSString *file in files)
2626 if (application_r(file)) {
2627 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2628 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2629 if ([id isEqualToString:me])
2632 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2634 display = application_r[1];
2636 NSString *bundle([file stringByDeletingLastPathComponent]);
2637 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2638 if (icon == nil || [icon length] == 0)
2640 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2642 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2643 [applications addObject:application];
2645 [application addObject:id];
2646 [application addObject:display];
2647 [application addObject:url];
2650 return [applications count] == 0 ? nil : applications;
2653 - (Source *) source {
2655 @synchronized (database_) {
2656 if ([database_ era] != era_ || file_.end())
2659 source_ = [database_ getSource:file_.File()];
2671 - (NSString *) role {
2675 - (BOOL) matches:(NSString *)text {
2681 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2682 if (range.location != NSNotFound)
2685 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2686 if (range.location != NSNotFound)
2689 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2690 if (range.location != NSNotFound)
2696 - (bool) hasSupportingRole {
2699 if ([role_ isEqualToString:@"enduser"])
2701 if ([Role_ isEqualToString:@"User"])
2703 if ([role_ isEqualToString:@"hacker"])
2705 if ([Role_ isEqualToString:@"Hacker"])
2707 if ([role_ isEqualToString:@"developer"])
2709 if ([Role_ isEqualToString:@"Developer"])
2714 - (BOOL) hasTag:(NSString *)tag {
2715 return tags_ == nil ? NO : [tags_ containsObject:tag];
2718 - (NSString *) primaryPurpose {
2719 for (NSString *tag in tags_)
2720 if ([tag hasPrefix:@"purpose::"])
2721 return [tag substringFromIndex:9];
2725 - (NSArray *) purposes {
2726 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2727 for (NSString *tag in tags_)
2728 if ([tag hasPrefix:@"purpose::"])
2729 [purposes addObject:[tag substringFromIndex:9]];
2730 return [purposes count] == 0 ? nil : purposes;
2733 - (bool) isCommercial {
2734 return [self hasTag:@"cydia::commercial"];
2737 - (CYString &) cyname {
2738 return name_.empty() ? id_ : name_;
2741 - (uint32_t) compareBySection:(NSArray *)sections {
2742 NSString *section([self section]);
2743 for (size_t i(0), e([sections count]); i != e; ++i) {
2744 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2748 return _not(uint32_t);
2751 - (uint32_t) compareForChanges {
2756 uint32_t timestamp : 30;
2757 uint32_t ignored : 1;
2758 uint32_t upgradable : 1;
2762 bool upgradable([self upgradableAndEssential:YES]);
2763 value.bits.upgradable = upgradable ? 1 : 0;
2766 value.bits.timestamp = 0;
2767 value.bits.ignored = [self ignored] ? 0 : 1;
2768 value.bits.upgradable = 1;
2770 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2771 value.bits.ignored = 0;
2772 value.bits.upgradable = 0;
2775 return _not(uint32_t) - value.key;
2779 pkgProblemResolver *resolver = [database_ resolver];
2780 resolver->Clear(iterator_);
2781 resolver->Protect(iterator_);
2785 pkgProblemResolver *resolver = [database_ resolver];
2786 resolver->Clear(iterator_);
2787 resolver->Protect(iterator_);
2788 pkgCacheFile &cache([database_ cache]);
2789 cache->MarkInstall(iterator_, false);
2790 pkgDepCache::StateCache &state((*cache)[iterator_]);
2791 if (!state.Install())
2792 cache->SetReInstall(iterator_, true);
2796 pkgProblemResolver *resolver = [database_ resolver];
2797 resolver->Clear(iterator_);
2798 resolver->Protect(iterator_);
2799 resolver->Remove(iterator_);
2800 [database_ cache]->MarkDelete(iterator_, true);
2803 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2804 _profile(Package$isUnfilteredAndSearchedForBy)
2807 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2808 value &= [self unfiltered];
2811 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2812 value &= [self matches:search];
2819 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2820 if ([search length] == 0)
2823 _profile(Package$isUnfilteredAndSelectedForBy)
2826 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2827 value &= [self unfiltered];
2830 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2831 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2838 - (bool) isInstalledAndVisible:(NSNumber *)number {
2839 return (![number boolValue] || [self visible]) && ![self uninstalled];
2842 - (bool) isVisibleInSection:(NSString *)name {
2843 NSString *section = [self section];
2848 section == nil && [name length] == 0 ||
2849 [name isEqualToString:section]
2853 - (bool) isVisibleInSource:(Source *)source {
2854 return [self source] == source && [self visible];
2859 /* Section Class {{{ */
2860 @interface Section : NSObject {
2865 NSString *localized_;
2868 - (NSComparisonResult) compareByLocalized:(Section *)section;
2869 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2870 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2871 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2872 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2873 - (NSString *) name;
2880 - (void) addToCount;
2882 - (void) setCount:(size_t)count;
2883 - (NSString *) localized;
2887 @implementation Section
2891 if (localized_ != nil)
2892 [localized_ release];
2896 - (NSComparisonResult) compareByLocalized:(Section *)section {
2897 NSString *lhs(localized_);
2898 NSString *rhs([section localized]);
2900 /*if ([lhs length] != 0 && [rhs length] != 0) {
2901 unichar lhc = [lhs characterAtIndex:0];
2902 unichar rhc = [rhs characterAtIndex:0];
2904 if (isalpha(lhc) && !isalpha(rhc))
2905 return NSOrderedAscending;
2906 else if (!isalpha(lhc) && isalpha(rhc))
2907 return NSOrderedDescending;
2910 return [lhs compare:rhs options:LaxCompareOptions_];
2913 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2914 if ((self = [self initWithName:name localize:NO]) != nil) {
2915 if (localized != nil)
2916 localized_ = [localized retain];
2920 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2921 return [self initWithName:name row:0 localize:localize];
2924 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2925 if ((self = [super init]) != nil) {
2926 name_ = [name retain];
2930 localized_ = [LocalizeSection(name_) retain];
2934 /* XXX: localize the index thingees */
2935 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2936 if ((self = [super init]) != nil) {
2937 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2943 - (NSString *) name {
2963 - (void) addToCount {
2967 - (void) setCount:(size_t)count {
2971 - (NSString *) localized {
2978 static NSString *Colon_;
2979 static NSString *Error_;
2980 static NSString *Warning_;
2982 /* Database Implementation {{{ */
2983 @implementation Database
2985 + (Database *) sharedInstance {
2986 static Database *instance;
2987 if (instance == nil)
2988 instance = [[Database alloc] init];
2998 NSRecycleZone(zone_);
2999 // XXX: malloc_destroy_zone(zone_);
3000 apr_pool_destroy(pool_);
3004 - (void) _readCydia:(NSNumber *)fd { _pooled
3005 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3006 std::istream is(&ib);
3009 static Pcre finish_r("^finish:([^:]*)$");
3011 while (std::getline(is, line)) {
3012 const char *data(line.c_str());
3013 size_t size = line.size();
3014 lprintf("C:%s\n", data);
3016 if (finish_r(data, size)) {
3017 NSString *finish = finish_r[1];
3018 int index = [Finishes_ indexOfObject:finish];
3019 if (index != INT_MAX && index > Finish_)
3027 - (void) _readStatus:(NSNumber *)fd { _pooled
3028 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3029 std::istream is(&ib);
3032 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3033 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3035 while (std::getline(is, line)) {
3036 const char *data(line.c_str());
3037 size_t size(line.size());
3038 lprintf("S:%s\n", data);
3040 if (conffile_r(data, size)) {
3041 [delegate_ setConfigurationData:conffile_r[1]];
3042 } else if (strncmp(data, "status: ", 8) == 0) {
3043 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3044 [delegate_ setProgressTitle:string];
3045 } else if (pmstatus_r(data, size)) {
3046 std::string type([pmstatus_r[1] UTF8String]);
3047 NSString *id = pmstatus_r[2];
3049 float percent([pmstatus_r[3] floatValue]);
3050 [delegate_ setProgressPercent:(percent / 100)];
3052 NSString *string = pmstatus_r[4];
3054 if (type == "pmerror")
3055 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3056 withObject:[NSArray arrayWithObjects:string, id, nil]
3059 else if (type == "pmstatus") {
3060 [delegate_ setProgressTitle:string];
3061 } else if (type == "pmconffile")
3062 [delegate_ setConfigurationData:string];
3064 lprintf("E:unknown pmstatus\n");
3066 lprintf("E:unknown status\n");
3072 - (void) _readOutput:(NSNumber *)fd { _pooled
3073 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3074 std::istream is(&ib);
3077 while (std::getline(is, line)) {
3078 lprintf("O:%s\n", line.c_str());
3079 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3089 - (Package *) packageWithName:(NSString *)name {
3090 @synchronized (self) {
3091 if (static_cast<pkgDepCache *>(cache_) == NULL)
3093 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3094 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3098 if ((self = [super init]) != nil) {
3105 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3106 apr_pool_create(&pool_, NULL);
3108 packages_ = [[NSMutableArray alloc] init];
3112 _assert(pipe(fds) != -1);
3115 _config->Set("APT::Keep-Fds::", cydiafd_);
3116 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3119 detachNewThreadSelector:@selector(_readCydia:)
3121 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3124 _assert(pipe(fds) != -1);
3128 detachNewThreadSelector:@selector(_readStatus:)
3130 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3133 _assert(pipe(fds) != -1);
3134 _assert(dup2(fds[0], 0) != -1);
3135 _assert(close(fds[0]) != -1);
3137 input_ = fdopen(fds[1], "a");
3139 _assert(pipe(fds) != -1);
3140 _assert(dup2(fds[1], 1) != -1);
3141 _assert(close(fds[1]) != -1);
3144 detachNewThreadSelector:@selector(_readOutput:)
3146 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3151 - (pkgCacheFile &) cache {
3155 - (pkgDepCache::Policy *) policy {
3159 - (pkgRecords *) records {
3163 - (pkgProblemResolver *) resolver {
3167 - (pkgAcquire &) fetcher {
3171 - (pkgSourceList &) list {
3175 - (NSArray *) packages {
3179 - (NSArray *) sources {
3180 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3181 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3182 [sources addObject:i->second];
3186 - (NSArray *) issues {
3187 if (cache_->BrokenCount() == 0)
3190 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3192 for (Package *package in packages_) {
3193 if (![package broken])
3195 pkgCache::PkgIterator pkg([package iterator]);
3197 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3198 [entry addObject:[package name]];
3199 [issues addObject:entry];
3201 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3205 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3206 pkgCache::DepIterator start;
3207 pkgCache::DepIterator end;
3208 dep.GlobOr(start, end); // ++dep
3210 if (!cache_->IsImportantDep(end))
3212 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3215 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3216 [entry addObject:failure];
3217 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3219 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3220 if (Package *package = [self packageWithName:name])
3221 name = [package name];
3222 [failure addObject:name];
3224 pkgCache::PkgIterator target(start.TargetPkg());
3225 if (target->ProvidesList != 0)
3226 [failure addObject:@"?"];
3228 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3230 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3231 else if (!cache_[target].CandidateVerIter(cache_).end())
3232 [failure addObject:@"-"];
3233 else if (target->ProvidesList == 0)
3234 [failure addObject:@"!"];
3236 [failure addObject:@"%"];
3240 if (start.TargetVer() != 0)
3241 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3252 - (bool) popErrorWithTitle:(NSString *)title {
3254 std::string message;
3256 while (!_error->empty()) {
3258 bool warning(!_error->PopMessage(error));
3262 size_t size(error.size());
3263 if (size == 0 || error[size - 1] != '\n')
3265 error.resize(size - 1);
3267 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3269 if (!message.empty())
3274 if (fatal && !message.empty())
3275 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3280 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3281 return [self popErrorWithTitle:title] || !success;
3284 - (void) reloadData { CYPoolStart() {
3285 @synchronized (self) {
3288 [packages_ removeAllObjects];
3314 apr_pool_clear(pool_);
3315 NSRecycleZone(zone_);
3317 int chk(creat("/tmp/cydia.chk", 0644));
3321 NSString *title(UCLocalize("DATABASE"));
3324 if (!cache_.Open(progress_, true)) { pop:
3326 bool warning(!_error->PopMessage(error));
3327 lprintf("cache_.Open():[%s]\n", error.c_str());
3329 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3330 [delegate_ repairWithSelector:@selector(configure)];
3331 else if (error == "The package lists or status file could not be parsed or opened.")
3332 [delegate_ repairWithSelector:@selector(update)];
3333 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3334 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3335 // else if (error == "The list of sources could not be read.")
3337 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3346 unlink("/tmp/cydia.chk");
3348 now_ = [[NSDate date] retain];
3350 policy_ = new pkgDepCache::Policy();
3351 records_ = new pkgRecords(cache_);
3352 resolver_ = new pkgProblemResolver(cache_);
3353 fetcher_ = new pkgAcquire(&status_);
3356 list_ = new pkgSourceList();
3357 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3360 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3361 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3365 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3368 if (cache_->BrokenCount() != 0) {
3369 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3372 if (cache_->BrokenCount() != 0) {
3373 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3377 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3383 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3384 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3385 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3386 // XXX: this could be more intelligent
3387 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3388 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3390 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3397 /*std::vector<Package *> packages;
3398 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3399 [packages_ release];
3404 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3405 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3406 //packages.push_back(package);
3407 [packages_ addObject:package];
3411 /*if (packages.empty())
3412 packages_ = [[NSArray alloc] init];
3414 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3417 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3418 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3419 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3427 /*if (!packages.empty())
3428 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3429 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3431 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3433 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3435 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3442 - (void) configure {
3443 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3444 system([dpkg UTF8String]);
3448 // XXX: I don't remember this condition
3453 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3455 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3457 if ([self popErrorWithTitle:title])
3461 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3464 public pkgArchiveCleaner
3467 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3472 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3479 fetcher_->Shutdown();
3481 pkgRecords records(cache_);
3483 lock_ = new FileFd();
3484 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3486 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3488 if ([self popErrorWithTitle:title])
3492 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3495 manager_ = (_system->CreatePM(cache_));
3496 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3503 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3505 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3507 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3509 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3510 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3513 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3518 bool failed = false;
3519 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3520 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3522 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3525 std::string uri = (*item)->DescURI();
3526 std::string error = (*item)->ErrorText;
3528 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3531 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3532 withObject:[NSArray arrayWithObjects:
3533 [NSString stringWithUTF8String:error.c_str()],
3545 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3547 if (_error->PendingError()) {
3552 if (result == pkgPackageManager::Failed) {
3557 if (result != pkgPackageManager::Completed) {
3562 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3564 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3566 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3567 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3570 if (![before isEqualToArray:after])
3575 NSString *title(UCLocalize("UPGRADE"));
3576 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3582 [self updateWithStatus:status_];
3585 - (void) setVisible {
3586 for (Package *package in packages_)
3587 [package setVisible];
3590 - (void) updateWithStatus:(Status &)status {
3591 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3592 NSString *title(UCLocalize("REFRESHING_DATA"));
3595 if (!list.ReadMainList())
3596 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3599 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3600 if ([self popErrorWithTitle:title])
3603 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3604 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3605 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3607 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3611 - (void) setDelegate:(id)delegate {
3612 delegate_ = delegate;
3613 status_.setDelegate(delegate);
3614 progress_.setDelegate(delegate);
3617 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3618 SourceMap::const_iterator i(sources_.find(file->ID));
3619 return i == sources_.end() ? nil : i->second;
3625 /* Confirmation Controller {{{ */
3626 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3627 if (!iterator.end())
3628 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3629 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3631 pkgCache::PkgIterator package(dep.TargetPkg());
3634 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3642 /* Web Scripting {{{ */
3643 @interface CydiaObject : NSObject {
3648 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3651 @implementation CydiaObject
3654 [indirect_ release];
3658 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3659 if ((self = [super init]) != nil) {
3660 indirect_ = [indirect retain];
3664 - (void) setDelegate:(id)delegate {
3665 delegate_ = delegate;
3668 + (NSArray *) _attributeKeys {
3669 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3672 - (NSArray *) attributeKeys {
3673 return [[self class] _attributeKeys];
3676 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3677 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3680 - (NSString *) device {
3681 return [[UIDevice currentDevice] uniqueIdentifier];
3684 #if 0 // XXX: implement!
3685 - (NSString *) mac {
3686 if (![indirect_ promptForSensitive:@"Mac Address"])
3690 - (NSString *) serial {
3691 if (![indirect_ promptForSensitive:@"Serial #"])
3695 - (NSString *) firewire {
3696 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3700 - (NSString *) imei {
3701 if (![indirect_ promptForSensitive:@"IMEI"])
3706 + (NSString *) webScriptNameForSelector:(SEL)selector {
3707 if (selector == @selector(close))
3709 else if (selector == @selector(getInstalledPackages))
3710 return @"getInstalledPackages";
3711 else if (selector == @selector(getPackageById:))
3712 return @"getPackageById";
3713 else if (selector == @selector(installPackages:))
3714 return @"installPackages";
3715 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3716 return @"setButtonImage";
3717 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3718 return @"setButtonTitle";
3719 else if (selector == @selector(setPopupHook:))
3720 return @"setPopupHook";
3721 else if (selector == @selector(setSpecial:))
3722 return @"setSpecial";
3723 else if (selector == @selector(setToken:))
3725 else if (selector == @selector(setViewportWidth:))
3726 return @"setViewportWidth";
3727 else if (selector == @selector(supports:))
3729 else if (selector == @selector(stringWithFormat:arguments:))
3731 else if (selector == @selector(localizedStringForKey:value:table:))
3733 else if (selector == @selector(du:))
3735 else if (selector == @selector(statfs:))
3741 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3742 return [self webScriptNameForSelector:selector] == nil;
3745 - (BOOL) supports:(NSString *)feature {
3746 return [feature isEqualToString:@"window.open"];
3749 - (NSArray *) getInstalledPackages {
3750 NSArray *packages([[Database sharedInstance] packages]);
3751 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3752 for (Package *package in packages)
3753 if ([package installed] != nil)
3754 [installed addObject:package];
3758 - (Package *) getPackageById:(NSString *)id {
3759 Package *package([[Database sharedInstance] packageWithName:id]);
3764 - (NSArray *) statfs:(NSString *)path {
3767 if (path == nil || statfs([path UTF8String], &stat) == -1)
3770 return [NSArray arrayWithObjects:
3771 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3772 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3773 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3777 - (NSNumber *) du:(NSString *)path {
3778 NSNumber *value(nil);
3781 _assert(pipe(fds) != -1);
3783 pid_t pid(ExecFork());
3785 _assert(dup2(fds[1], 1) != -1);
3786 _assert(close(fds[0]) != -1);
3787 _assert(close(fds[1]) != -1);
3788 /* XXX: this should probably not use du */
3789 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3794 _assert(close(fds[1]) != -1);
3796 if (FILE *du = fdopen(fds[0], "r")) {
3798 while (fgets(line, sizeof(line), du) != NULL) {
3799 size_t length(strlen(line));
3800 while (length != 0 && line[length - 1] == '\n')
3801 line[--length] = '\0';
3802 if (char *tab = strchr(line, '\t')) {
3804 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3809 } else _assert(close(fds[0]));
3813 if (waitpid(pid, &status, 0) == -1)
3816 else _assert(false);
3825 - (void) installPackages:(NSArray *)packages {
3826 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3829 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3830 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3833 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3834 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3837 - (void) setSpecial:(id)function {
3838 [indirect_ setSpecial:function];
3841 - (void) setToken:(NSString *)token {
3844 Token_ = [token retain];
3846 [Metadata_ setObject:Token_ forKey:@"Token"];
3850 - (void) setPopupHook:(id)function {
3851 [indirect_ setPopupHook:function];
3854 - (void) setViewportWidth:(float)width {
3855 [indirect_ setViewportWidth:width];
3858 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3859 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3860 unsigned count([arguments count]);
3862 for (unsigned i(0); i != count; ++i)
3863 values[i] = [arguments objectAtIndex:i];
3864 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3867 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3868 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3870 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3872 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3878 /* Cydia Browser Controller {{{ */
3879 @interface CYBrowserController : BrowserController {
3880 CydiaObject *cydia_;
3885 @implementation CYBrowserController
3892 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3895 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3896 [super webView:view didClearWindowObject:window forFrame:frame];
3898 WebDataSource *source([frame dataSource]);
3899 NSURLResponse *response([source response]);
3900 NSURL *url([response URL]);
3901 NSString *scheme([url scheme]);
3903 NSHTTPURLResponse *http;
3904 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3905 http = (NSHTTPURLResponse *) response;
3909 NSDictionary *headers([http allHeaderFields]);
3910 NSString *host([url host]);
3911 [self setHeaders:headers forHost:host];
3914 [host isEqualToString:@"cydia.saurik.com"] ||
3915 [host hasSuffix:@".cydia.saurik.com"] ||
3916 [scheme isEqualToString:@"file"]
3918 [window setValue:cydia_ forKey:@"cydia"];
3921 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3922 if (System_ != NULL)
3923 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3924 if (Machine_ != NULL)
3925 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3927 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3929 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3932 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3933 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3934 [self _setMoreHeaders:copy];
3938 - (void) setDelegate:(id)delegate {
3939 [super setDelegate:delegate];
3940 [cydia_ setDelegate:delegate];
3944 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3945 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3947 WebView *webview([[webview_ _documentView] webView]);
3949 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3951 NSString *application = package == nil ? @"Cydia" : [NSString
3952 stringWithFormat:@"Cydia/%@",
3957 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3959 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3960 if (Product_ != nil)
3961 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3963 [webview setApplicationNameForUserAgent:application];
3970 /* Confirmation {{{ */
3971 @protocol ConfirmationControllerDelegate
3972 - (void) cancelAndClear:(bool)clear;
3973 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3977 @interface ConfirmationController : CYBrowserController {
3978 _transient Database *database_;
3979 UIAlertView *essential_;
3986 - (id) initWithDatabase:(Database *)database;
3990 @implementation ConfirmationController
3997 if (essential_ != nil)
3998 [essential_ release];
4002 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4003 NSString *context([alert context]);
4005 if ([context isEqualToString:@"remove"]) {
4006 if (button == [alert cancelButtonIndex]) {
4007 [self dismissModalViewControllerAnimated:YES];
4008 } else if (button == [alert firstOtherButtonIndex]) {
4011 [delegate_ confirmWithNavigationController:[self navigationController]];
4014 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4015 } else if ([context isEqualToString:@"unable"]) {
4016 [self dismissModalViewControllerAnimated:YES];
4017 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4019 [super alertView:alert clickedButtonAtIndex:button];
4023 - (void) _doContinue {
4024 [self dismissModalViewControllerAnimated:YES];
4025 [delegate_ cancelAndClear:NO];
4028 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4029 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4033 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4034 [super webView:view didClearWindowObject:window forFrame:frame];
4035 [window setValue:changes_ forKey:@"changes"];
4036 [window setValue:issues_ forKey:@"issues"];
4037 [window setValue:sizes_ forKey:@"sizes"];
4038 [window setValue:self forKey:@"queue"];
4041 - (id) initWithDatabase:(Database *)database {
4042 if ((self = [super init]) != nil) {
4043 database_ = database;
4045 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4047 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4048 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4049 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4050 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4051 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4055 pkgDepCache::Policy *policy([database_ policy]);
4057 pkgCacheFile &cache([database_ cache]);
4058 NSArray *packages = [database_ packages];
4059 for (Package *package in packages) {
4060 pkgCache::PkgIterator iterator = [package iterator];
4061 pkgDepCache::StateCache &state(cache[iterator]);
4063 NSString *name([package name]);
4065 if (state.NewInstall())
4066 [installing addObject:name];
4067 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4068 [reinstalling addObject:name];
4069 else if (state.Upgrade())
4070 [upgrading addObject:name];
4071 else if (state.Downgrade())
4072 [downgrading addObject:name];
4073 else if (state.Delete()) {
4074 if ([package essential])
4076 [removing addObject:name];
4079 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4080 substrate_ |= DepSubstrate(iterator.CurrentVer());
4085 else if (Advanced_) {
4086 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4088 essential_ = [[UIAlertView alloc]
4089 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4090 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4092 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4093 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4096 [essential_ setContext:@"remove"];
4098 essential_ = [[UIAlertView alloc]
4099 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4100 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4102 cancelButtonTitle:UCLocalize("OKAY")
4103 otherButtonTitles:nil
4106 [essential_ setContext:@"unable"];
4109 changes_ = [[NSArray alloc] initWithObjects:
4117 issues_ = [database_ issues];
4119 issues_ = [issues_ retain];
4121 sizes_ = [[NSArray alloc] initWithObjects:
4122 SizeString([database_ fetcher].FetchNeeded()),
4123 SizeString([database_ fetcher].PartialPresent()),
4126 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4128 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4129 initWithTitle:UCLocalize("CANCEL")
4130 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4131 style:UIBarButtonItemStylePlain
4133 action:@selector(cancelButtonClicked)
4135 [[self navigationItem] setLeftBarButtonItem:leftItem];
4140 - (void) applyRightButton {
4141 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4142 initWithTitle:UCLocalize("CONFIRM")
4143 style:UIBarButtonItemStylePlain
4145 action:@selector(confirmButtonClicked)
4147 #if !AlwaysReload && !IgnoreInstall
4148 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4149 else [super applyRightButton];
4151 [[self navigationItem] setRightBarButtonItem:nil];
4153 [rightItem release];
4156 - (void) cancelButtonClicked {
4157 [self dismissModalViewControllerAnimated:YES];
4158 [delegate_ cancelAndClear:YES];
4162 - (void) confirmButtonClicked {
4166 if (essential_ != nil)
4171 [delegate_ confirmWithNavigationController:[self navigationController]];
4179 /* Progress Data {{{ */
4180 @interface ProgressData : NSObject {
4186 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4193 @implementation ProgressData
4195 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4196 if ((self = [super init]) != nil) {
4197 selector_ = selector;
4217 /* Progress Controller {{{ */
4218 @interface ProgressController : CYViewController <
4219 ConfigurationDelegate,
4222 _transient Database *database_;
4223 UIProgressBar *progress_;
4224 UITextView *output_;
4225 UITextLabel *status_;
4226 UIPushButton *close_;
4228 SHA1SumValue springlist_;
4229 SHA1SumValue notifyconf_;
4233 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4235 - (void) _retachThread;
4236 - (void) _detachNewThreadData:(ProgressData *)data;
4237 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4243 @protocol ProgressControllerDelegate
4244 - (void) progressControllerIsComplete:(ProgressController *)sender;
4247 @implementation ProgressController
4250 [database_ setDelegate:nil];
4251 [progress_ release];
4260 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4261 if ((self = [super init]) != nil) {
4262 database_ = database;
4263 [database_ setDelegate:self];
4264 delegate_ = delegate;
4266 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4268 progress_ = [[UIProgressBar alloc] init];
4269 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4270 [progress_ setStyle:0];
4272 status_ = [[UITextLabel alloc] init];
4273 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4274 [status_ setColor:[UIColor whiteColor]];
4275 [status_ setBackgroundColor:[UIColor clearColor]];
4276 [status_ setCentersHorizontally:YES];
4277 //[status_ setFont:font];
4279 output_ = [[UITextView alloc] init];
4281 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4282 //[output_ setTextFont:@"Courier New"];
4283 [output_ setFont:[[output_ font] fontWithSize:12]];
4284 [output_ setTextColor:[UIColor whiteColor]];
4285 [output_ setBackgroundColor:[UIColor clearColor]];
4286 [output_ setMarginTop:0];
4287 [output_ setAllowsRubberBanding:YES];
4288 [output_ setEditable:NO];
4289 [[self view] addSubview:output_];
4291 close_ = [[UIPushButton alloc] init];
4292 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4293 [close_ setAutosizesToFit:NO];
4294 [close_ setDrawsShadow:YES];
4295 [close_ setStretchBackground:YES];
4296 [close_ setEnabled:YES];
4297 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4298 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4299 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4300 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4304 - (void) positionViews {
4305 CGRect bounds = [[self view] bounds];
4306 CGSize prgsize = [UIProgressBar defaultSize];
4309 (bounds.size.width - prgsize.width) / 2,
4310 bounds.size.height - prgsize.height - 20
4313 float closewidth = bounds.size.width - 20;
4314 if (closewidth > 300) closewidth = 300;
4316 [progress_ setFrame:prgrect];
4317 [status_ setFrame:CGRectMake(
4319 bounds.size.height - prgsize.height - 50,
4320 bounds.size.width - 20,
4323 [output_ setFrame:CGRectMake(
4326 bounds.size.width - 20,
4327 bounds.size.height - 62
4329 [close_ setFrame:CGRectMake(
4330 (bounds.size.width - closewidth) / 2,
4331 bounds.size.height - prgsize.height - 50,
4337 - (void) viewWillAppear:(BOOL)animated {
4338 [super viewDidAppear:animated];
4339 [[self navigationItem] setHidesBackButton:YES];
4340 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4342 [self positionViews];
4345 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4346 [self positionViews];
4349 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4350 NSString *context([alert context]);
4352 if ([context isEqualToString:@"conffile"]) {
4353 FILE *input = [database_ input];
4354 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4355 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4360 - (void) closeButtonPushed {
4363 UpdateExternalStatus(0);
4367 [self dismissModalViewControllerAnimated:YES];
4371 [delegate_ terminateWithSuccess];
4372 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4373 [delegate_ suspendWithAnimation:YES];
4375 [delegate_ suspend];*/
4379 system("launchctl stop com.apple.SpringBoard");
4383 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4392 - (void) _retachThread {
4393 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4395 [[self view] addSubview:close_];
4396 [progress_ removeFromSuperview];
4397 [status_ removeFromSuperview];
4399 [database_ popErrorWithTitle:title_];
4400 [delegate_ progressControllerIsComplete:self];
4404 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4407 MMap mmap(file, MMap::ReadOnly);
4409 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4410 if (!(notifyconf_ == sha1.Result()))
4417 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4420 MMap mmap(file, MMap::ReadOnly);
4422 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4423 if (!(springlist_ == sha1.Result()))
4429 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4430 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4431 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4432 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4433 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4436 system("su -c /usr/bin/uicache mobile");
4438 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4440 [delegate_ setStatusBarShowsProgress:NO];
4443 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4444 [[data target] performSelector:[data selector] withObject:[data object]];
4447 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4450 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4451 UpdateExternalStatus(1);
4458 title_ = [title retain];
4460 [[self navigationItem] setTitle:title_];
4462 [status_ setText:nil];
4463 [output_ setText:@""];
4464 [progress_ setProgress:0];
4466 [close_ removeFromSuperview];
4467 [[self view] addSubview:progress_];
4468 [[self view] addSubview:status_];
4470 [delegate_ setStatusBarShowsProgress:YES];
4475 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4478 MMap mmap(file, MMap::ReadOnly);
4480 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4481 notifyconf_ = sha1.Result();
4487 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4490 MMap mmap(file, MMap::ReadOnly);
4492 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4493 springlist_ = sha1.Result();
4498 detachNewThreadSelector:@selector(_detachNewThreadData:)
4500 withObject:[[ProgressData alloc]
4501 initWithSelector:selector
4508 - (void) repairWithSelector:(SEL)selector {
4510 detachNewThreadSelector:selector
4513 title:UCLocalize("REPAIRING")
4517 - (void) setConfigurationData:(NSString *)data {
4519 performSelectorOnMainThread:@selector(_setConfigurationData:)
4525 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4526 CYActionSheet *sheet([[[CYActionSheet alloc]
4528 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4529 defaultButtonIndex:0
4532 [sheet setMessage:error];
4533 [sheet yieldToPopupAlertAnimated:YES];
4537 - (void) setProgressTitle:(NSString *)title {
4539 performSelectorOnMainThread:@selector(_setProgressTitle:)
4545 - (void) setProgressPercent:(float)percent {
4547 performSelectorOnMainThread:@selector(_setProgressPercent:)
4548 withObject:[NSNumber numberWithFloat:percent]
4553 - (void) startProgress {
4556 - (void) addProgressOutput:(NSString *)output {
4558 performSelectorOnMainThread:@selector(_addProgressOutput:)
4564 - (bool) isCancelling:(size_t)received {
4568 - (void) _setConfigurationData:(NSString *)data {
4569 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4571 if (!conffile_r(data)) {
4572 lprintf("E:invalid conffile\n");
4576 NSString *ofile = conffile_r[1];
4577 //NSString *nfile = conffile_r[2];
4579 UIAlertView *alert = [[[UIAlertView alloc]
4580 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4581 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4583 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4584 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4585 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4589 [alert setContext:@"conffile"];
4593 - (void) _setProgressTitle:(NSString *)title {
4594 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4595 for (size_t i(0), e([words count]); i != e; ++i) {
4596 NSString *word([words objectAtIndex:i]);
4597 if (Package *package = [database_ packageWithName:word])
4598 [words replaceObjectAtIndex:i withObject:[package name]];
4601 [status_ setText:[words componentsJoinedByString:@" "]];
4604 - (void) _setProgressPercent:(NSNumber *)percent {
4605 [progress_ setProgress:[percent floatValue]];
4608 - (void) _addProgressOutput:(NSString *)output {
4609 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4610 CGSize size = [output_ contentSize];
4611 CGRect rect = {{0, size.height}, {size.width, 0}};
4612 [output_ scrollRectToVisible:rect animated:YES];
4615 - (BOOL) isRunning {
4622 /* Cell Content View {{{ */
4623 @protocol ContentDelegate
4624 - (void) drawContentRect:(CGRect)rect;
4627 @interface ContentView : UIView {
4628 _transient id<ContentDelegate> delegate_;
4633 @implementation ContentView
4634 - (id) initWithFrame:(CGRect)frame {
4635 if ((self = [super initWithFrame:frame]) != nil) {
4636 /* Fix landscape stretching. */
4637 [self setNeedsDisplayOnBoundsChange:YES];
4641 - (void) setDelegate:(id<ContentDelegate>)delegate {
4642 delegate_ = delegate;
4645 - (void) drawRect:(CGRect)rect {
4646 [super drawRect:rect];
4647 [delegate_ drawContentRect:rect];
4651 /* Package Cell {{{ */
4652 @interface PackageCell : UITableViewCell <
4657 NSString *description_;
4663 ContentView *content_;
4669 - (PackageCell *) init;
4670 - (void) setPackage:(Package *)package;
4672 + (int) heightForPackage:(Package *)package;
4673 - (void) drawContentRect:(CGRect)rect;
4677 @implementation PackageCell
4679 - (void) clearPackage {
4690 if (description_ != nil) {
4691 [description_ release];
4695 if (source_ != nil) {
4700 if (badge_ != nil) {
4705 if (placard_ != nil) {
4715 [self clearPackage];
4722 return faded_ ? [self selectionPercent] : fade_;
4725 - (PackageCell *) init {
4726 CGRect frame(CGRectMake(0, 0, 320, 74));
4727 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4728 UIView *content([self contentView]);
4729 CGRect bounds([content bounds]);
4731 content_ = [[ContentView alloc] initWithFrame:bounds];
4732 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4733 [content addSubview:content_];
4735 [content_ setDelegate:self];
4736 [content_ setOpaque:YES];
4737 if ([self respondsToSelector:@selector(selectionPercent)])
4742 - (void) _setBackgroundColor {
4744 if (NSString *mode = [package_ mode]) {
4745 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4746 color = remove ? RemovingColor_ : InstallingColor_;
4748 color = [UIColor whiteColor];
4750 [content_ setBackgroundColor:color];
4751 [self setNeedsDisplay];
4754 - (void) setPackage:(Package *)package {
4755 [self clearPackage];
4758 Source *source = [package source];
4760 icon_ = [[package icon] retain];
4761 name_ = [[package name] retain];
4764 description_ = [package longDescription];
4765 if (description_ == nil)
4766 description_ = [package shortDescription];
4767 if (description_ != nil)
4768 description_ = [description_ retain];
4770 commercial_ = [package isCommercial];
4772 package_ = [package retain];
4774 NSString *label = nil;
4775 bool trusted = false;
4777 if (source != nil) {
4778 label = [source label];
4779 trusted = [source trusted];
4780 } else if ([[package id] isEqualToString:@"firmware"])
4781 label = UCLocalize("APPLE");
4783 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4785 NSString *from(label);
4787 NSString *section = [package simpleSection];
4788 if (section != nil && ![section isEqualToString:label]) {
4789 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4790 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4793 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4794 source_ = [from retain];
4796 if (NSString *purpose = [package primaryPurpose])
4797 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4798 badge_ = [badge_ retain];
4800 if ([package installed] != nil)
4801 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4802 placard_ = [placard_ retain];
4804 [self _setBackgroundColor];
4805 [content_ setNeedsDisplay];
4808 - (void) drawContentRect:(CGRect)rect {
4809 bool selected([self isSelected]);
4810 float width([self bounds].size.width);
4813 CGContextRef context(UIGraphicsGetCurrentContext());
4814 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4815 CGContextFillRect(context, rect);
4820 rect.size = [icon_ size];
4822 rect.size.width /= 2;
4823 rect.size.height /= 2;
4825 rect.origin.x = 25 - rect.size.width / 2;
4826 rect.origin.y = 25 - rect.size.height / 2;
4828 [icon_ drawInRect:rect];
4831 if (badge_ != nil) {
4832 CGSize size = [badge_ size];
4834 [badge_ drawAtPoint:CGPointMake(
4835 36 - size.width / 2,
4836 36 - size.height / 2
4844 UISetColor(commercial_ ? Purple_ : Black_);
4845 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4846 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4849 UISetColor(commercial_ ? Purplish_ : Gray_);
4850 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4852 if (placard_ != nil)
4853 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4856 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4857 //[self _setBackgroundColor];
4858 [super setSelected:selected animated:fade];
4859 [content_ setNeedsDisplay];
4862 + (int) heightForPackage:(Package *)package {
4868 /* Section Cell {{{ */
4869 @interface SectionCell : UITableViewCell <
4877 ContentView *content_;
4882 - (void) setSection:(Section *)section editing:(BOOL)editing;
4886 @implementation SectionCell
4888 - (void) clearSection {
4889 if (basic_ != nil) {
4894 if (section_ != nil) {
4904 if (count_ != nil) {
4911 [self clearSection];
4919 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4920 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4921 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4922 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4923 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4925 UIView *content([self contentView]);
4926 CGRect bounds([content bounds]);
4928 content_ = [[ContentView alloc] initWithFrame:bounds];
4929 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4930 [content addSubview:content_];
4931 [content_ setBackgroundColor:[UIColor whiteColor]];
4933 [content_ setDelegate:self];
4937 - (void) onSwitch:(id)sender {
4938 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4939 if (metadata == nil) {
4940 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4941 [Sections_ setObject:metadata forKey:basic_];
4945 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4948 - (void) setSection:(Section *)section editing:(BOOL)editing {
4949 if (editing != editing_) {
4951 [switch_ removeFromSuperview];
4953 [self addSubview:switch_];
4957 [self clearSection];
4959 if (section == nil) {
4960 name_ = [UCLocalize("ALL_PACKAGES") retain];
4963 basic_ = [section name];
4965 basic_ = [basic_ retain];
4967 section_ = [section localized];
4968 if (section_ != nil)
4969 section_ = [section_ retain];
4971 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4972 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4975 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4978 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4979 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4981 [content_ setNeedsDisplay];
4984 - (void) setFrame:(CGRect)frame {
4985 [super setFrame:frame];
4987 CGRect rect([switch_ frame]);
4988 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4991 - (void) drawContentRect:(CGRect)rect {
4992 BOOL selected = [self isSelected];
4994 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5002 float width(rect.size.width);
5006 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5008 CGSize size = [count_ sizeWithFont:Font14_];
5012 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5018 /* File Table {{{ */
5019 @interface FileTable : CYViewController <
5020 UITableViewDataSource,
5023 _transient Database *database_;
5026 NSMutableArray *files_;
5030 - (id) initWithDatabase:(Database *)database;
5031 - (void) setPackage:(Package *)package;
5035 @implementation FileTable
5038 if (package_ != nil)
5047 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5048 return files_ == nil ? 0 : [files_ count];
5051 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5055 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5056 static NSString *reuseIdentifier = @"Cell";
5058 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5060 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5061 [cell setFont:[UIFont systemFontOfSize:16]];
5063 [cell setText:[files_ objectAtIndex:indexPath.row]];
5064 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5069 - (id) initWithDatabase:(Database *)database {
5070 if ((self = [super init]) != nil) {
5071 database_ = database;
5073 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5075 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5077 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5078 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5079 [list_ setRowHeight:24.0f];
5080 [[self view] addSubview:list_];
5082 [list_ setDataSource:self];
5083 [list_ setDelegate:self];
5087 - (void) setPackage:(Package *)package {
5088 if (package_ != nil) {
5089 [package_ autorelease];
5098 [files_ removeAllObjects];
5100 if (package != nil) {
5101 package_ = [package retain];
5102 name_ = [[package id] retain];
5104 if (NSArray *files = [package files])
5105 [files_ addObjectsFromArray:files];
5107 if ([files_ count] != 0) {
5108 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5109 [files_ removeObjectAtIndex:0];
5110 [files_ sortUsingSelector:@selector(compareByPath:)];
5112 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5113 [stack addObject:@"/"];
5115 for (int i(0), e([files_ count]); i != e; ++i) {
5116 NSString *file = [files_ objectAtIndex:i];
5117 while (![file hasPrefix:[stack lastObject]])
5118 [stack removeLastObject];
5119 NSString *directory = [stack lastObject];
5120 [stack addObject:[file stringByAppendingString:@"/"]];
5121 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5122 ([stack count] - 2) * 3, "",
5123 [file substringFromIndex:[directory length]]
5132 - (void) reloadData {
5133 [self setPackage:[database_ packageWithName:name_]];
5138 /* Package Controller {{{ */
5139 @interface PackageController : CYBrowserController <
5140 UIActionSheetDelegate
5142 _transient Database *database_;
5146 NSMutableArray *buttons_;
5147 UIBarButtonItem *button_;
5150 - (id) initWithDatabase:(Database *)database;
5151 - (void) setPackage:(Package *)package;
5155 @implementation PackageController
5158 if (package_ != nil)
5172 if ([self retainCount] == 1)
5173 [delegate_ setPackageController:self];
5177 /* XXX: this is not safe at all... localization of /fail/ */
5178 - (void) _clickButtonWithName:(NSString *)name {
5179 if ([name isEqualToString:UCLocalize("CLEAR")])
5180 [delegate_ clearPackage:package_];
5181 else if ([name isEqualToString:UCLocalize("INSTALL")])
5182 [delegate_ installPackage:package_];
5183 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5184 [delegate_ installPackage:package_];
5185 else if ([name isEqualToString:UCLocalize("REMOVE")])
5186 [delegate_ removePackage:package_];
5187 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5188 [delegate_ installPackage:package_];
5189 else _assert(false);
5192 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5193 NSString *context([sheet context]);
5195 if ([context isEqualToString:@"modify"]) {
5196 if (button != [sheet cancelButtonIndex]) {
5197 NSString *buttonName = [buttons_ objectAtIndex:button];
5198 [self _clickButtonWithName:buttonName];
5201 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5205 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5206 [super webView:view didClearWindowObject:window forFrame:frame];
5207 [window setValue:package_ forKey:@"package"];
5210 - (bool) _allowJavaScriptPanel {
5215 - (void) _customButtonClicked {
5216 int count([buttons_ count]);
5221 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5223 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5224 [buttons addObjectsFromArray:buttons_];
5226 UIActionSheet *sheet = [[[UIActionSheet alloc]
5229 cancelButtonTitle:nil
5230 destructiveButtonTitle:nil
5231 otherButtonTitles:nil
5234 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5236 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5237 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5239 [sheet setContext:@"modify"];
5241 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5245 // We don't want to allow non-commercial packages to do custom things to the install button,
5246 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5247 - (void) customButtonClicked {
5249 [super customButtonClicked];
5251 [self _customButtonClicked];
5254 - (void) reloadButtonClicked {
5255 // Don't reload a package view by clicking the button.
5258 - (void) applyLoadingTitle {
5259 // Don't show "Loading" as the title. Ever.
5262 - (UIBarButtonItem *) rightButton {
5267 - (id) initWithDatabase:(Database *)database {
5268 if ((self = [super init]) != nil) {
5269 database_ = database;
5270 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5271 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5275 - (void) setPackage:(Package *)package {
5276 if (package_ != nil) {
5277 [package_ autorelease];
5286 [buttons_ removeAllObjects];
5288 if (package != nil) {
5291 package_ = [package retain];
5292 name_ = [[package id] retain];
5293 commercial_ = [package isCommercial];
5295 if ([package_ mode] != nil)
5296 [buttons_ addObject:UCLocalize("CLEAR")];
5297 if ([package_ source] == nil);
5298 else if ([package_ upgradableAndEssential:NO])
5299 [buttons_ addObject:UCLocalize("UPGRADE")];
5300 else if ([package_ uninstalled])
5301 [buttons_ addObject:UCLocalize("INSTALL")];
5303 [buttons_ addObject:UCLocalize("REINSTALL")];
5304 if (![package_ uninstalled])
5305 [buttons_ addObject:UCLocalize("REMOVE")];
5312 switch ([buttons_ count]) {
5313 case 0: title = nil; break;
5314 case 1: title = [buttons_ objectAtIndex:0]; break;
5315 default: title = UCLocalize("MODIFY"); break;
5318 button_ = [[UIBarButtonItem alloc]
5320 style:UIBarButtonItemStylePlain
5322 action:@selector(customButtonClicked)
5326 - (bool) isLoading {
5327 return commercial_ ? [super isLoading] : false;
5330 - (void) reloadData {
5331 [self setPackage:[database_ packageWithName:name_]];
5336 /* Package Table {{{ */
5337 @interface PackageTable : UIView <
5338 UITableViewDataSource,
5341 _transient Database *database_;
5342 NSMutableArray *packages_;
5343 NSMutableArray *sections_;
5345 NSMutableArray *index_;
5346 NSMutableDictionary *indices_;
5352 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5354 - (void) setDelegate:(id)delegate;
5356 - (void) reloadData;
5357 - (void) resetCursor;
5359 - (UITableView *) list;
5361 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5363 - (void) deselectWithAnimation:(BOOL)animated;
5367 @implementation PackageTable
5370 [packages_ release];
5371 [sections_ release];
5379 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5380 NSInteger count([sections_ count]);
5381 return count == 0 ? 1 : count;
5384 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5385 if ([sections_ count] == 0)
5387 return [[sections_ objectAtIndex:section] name];
5390 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5391 if ([sections_ count] == 0)
5393 return [[sections_ objectAtIndex:section] count];
5396 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5397 Section *section([sections_ objectAtIndex:[path section]]);
5398 NSInteger row([path row]);
5399 Package *package([packages_ objectAtIndex:([section row] + row)]);
5403 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5404 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5406 cell = [[[PackageCell alloc] init] autorelease];
5407 [cell setPackage:[self packageAtIndexPath:path]];
5411 - (void) deselectWithAnimation:(BOOL)animated {
5412 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5415 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5416 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5419 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5420 Package *package([self packageAtIndexPath:path]);
5421 package = [database_ packageWithName:[package id]];
5422 [target_ performSelector:action_ withObject:package];
5426 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5427 return [packages_ count] > 20 ? index_ : nil;
5430 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5434 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5435 if ((self = [super initWithFrame:frame]) != nil) {
5436 database_ = database;
5441 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5442 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5444 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5445 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5447 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5448 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5449 [list_ setRowHeight:73.0f];
5450 [self addSubview:list_];
5452 [list_ setDataSource:self];
5453 [list_ setDelegate:self];
5457 - (void) setDelegate:(id)delegate {
5458 delegate_ = delegate;
5461 - (bool) hasPackage:(Package *)package {
5465 - (void) reloadData {
5466 NSArray *packages = [database_ packages];
5468 [packages_ removeAllObjects];
5469 [sections_ removeAllObjects];
5471 _profile(PackageTable$reloadData$Filter)
5472 for (Package *package in packages)
5473 if ([self hasPackage:package])
5474 [packages_ addObject:package];
5477 [index_ removeAllObjects];
5478 [indices_ removeAllObjects];
5480 Section *section = nil;
5482 _profile(PackageTable$reloadData$Section)
5483 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5487 _profile(PackageTable$reloadData$Section$Package)
5488 package = [packages_ objectAtIndex:offset];
5489 index = [package index];
5492 if (section == nil || [section index] != index) {
5493 _profile(PackageTable$reloadData$Section$Allocate)
5494 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5497 [index_ addObject:[section name]];
5498 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5500 _profile(PackageTable$reloadData$Section$Add)
5501 [sections_ addObject:section];
5505 [section addToCount];
5509 _profile(PackageTable$reloadData$List)
5514 - (void) resetCursor {
5515 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5518 - (UITableView *) list {
5522 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5523 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5528 /* Filtered Package Table {{{ */
5529 @interface FilteredPackageTable : PackageTable {
5535 - (void) setObject:(id)object;
5536 - (void) setObject:(id)object forFilter:(SEL)filter;
5538 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5542 @implementation FilteredPackageTable
5550 - (void) setFilter:(SEL)filter {
5553 /* XXX: this is an unsafe optimization of doomy hell */
5554 Method method(class_getInstanceMethod([Package class], filter));
5555 _assert(method != NULL);
5556 imp_ = method_getImplementation(method);
5557 _assert(imp_ != NULL);
5560 - (void) setObject:(id)object {
5566 object_ = [object retain];
5569 - (void) setObject:(id)object forFilter:(SEL)filter {
5570 [self setFilter:filter];
5571 [self setObject:object];
5574 - (bool) hasPackage:(Package *)package {
5575 _profile(FilteredPackageTable$hasPackage)
5576 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5580 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5581 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5582 [self setFilter:filter];
5583 object_ = [object retain];
5591 /* Filtered Package Controller {{{ */
5592 @interface FilteredPackageController : CYViewController {
5593 _transient Database *database_;
5594 FilteredPackageTable *packages_;
5598 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5602 @implementation FilteredPackageController
5605 [packages_ release];
5611 - (void) viewDidAppear:(BOOL)animated {
5612 [super viewDidAppear:animated];
5613 [packages_ deselectWithAnimation:animated];
5616 - (void) didSelectPackage:(Package *)package {
5617 PackageController *view([delegate_ packageController]);
5618 [view setPackage:package];
5619 [view setDelegate:delegate_];
5620 [[self navigationController] pushViewController:view animated:YES];
5623 - (NSString *) title { return title_; }
5625 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5626 if ((self = [super init]) != nil) {
5627 database_ = database;
5628 title_ = [title copy];
5629 [[self navigationItem] setTitle:title_];
5631 packages_ = [[FilteredPackageTable alloc]
5632 initWithFrame:[[self view] bounds]
5635 action:@selector(didSelectPackage:)
5640 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5641 [[self view] addSubview:packages_];
5645 - (void) reloadData {
5646 [packages_ reloadData];
5649 - (void) setDelegate:(id)delegate {
5650 [super setDelegate:delegate];
5651 [packages_ setDelegate:delegate];
5658 /* Add Source Controller {{{ */
5659 @interface AddSourceController : CYViewController {
5660 _transient Database *database_;
5663 - (id) initWithDatabase:(Database *)database;
5667 @implementation AddSourceController
5669 - (id) initWithDatabase:(Database *)database {
5670 if ((self = [super init]) != nil) {
5671 database_ = database;
5677 /* Source Cell {{{ */
5678 @interface SourceCell : UITableViewCell <
5683 NSString *description_;
5685 ContentView *content_;
5688 - (void) setSource:(Source *)source;
5692 @implementation SourceCell
5694 - (void) clearSource {
5697 [description_ release];
5706 - (void) setSource:(Source *)source {
5710 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5712 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5713 icon_ = [icon_ retain];
5715 origin_ = [[source name] retain];
5716 label_ = [[source uri] retain];
5717 description_ = [[source description] retain];
5719 [content_ setNeedsDisplay];
5728 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5729 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5730 UIView *content([self contentView]);
5731 CGRect bounds([content bounds]);
5733 content_ = [[ContentView alloc] initWithFrame:bounds];
5734 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5735 [content_ setBackgroundColor:[UIColor whiteColor]];
5736 [content addSubview:content_];
5738 [content_ setDelegate:self];
5739 [content_ setOpaque:YES];
5743 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5744 [super setSelected:selected animated:animated];
5745 [content_ setNeedsDisplay];
5748 - (void) drawContentRect:(CGRect)rect {
5749 bool selected([self isSelected]);
5750 float width(rect.size.width);
5753 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5760 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5764 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5768 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5773 /* Source Table {{{ */
5774 @interface SourceTable : CYViewController <
5775 UITableViewDataSource,
5778 _transient Database *database_;
5780 NSMutableArray *sources_;
5784 UIProgressHUD *hud_;
5787 //NSURLConnection *installer_;
5788 NSURLConnection *trivial_;
5789 NSURLConnection *trivial_bz2_;
5790 NSURLConnection *trivial_gz_;
5791 //NSURLConnection *automatic_;
5796 - (id) initWithDatabase:(Database *)database;
5798 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5802 @implementation SourceTable
5804 - (void) _deallocConnection:(NSURLConnection *)connection {
5805 if (connection != nil) {
5806 [connection cancel];
5807 //[connection setDelegate:nil];
5808 [connection release];
5820 //[self _deallocConnection:installer_];
5821 [self _deallocConnection:trivial_];
5822 [self _deallocConnection:trivial_gz_];
5823 [self _deallocConnection:trivial_bz2_];
5824 //[self _deallocConnection:automatic_];
5831 - (void) viewDidAppear:(BOOL)animated {
5832 [super viewDidAppear:animated];
5833 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5836 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5837 return offset_ == 0 ? 1 : 2;
5840 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5841 switch (section + (offset_ == 0 ? 1 : 0)) {
5842 case 0: return UCLocalize("ENTERED_BY_USER");
5843 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5849 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5850 int count = [sources_ count];
5852 case 0: return (offset_ == 0 ? count : offset_);
5853 case 1: return count - offset_;
5859 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5861 switch (indexPath.section) {
5862 case 0: idx = indexPath.row; break;
5863 case 1: idx = indexPath.row + offset_; break;
5867 return [sources_ objectAtIndex:idx];
5870 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5871 Source *source = [self sourceAtIndexPath:indexPath];
5872 return [source description] == nil ? 56 : 73;
5875 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5876 static NSString *cellIdentifier = @"SourceCell";
5878 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5879 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5880 [cell setSource:[self sourceAtIndexPath:indexPath]];
5885 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5886 return UITableViewCellAccessoryDisclosureIndicator;
5889 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5890 Source *source = [self sourceAtIndexPath:indexPath];
5892 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5893 initWithDatabase:database_
5894 title:[source label]
5895 filter:@selector(isVisibleInSource:)
5899 [packages setDelegate:delegate_];
5901 [[self navigationController] pushViewController:packages animated:YES];
5904 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5905 Source *source = [self sourceAtIndexPath:indexPath];
5906 return [source record] != nil;
5909 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5910 Source *source = [self sourceAtIndexPath:indexPath];
5911 [Sources_ removeObjectForKey:[source key]];
5912 [delegate_ syncData];
5916 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5919 @"./", @"Distribution",
5920 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5922 [delegate_ syncData];
5925 - (NSString *) getWarning {
5926 NSString *href(href_);
5927 NSRange colon([href rangeOfString:@"://"]);
5928 if (colon.location != NSNotFound)
5929 href = [href substringFromIndex:(colon.location + 3)];
5930 href = [href stringByAddingPercentEscapes];
5931 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5932 href = [href stringByCachingURLWithCurrentCDN];
5934 NSURL *url([NSURL URLWithString:href]);
5936 NSStringEncoding encoding;
5937 NSError *error(nil);
5939 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5940 return [warning length] == 0 ? nil : warning;
5944 - (void) _endConnection:(NSURLConnection *)connection {
5945 NSURLConnection **field = NULL;
5946 if (connection == trivial_)
5948 else if (connection == trivial_bz2_)
5949 field = &trivial_bz2_;
5950 else if (connection == trivial_gz_)
5951 field = &trivial_gz_;
5952 _assert(field != NULL);
5953 [connection release];
5958 trivial_bz2_ == nil &&
5964 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5967 UIAlertView *alert = [[[UIAlertView alloc]
5968 initWithTitle:UCLocalize("SOURCE_WARNING")
5971 cancelButtonTitle:UCLocalize("CANCEL")
5972 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5975 [alert setContext:@"warning"];
5976 [alert setNumberOfRows:1];
5980 } else if (error_ != nil) {
5981 UIAlertView *alert = [[[UIAlertView alloc]
5982 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5983 message:[error_ localizedDescription]
5985 cancelButtonTitle:UCLocalize("OK")
5986 otherButtonTitles:nil
5989 [alert setContext:@"urlerror"];
5992 UIAlertView *alert = [[[UIAlertView alloc]
5993 initWithTitle:UCLocalize("NOT_REPOSITORY")
5994 message:UCLocalize("NOT_REPOSITORY_EX")
5996 cancelButtonTitle:UCLocalize("OK")
5997 otherButtonTitles:nil
6000 [alert setContext:@"trivial"];
6004 [delegate_ setStatusBarShowsProgress:NO];
6005 [delegate_ removeProgressHUD:hud_];
6015 if (error_ != nil) {
6022 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6023 switch ([response statusCode]) {
6029 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6030 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6032 error_ = [error retain];
6033 [self _endConnection:connection];
6036 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6037 [self _endConnection:connection];
6040 - (NSString *) title { return UCLocalize("SOURCES"); }
6042 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6043 NSMutableURLRequest *request = [NSMutableURLRequest
6044 requestWithURL:[NSURL URLWithString:href]
6045 cachePolicy:NSURLRequestUseProtocolCachePolicy
6046 timeoutInterval:120.0
6049 [request setHTTPMethod:method];
6051 if (Machine_ != NULL)
6052 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6053 if (UniqueID_ != nil)
6054 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6056 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6058 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6061 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6062 NSString *context([alert context]);
6064 if ([context isEqualToString:@"source"]) {
6067 NSString *href = [[alert textField] text];
6069 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6071 if (![href hasSuffix:@"/"])
6072 href_ = [href stringByAppendingString:@"/"];
6075 href_ = [href_ retain];
6077 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6078 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6079 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6080 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6084 hud_ = [[delegate_ addProgressHUD] retain];
6085 [hud_ setText:UCLocalize("VERIFYING_URL")];
6094 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6095 } else if ([context isEqualToString:@"trivial"])
6096 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6097 else if ([context isEqualToString:@"urlerror"])
6098 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6099 else if ([context isEqualToString:@"warning"]) {
6114 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6118 - (id) initWithDatabase:(Database *)database {
6119 if ((self = [super init]) != nil) {
6120 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6121 [self updateButtonsForEditingStatus:NO animated:NO];
6123 database_ = database;
6124 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6126 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6127 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6128 [[self view] addSubview:list_];
6130 [list_ setDataSource:self];
6131 [list_ setDelegate:self];
6137 - (void) reloadData {
6139 if (!list.ReadMainList())
6142 [sources_ removeAllObjects];
6143 [sources_ addObjectsFromArray:[database_ sources]];
6145 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6148 int count([sources_ count]);
6150 for (int i = 0; i != count; i++) {
6151 if ([[sources_ objectAtIndex:i] record] == nil) break;
6155 [list_ setEditing:NO];
6156 [self updateButtonsForEditingStatus:NO animated:NO];
6160 - (void) addButtonClicked {
6161 /*[book_ pushPage:[[[AddSourceController alloc]
6166 UIAlertView *alert = [[[UIAlertView alloc]
6167 initWithTitle:UCLocalize("ENTER_APT_URL")
6170 cancelButtonTitle:UCLocalize("CANCEL")
6171 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6174 [alert setContext:@"source"];
6175 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6177 [alert setNumberOfRows:1];
6178 [alert addTextFieldWithValue:@"http://" label:@""];
6180 UITextInputTraits *traits = [[alert textField] textInputTraits];
6181 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6182 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6183 [traits setKeyboardType:UIKeyboardTypeURL];
6184 // XXX: UIReturnKeyDone
6185 [traits setReturnKeyType:UIReturnKeyNext];
6190 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6191 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6192 initWithTitle:UCLocalize("ADD")
6193 style:UIBarButtonItemStylePlain
6195 action:@selector(addButtonClicked)
6197 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6200 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6201 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6202 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6204 action:@selector(editButtonClicked)
6206 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6207 [rightItem release];
6209 if (IsWildcat_ && !editing) {
6210 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6211 initWithTitle:UCLocalize("SETTINGS")
6212 style:UIBarButtonItemStylePlain
6214 action:@selector(settingsButtonClicked)
6216 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6217 [settingsItem release];
6221 - (void) settingsButtonClicked {
6222 [delegate_ showSettings];
6225 - (void) editButtonClicked {
6226 [list_ setEditing:![list_ isEditing] animated:YES];
6228 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6234 /* Installed Controller {{{ */
6235 @interface InstalledController : FilteredPackageController {
6239 - (id) initWithDatabase:(Database *)database;
6241 - (void) updateRoleButton;
6242 - (void) queueStatusDidChange;
6246 @implementation InstalledController
6252 - (NSString *) title { return UCLocalize("INSTALLED"); }
6254 - (id) initWithDatabase:(Database *)database {
6255 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6256 [self updateRoleButton];
6257 [self queueStatusDidChange];
6262 - (void) queueButtonClicked {
6267 - (void) queueStatusDidChange {
6270 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6271 initWithTitle:UCLocalize("QUEUE")
6272 style:UIBarButtonItemStyleDone
6274 action:@selector(queueButtonClicked)
6276 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6277 else [[self navigationItem] setLeftBarButtonItem:nil];
6278 [queueItem release];
6283 - (void) reloadData {
6284 [packages_ reloadData];
6287 - (void) updateRoleButton {
6288 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6289 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6290 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6292 action:@selector(roleButtonClicked)
6294 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6295 [rightItem release];
6298 - (void) roleButtonClicked {
6299 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6300 [packages_ reloadData];
6303 [self updateRoleButton];
6306 - (void) setDelegate:(id)delegate {
6307 [super setDelegate:delegate];
6308 [packages_ setDelegate:delegate];
6314 /* Home Controller {{{ */
6315 @interface HomeController : CYBrowserController {
6320 @implementation HomeController
6322 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6323 [super _setMoreHeaders:request];
6326 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6327 if (UniqueID_ != nil)
6328 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6330 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6333 - (void) aboutButtonClicked {
6334 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6336 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6337 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6338 [alert setCancelButtonIndex:0];
6341 @"Copyright (C) 2008-2010\n"
6342 "Jay Freeman (saurik)\n"
6343 "saurik@saurik.com\n"
6344 "http://www.saurik.com/"
6350 - (void) viewWillAppear:(BOOL)animated {
6351 [super viewWillAppear:animated];
6352 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6355 - (void) viewWillDisappear:(BOOL)animated {
6356 [super viewWillDisappear:animated];
6357 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6361 if ((self = [super init]) != nil) {
6362 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6363 initWithTitle:UCLocalize("ABOUT")
6364 style:UIBarButtonItemStylePlain
6366 action:@selector(aboutButtonClicked)
6373 /* Manage Controller {{{ */
6374 @interface ManageController : CYBrowserController {
6377 - (void) queueStatusDidChange;
6380 @implementation ManageController
6383 if ((self = [super init]) != nil) {
6384 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6386 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6387 initWithTitle:UCLocalize("SETTINGS")
6388 style:UIBarButtonItemStylePlain
6390 action:@selector(settingsButtonClicked)
6392 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6393 [settingsItem release];
6395 [self queueStatusDidChange];
6399 - (void) settingsButtonClicked {
6400 [delegate_ showSettings];
6404 - (void) queueButtonClicked {
6408 - (void) applyLoadingTitle {
6409 // No "Loading" title.
6412 - (void) applyRightButton {
6417 - (void) queueStatusDidChange {
6419 if (!IsWildcat_ && Queuing_) {
6420 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6421 initWithTitle:UCLocalize("QUEUE")
6422 style:UIBarButtonItemStyleDone
6424 action:@selector(queueButtonClicked)
6426 [[self navigationItem] setRightBarButtonItem:queueItem];
6428 [queueItem release];
6430 [[self navigationItem] setRightBarButtonItem:nil];
6435 - (bool) isLoading {
6442 /* Refresh Bar {{{ */
6443 @interface RefreshBar : UINavigationBar {
6444 UIProgressIndicator *indicator_;
6445 UITextLabel *prompt_;
6446 UIProgressBar *progress_;
6447 UINavigationButton *cancel_;
6452 @implementation RefreshBar
6454 - (void) positionViews {
6455 CGRect frame = [cancel_ frame];
6456 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6457 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6458 [cancel_ setFrame:frame];
6460 CGSize prgsize = {75, 100};
6462 [self frame].size.width - prgsize.width - 10,
6463 ([self frame].size.height - prgsize.height) / 2
6465 [progress_ setFrame:prgrect];
6467 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6468 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6469 CGRect indrect = {{indoffset, indoffset}, indsize};
6470 [indicator_ setFrame:indrect];
6472 CGSize prmsize = {215, indsize.height + 4};
6474 indoffset * 2 + indsize.width,
6475 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6477 [prompt_ setFrame:prmrect];
6480 - (void)setFrame:(CGRect)frame {
6481 [super setFrame:frame];
6483 [self positionViews];
6486 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6487 if ((self = [super initWithFrame:frame])) {
6488 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6490 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6491 [self setBarStyle:UIBarStyleBlack];
6493 UIBarStyle barstyle([self _barStyle:NO]);
6494 bool ugly(barstyle == UIBarStyleDefault);
6496 UIProgressIndicatorStyle style = ugly ?
6497 UIProgressIndicatorStyleMediumBrown :
6498 UIProgressIndicatorStyleMediumWhite;
6500 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6501 [indicator_ setStyle:style];
6502 [indicator_ startAnimation];
6503 [self addSubview:indicator_];
6505 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6506 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6507 [prompt_ setBackgroundColor:[UIColor clearColor]];
6508 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6509 [self addSubview:prompt_];
6511 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6512 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6513 [progress_ setStyle:0];
6514 [self addSubview:progress_];
6516 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6517 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6518 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6519 [cancel_ setBarStyle:barstyle];
6521 [self positionViews];
6526 [cancel_ removeFromSuperview];
6530 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6531 [progress_ setProgress:0];
6532 [self addSubview:cancel_];
6536 [cancel_ removeFromSuperview];
6539 - (void) setPrompt:(NSString *)prompt {
6540 [prompt_ setText:prompt];
6543 - (void) setProgress:(float)progress {
6544 [progress_ setProgress:progress];
6550 @class CYNavigationController;
6552 /* Cydia Tab Bar Controller {{{ */
6553 @interface CYTabBarController : UITabBarController {
6554 Database *database_;
6559 @implementation CYTabBarController
6561 /* XXX: some logic should probably go here related to
6562 freeing the view controllers on tab change */
6564 - (void) reloadData {
6565 size_t count([[self viewControllers] count]);
6566 for (size_t i(0); i != count; ++i) {
6567 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6572 - (id) initWithDatabase:(Database *)database {
6573 if ((self = [super init]) != nil) {
6574 database_ = database;
6581 /* Cydia Navigation Controller {{{ */
6582 @interface CYNavigationController : UINavigationController {
6583 _transient Database *database_;
6584 id<UINavigationControllerDelegate> delegate_;
6587 - (id) initWithDatabase:(Database *)database;
6588 - (void) reloadData;
6593 @implementation CYNavigationController
6595 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6596 // Inherit autorotation settings for modal parents.
6597 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6598 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6600 return [super shouldAutorotateToInterfaceOrientation:orientation];
6608 - (void) reloadData {
6609 size_t count([[self viewControllers] count]);
6610 for (size_t i(0); i != count; ++i) {
6611 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6616 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6617 delegate_ = delegate;
6620 - (id) initWithDatabase:(Database *)database {
6621 if ((self = [super init]) != nil) {
6622 database_ = database;
6628 /* Cydia:// Protocol {{{ */
6629 @interface CydiaURLProtocol : NSURLProtocol {
6634 @implementation CydiaURLProtocol
6636 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6637 NSURL *url([request URL]);
6640 NSString *scheme([[url scheme] lowercaseString]);
6641 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6646 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6650 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6651 id<NSURLProtocolClient> client([self client]);
6653 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6655 NSData *data(UIImagePNGRepresentation(icon));
6657 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6658 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6659 [client URLProtocol:self didLoadData:data];
6660 [client URLProtocolDidFinishLoading:self];
6664 - (void) startLoading {
6665 id<NSURLProtocolClient> client([self client]);
6666 NSURLRequest *request([self request]);
6668 NSURL *url([request URL]);
6669 NSString *href([url absoluteString]);
6671 NSString *path([href substringFromIndex:8]);
6672 NSRange slash([path rangeOfString:@"/"]);
6675 if (slash.location == NSNotFound) {
6679 command = [path substringToIndex:slash.location];
6680 path = [path substringFromIndex:(slash.location + 1)];
6683 Database *database([Database sharedInstance]);
6685 if ([command isEqualToString:@"package-icon"]) {
6688 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6689 Package *package([database packageWithName:path]);
6692 UIImage *icon([package icon]);
6693 [self _returnPNGWithImage:icon forRequest:request];
6694 } else if ([command isEqualToString:@"source-icon"]) {
6697 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6698 NSString *source(Simplify(path));
6699 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6701 icon = [UIImage applicationImageNamed:@"unknown.png"];
6702 [self _returnPNGWithImage:icon forRequest:request];
6703 } else if ([command isEqualToString:@"uikit-image"]) {
6706 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6707 UIImage *icon(_UIImageWithName(path));
6708 [self _returnPNGWithImage:icon forRequest:request];
6709 } else if ([command isEqualToString:@"section-icon"]) {
6712 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6713 NSString *section(Simplify(path));
6714 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6716 icon = [UIImage applicationImageNamed:@"unknown.png"];
6717 [self _returnPNGWithImage:icon forRequest:request];
6719 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6723 - (void) stopLoading {
6729 /* Sections Controller {{{ */
6730 @interface SectionsController : CYViewController <
6731 UITableViewDataSource,
6734 _transient Database *database_;
6735 NSMutableArray *sections_;
6736 NSMutableArray *filtered_;
6742 - (id) initWithDatabase:(Database *)database;
6743 - (void) reloadData;
6746 - (void) editButtonClicked;
6750 @implementation SectionsController
6753 [list_ setDataSource:nil];
6754 [list_ setDelegate:nil];
6756 [sections_ release];
6757 [filtered_ release];
6759 [accessory_ release];
6763 - (void) viewDidAppear:(BOOL)animated {
6764 [super viewDidAppear:animated];
6765 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6768 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6769 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6773 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6774 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6777 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6781 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6782 static NSString *reuseIdentifier = @"SectionCell";
6784 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6785 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6786 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6791 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6795 Section *section = [self sectionAtIndexPath:indexPath];
6796 NSString *name = [section name];
6799 if ([indexPath row] == 0) {
6802 title = UCLocalize("ALL_PACKAGES");
6805 name = [NSString stringWithString:name];
6806 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6809 title = UCLocalize("NO_SECTION");
6813 FilteredPackageController *table = [[[FilteredPackageController alloc]
6814 initWithDatabase:database_
6816 filter:@selector(isVisibleInSection:)
6820 [table setDelegate:delegate_];
6822 [[self navigationController] pushViewController:table animated:YES];
6825 - (NSString *) title { return UCLocalize("SECTIONS"); }
6827 - (id) initWithDatabase:(Database *)database {
6828 if ((self = [super init]) != nil) {
6829 database_ = database;
6831 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6833 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6834 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6836 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6837 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6838 [list_ setRowHeight:45.0f];
6839 [[self view] addSubview:list_];
6841 [list_ setDataSource:self];
6842 [list_ setDelegate:self];
6848 - (void) reloadData {
6849 NSArray *packages = [database_ packages];
6851 [sections_ removeAllObjects];
6852 [filtered_ removeAllObjects];
6855 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6856 SectionMap sections;
6857 sections.resize(64);
6859 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6863 for (Package *package in packages) {
6864 NSString *name([package section]);
6865 NSString *key(name == nil ? @"" : name);
6870 _profile(SectionsView$reloadData$Section)
6871 section = §ions[key];
6872 if (*section == nil) {
6873 _profile(SectionsView$reloadData$Section$Allocate)
6874 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6879 [*section addToCount];
6881 _profile(SectionsView$reloadData$Filter)
6882 if (![package valid] || ![package visible])
6886 [*section addToRow];
6890 _profile(SectionsView$reloadData$Section)
6891 section = [sections objectForKey:key];
6892 if (section == nil) {
6893 _profile(SectionsView$reloadData$Section$Allocate)
6894 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6895 [sections setObject:section forKey:key];
6900 [section addToCount];
6902 _profile(SectionsView$reloadData$Filter)
6903 if (![package valid] || ![package visible])
6913 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6914 [sections_ addObject:i->second];
6916 [sections_ addObjectsFromArray:[sections allValues]];
6919 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6921 for (Section *section in sections_) {
6922 size_t count([section row]);
6926 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6927 [section setCount:count];
6928 [filtered_ addObject:section];
6931 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6932 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6933 style:UIBarButtonItemStylePlain
6935 action:@selector(editButtonClicked)
6937 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6938 [rightItem release];
6944 - (void) resetView {
6946 [self editButtonClicked];
6949 - (void) editButtonClicked {
6950 if ((editing_ = !editing_))
6953 [delegate_ updateData];
6955 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6956 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6957 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6960 - (UIView *) accessoryView {
6966 /* Changes Controller {{{ */
6967 @interface ChangesController : CYViewController <
6968 UITableViewDataSource,
6971 _transient Database *database_;
6972 NSMutableArray *packages_;
6973 NSMutableArray *sections_;
6976 BOOL hasSentFirstLoad_;
6979 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6980 - (void) reloadData;
6984 @implementation ChangesController
6987 [list_ setDelegate:nil];
6988 [list_ setDataSource:nil];
6990 [packages_ release];
6991 [sections_ release];
6996 - (void) viewDidAppear:(BOOL)animated {
6997 [super viewDidAppear:animated];
6998 if (!hasSentFirstLoad_) {
6999 hasSentFirstLoad_ = YES;
7000 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7002 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7006 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7007 NSInteger count([sections_ count]);
7008 return count == 0 ? 1 : count;
7011 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7012 if ([sections_ count] == 0)
7014 return [[sections_ objectAtIndex:section] name];
7017 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7018 if ([sections_ count] == 0)
7020 return [[sections_ objectAtIndex:section] count];
7023 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7024 Section *section([sections_ objectAtIndex:[path section]]);
7025 NSInteger row([path row]);
7026 return [packages_ objectAtIndex:([section row] + row)];
7029 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7030 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7032 cell = [[[PackageCell alloc] init] autorelease];
7033 [cell setPackage:[self packageAtIndexPath:path]];
7037 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7038 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7041 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7042 Package *package([self packageAtIndexPath:path]);
7043 PackageController *view([delegate_ packageController]);
7044 [view setDelegate:delegate_];
7045 [view setPackage:package];
7046 [[self navigationController] pushViewController:view animated:YES];
7050 - (void) refreshButtonClicked {
7051 [delegate_ beginUpdate];
7052 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7055 - (void) upgradeButtonClicked {
7056 [delegate_ distUpgrade];
7059 - (NSString *) title { return UCLocalize("CHANGES"); }
7061 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7062 if ((self = [super init]) != nil) {
7063 database_ = database;
7064 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7066 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7067 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7069 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7070 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7071 [list_ setRowHeight:73.0f];
7072 [[self view] addSubview:list_];
7074 [list_ setDataSource:self];
7075 [list_ setDelegate:self];
7077 delegate_ = delegate;
7081 - (void) _reloadPackages:(NSArray *)packages {
7083 for (Package *package in packages)
7085 [package uninstalled] && [package valid] && [package visible] ||
7086 [package upgradableAndEssential:YES]
7088 [packages_ addObject:package];
7091 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7095 - (void) reloadData {
7096 NSArray *packages = [database_ packages];
7098 [packages_ removeAllObjects];
7099 [sections_ removeAllObjects];
7101 UIProgressHUD *hud([delegate_ addProgressHUD]);
7103 [hud setText:@"Loading Changes"];
7104 //NSLog(@"HUD:%@::%@", delegate_, hud);
7105 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7106 [delegate_ removeProgressHUD:hud];
7108 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7109 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7110 Section *section = nil;
7114 bool unseens = false;
7116 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7118 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7119 Package *package = [packages_ objectAtIndex:offset];
7121 BOOL uae = [package upgradableAndEssential:YES];
7127 _profile(ChangesController$reloadData$Remember)
7128 seen = [package seen];
7131 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7136 name = UCLocalize("UNKNOWN");
7138 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7142 _profile(ChangesController$reloadData$Allocate)
7143 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7144 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7145 [sections_ addObject:section];
7149 [section addToCount];
7150 } else if ([package ignored])
7151 [ignored addToCount];
7154 [upgradable addToCount];
7159 CFRelease(formatter);
7162 Section *last = [sections_ lastObject];
7163 size_t count = [last count];
7164 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7165 [sections_ removeLastObject];
7168 if ([ignored count] != 0)
7169 [sections_ insertObject:ignored atIndex:0];
7171 [sections_ insertObject:upgradable atIndex:0];
7175 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7176 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7177 style:UIBarButtonItemStylePlain
7179 action:@selector(upgradeButtonClicked)
7181 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7182 [rightItem release];
7184 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7185 initWithTitle:UCLocalize("REFRESH")
7186 style:UIBarButtonItemStylePlain
7188 action:@selector(refreshButtonClicked)
7190 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7196 /* Search Controller {{{ */
7197 @interface SearchController : FilteredPackageController <
7200 UISearchBar *search_;
7203 - (id) initWithDatabase:(Database *)database;
7204 - (void) reloadData;
7208 @implementation SearchController
7215 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7216 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7217 [search_ resignFirstResponder];
7221 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7222 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7226 - (NSString *) title { return nil; }
7228 - (id) initWithDatabase:(Database *)database {
7229 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7232 - (void)viewDidAppear:(BOOL)animated {
7233 [super viewDidAppear:animated];
7235 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7236 [search_ layoutSubviews];
7237 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7238 UITextField *textField = [search_ searchField];
7239 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7240 [search_ setDelegate:self];
7241 [textField setEnablesReturnKeyAutomatically:NO];
7242 [[self navigationItem] setTitleView:textField];
7246 - (void) _reloadData {
7249 - (void) reloadData {
7250 _profile(SearchController$reloadData)
7251 [packages_ reloadData];
7254 [packages_ resetCursor];
7257 - (void) didSelectPackage:(Package *)package {
7258 [search_ resignFirstResponder];
7259 [super didSelectPackage:package];
7264 /* Settings Controller {{{ */
7265 @interface SettingsController : CYViewController <
7266 UITableViewDataSource,
7269 _transient Database *database_;
7272 UITableView *table_;
7273 id subscribedSwitch_;
7275 UITableViewCell *subscribedCell_;
7276 UITableViewCell *ignoredCell_;
7279 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7283 @implementation SettingsController
7287 if (package_ != nil)
7290 [subscribedSwitch_ release];
7291 [ignoredSwitch_ release];
7292 [subscribedCell_ release];
7293 [ignoredCell_ release];
7298 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7299 if (package_ == nil)
7305 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7306 if (package_ == nil)
7312 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7313 return UCLocalize("SHOW_ALL_CHANGES_EX");
7316 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7317 if (package_ == nil)
7320 NSMutableDictionary *metadata([package_ metadata]);
7323 if (NSNumber *number = [metadata objectForKey:key])
7324 before = [number boolValue];
7328 if (value != before) {
7329 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7331 [delegate_ updateData];
7335 - (void) onSubscribed:(id)control {
7336 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7339 - (void) onIgnored:(id)control {
7340 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7343 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7344 if (package_ == nil)
7347 switch ([indexPath row]) {
7348 case 0: return subscribedCell_;
7349 case 1: return ignoredCell_;
7357 - (NSString *) title { return UCLocalize("SETTINGS"); }
7359 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7360 if ((self = [super init])) {
7361 database_ = database;
7362 name_ = [package retain];
7364 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7366 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7367 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7368 [[self view] addSubview:table_];
7370 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7371 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7372 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7374 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7375 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7376 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7378 subscribedCell_ = [[UITableViewCell alloc] init];
7379 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7380 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7381 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7383 ignoredCell_ = [[UITableViewCell alloc] init];
7384 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7385 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7386 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7388 [table_ setDataSource:self];
7389 [table_ setDelegate:self];
7394 - (void) reloadData {
7395 if (package_ != nil)
7396 [package_ autorelease];
7397 package_ = [database_ packageWithName:name_];
7398 if (package_ != nil) {
7400 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7401 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7404 [table_ reloadData];
7409 /* Signature Controller {{{ */
7410 @interface SignatureController : CYBrowserController {
7411 _transient Database *database_;
7415 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7419 @implementation SignatureController
7426 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7428 [super webView:view didClearWindowObject:window forFrame:frame];
7431 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7432 if ((self = [super init]) != nil) {
7433 database_ = database;
7434 package_ = [package retain];
7439 - (void) reloadData {
7440 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7446 /* Role Controller {{{ */
7447 @interface RoleController : CYViewController <
7448 UITableViewDataSource,
7451 _transient Database *database_;
7453 UITableView *table_;
7454 UISegmentedControl *segment_;
7458 - (void) showDoneButton;
7459 - (void) resizeSegmentedControl;
7463 @implementation RoleController
7467 [container_ release];
7472 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7473 if ((self = [super init])) {
7474 database_ = database;
7475 roledelegate_ = delegate;
7477 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7479 NSArray *items = [NSArray arrayWithObjects:
7481 UCLocalize("HACKER"),
7482 UCLocalize("DEVELOPER"),
7484 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7485 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7486 [container_ addSubview:segment_];
7489 if ([Role_ isEqualToString:@"User"]) index = 0;
7490 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7491 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7493 [segment_ setSelectedSegmentIndex:index];
7494 [self showDoneButton];
7497 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7498 [self resizeSegmentedControl];
7500 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7501 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7502 [table_ setDelegate:self];
7503 [table_ setDataSource:self];
7504 [[self view] addSubview:table_];
7505 [table_ reloadData];
7509 - (void) resizeSegmentedControl {
7510 CGFloat width = [[self view] frame].size.width;
7511 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7514 - (void) viewWillAppear:(BOOL)animated {
7515 [super viewWillAppear:animated];
7517 [self resizeSegmentedControl];
7520 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7521 [self resizeSegmentedControl];
7524 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7525 [self resizeSegmentedControl];
7529 NSString *role(nil);
7531 switch ([segment_ selectedSegmentIndex]) {
7532 case 0: role = @"User"; break;
7533 case 1: role = @"Hacker"; break;
7534 case 2: role = @"Developer"; break;
7539 if (![role isEqualToString:Role_]) {
7540 bool rolling(Role_ == nil);
7543 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7547 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7552 [roledelegate_ loadData];
7554 [roledelegate_ updateData];
7558 - (void) segmentChanged:(UISegmentedControl *)control {
7559 [self showDoneButton];
7562 - (void) doneButtonClicked {
7564 [[self navigationController] dismissModalViewControllerAnimated:YES];
7567 - (void) showDoneButton {
7568 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7569 initWithTitle:UCLocalize("DONE")
7570 style:UIBarButtonItemStyleDone
7572 action:@selector(doneButtonClicked)
7574 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7575 [rightItem release];
7578 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7579 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7583 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7587 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7588 return nil; // This method is required by the protocol.
7591 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7593 return UCLocalize("ROLE_EX");
7595 return [NSString stringWithFormat:
7596 @"%@: %@\n%@: %@\n%@: %@",
7597 UCLocalize("USER"), UCLocalize("USER_EX"),
7598 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7599 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7604 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7605 if (section == 3) return 44.0f;
7609 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7610 if (section == 3) return container_;
7616 /* Stash Controller {{{ */
7617 @interface CYStashController : CYViewController {
7618 UIActivityIndicatorView *spinner_;
7624 @implementation CYStashController
7626 if ((self = [super init])) {
7627 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7629 spinner_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
7630 CGRect spinrect = [spinner_ frame];
7631 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7632 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7633 [spinner_ setFrame:spinrect];
7634 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7635 [[self view] addSubview:spinner_];
7637 [spinner_ startAnimating];
7640 captrect.size.width = [[self view] frame].size.width;
7641 captrect.size.height = 40.0f;
7642 captrect.origin.x = 0;
7643 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7644 caption_ = [[UILabel alloc] initWithFrame:captrect];
7645 [caption_ setText:@"Initializing Filesystem"];
7646 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7647 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7648 [caption_ setTextColor:[UIColor whiteColor]];
7649 [caption_ setBackgroundColor:[UIColor clearColor]];
7650 [caption_ setShadowColor:[UIColor blackColor]];
7651 [caption_ setTextAlignment:UITextAlignmentCenter];
7652 [[self view] addSubview:caption_];
7656 statusrect.size.width = [[self view] frame].size.width;
7657 statusrect.size.height = 30.0f;
7658 statusrect.origin.x = 0;
7659 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7660 status_ = [[UILabel alloc] initWithFrame:statusrect];
7661 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7662 [status_ setText:@"(Cydia will exit when complete.)"];
7663 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7664 [status_ setTextColor:[UIColor whiteColor]];
7665 [status_ setBackgroundColor:[UIColor clearColor]];
7666 [status_ setShadowColor:[UIColor blackColor]];
7667 [status_ setTextAlignment:UITextAlignmentCenter];
7668 [[self view] addSubview:status_];
7673 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7674 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7679 /* Cydia Container {{{ */
7680 @interface CYContainer : UIViewController <ProgressDelegate> {
7681 _transient Database *database_;
7682 RefreshBar *refreshbar_;
7687 UITabBarController *root_;
7690 - (void) setTabBarController:(UITabBarController *)controller;
7692 - (void) dropBar:(BOOL)animated;
7693 - (void) beginUpdate;
7694 - (void) raiseBar:(BOOL)animated;
7699 @implementation CYContainer
7701 - (BOOL) _reallyWantsFullScreenLayout {
7705 // NOTE: UIWindow only sends the top controller these messages,
7706 // So we have to forward them on.
7708 - (void) viewDidAppear:(BOOL)animated {
7709 [super viewDidAppear:animated];
7710 [root_ viewDidAppear:animated];
7713 - (void) viewWillAppear:(BOOL)animated {
7714 [super viewWillAppear:animated];
7715 [root_ viewWillAppear:animated];
7718 - (void) viewDidDisappear:(BOOL)animated {
7719 [super viewDidDisappear:animated];
7720 [root_ viewDidDisappear:animated];
7723 - (void) viewWillDisappear:(BOOL)animated {
7724 [super viewWillDisappear:animated];
7725 [root_ viewWillDisappear:animated];
7728 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7729 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7732 - (void) setTabBarController:(UITabBarController *)controller {
7734 [[self view] addSubview:[root_ view]];
7737 - (void) setUpdate:(NSDate *)date {
7741 - (void) beginUpdate {
7743 [refreshbar_ start];
7748 detachNewThreadSelector:@selector(performUpdate)
7754 - (void) performUpdate { _pooled
7756 status.setDelegate(self);
7757 [database_ updateWithStatus:status];
7760 performSelectorOnMainThread:@selector(completeUpdate)
7766 - (void) completeUpdate {
7767 if (!updating_) return;
7770 [self raiseBar:YES];
7772 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7775 - (void) cancelUpdate {
7777 [self raiseBar:YES];
7779 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7782 - (void) cancelPressed {
7783 [self cancelUpdate];
7790 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7791 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7794 - (void) startProgress {
7797 - (void) setProgressTitle:(NSString *)title {
7799 performSelectorOnMainThread:@selector(_setProgressTitle:)
7805 - (bool) isCancelling:(size_t)received {
7809 - (void) setProgressPercent:(float)percent {
7811 performSelectorOnMainThread:@selector(_setProgressPercent:)
7812 withObject:[NSNumber numberWithFloat:percent]
7817 - (void) addProgressOutput:(NSString *)output {
7819 performSelectorOnMainThread:@selector(_addProgressOutput:)
7825 - (void) _setProgressTitle:(NSString *)title {
7826 [refreshbar_ setPrompt:title];
7829 - (void) _setProgressPercent:(NSNumber *)percent {
7830 [refreshbar_ setProgress:[percent floatValue]];
7833 - (void) _addProgressOutput:(NSString *)output {
7836 - (void) setUpdateDelegate:(id)delegate {
7837 updatedelegate_ = delegate;
7840 - (CGFloat) statusBarHeight {
7841 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7842 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7844 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7848 - (void) dropBar:(BOOL)animated {
7849 if (dropped_) return;
7852 [[self view] addSubview:refreshbar_];
7854 CGFloat sboffset = [self statusBarHeight];
7856 CGRect barframe = [refreshbar_ frame];
7857 barframe.origin.y = sboffset;
7858 [refreshbar_ setFrame:barframe];
7860 if (animated) [UIView beginAnimations:nil context:NULL];
7861 CGRect viewframe = [[root_ view] frame];
7862 viewframe.origin.y += barframe.size.height + sboffset;
7863 viewframe.size.height -= barframe.size.height + sboffset;
7864 [[root_ view] setFrame:viewframe];
7865 if (animated) [UIView commitAnimations];
7867 // Ensure bar has the proper width for our view, it might have changed
7868 barframe.size.width = viewframe.size.width;
7869 [refreshbar_ setFrame:barframe];
7871 // XXX: fix Apple's layout bug
7872 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7875 - (void) raiseBar:(BOOL)animated {
7876 if (!dropped_) return;
7879 [refreshbar_ removeFromSuperview];
7881 CGFloat sboffset = [self statusBarHeight];
7883 if (animated) [UIView beginAnimations:nil context:NULL];
7884 CGRect barframe = [refreshbar_ frame];
7885 CGRect viewframe = [[root_ view] frame];
7886 viewframe.origin.y -= barframe.size.height + sboffset;
7887 viewframe.size.height += barframe.size.height + sboffset;
7888 [[root_ view] setFrame:viewframe];
7889 if (animated) [UIView commitAnimations];
7891 // XXX: fix Apple's layout bug
7892 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7895 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7896 // XXX: fix Apple's layout bug
7897 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7900 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7906 // XXX: fix Apple's layout bug
7907 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7910 - (void) statusBarFrameChanged:(NSNotification *)notification {
7918 [refreshbar_ release];
7919 [[NSNotificationCenter defaultCenter] removeObserver:self];
7923 - (id) initWithDatabase:(Database *)database {
7924 if ((self = [super init]) != nil) {
7925 database_ = database;
7927 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7928 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7930 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7947 @interface Cydia : UIApplication <
7948 ConfirmationControllerDelegate,
7949 ProgressControllerDelegate,
7951 UINavigationControllerDelegate
7954 CYContainer *container_;
7957 NSMutableArray *essential_;
7958 NSMutableArray *broken_;
7960 Database *database_;
7964 UIKeyboard *keyboard_;
7965 UIProgressHUD *hud_;
7967 SectionsController *sections_;
7968 ChangesController *changes_;
7969 ManageController *manage_;
7970 SearchController *search_;
7971 SourceTable *sources_;
7972 InstalledController *installed_;
7975 CYStashController *stash_;
7980 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7981 - (void) setPage:(CYViewController *)page;
7986 static _finline void _setHomePage(Cydia *self) {
7987 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7990 @implementation Cydia
7992 - (void) beginUpdate {
7993 [container_ beginUpdate];
7997 return [container_ updating];
8000 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8005 if ([broken_ count] != 0) {
8006 int count = [broken_ count];
8008 UIAlertView *alert = [[[UIAlertView alloc]
8009 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8010 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8012 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8013 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8016 [alert setContext:@"fixhalf"];
8018 } else if (!Ignored_ && [essential_ count] != 0) {
8019 int count = [essential_ count];
8021 UIAlertView *alert = [[[UIAlertView alloc]
8022 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8023 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8025 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8026 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8029 [alert setContext:@"upgrade"];
8034 - (void) _saveConfig {
8037 NSString *error(nil);
8038 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8040 NSError *error(nil);
8041 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8042 NSLog(@"failure to save metadata data: %@", error);
8045 NSLog(@"failure to serialize metadata: %@", error);
8053 - (void) _updateData {
8056 /* XXX: this is just stupid */
8057 if (tag_ != 1 && sections_ != nil)
8058 [sections_ reloadData];
8059 if (tag_ != 2 && changes_ != nil)
8060 [changes_ reloadData];
8061 if (tag_ != 4 && search_ != nil)
8062 [search_ reloadData];
8064 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8067 - (int)indexOfTabWithTag:(int)tag {
8069 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8070 if ([[controller tabBarItem] tag] == tag) return i;
8077 - (void) _refreshIfPossible {
8078 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8080 bool recently = false;
8081 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8082 if (update != nil) {
8083 NSTimeInterval interval([update timeIntervalSinceNow]);
8084 if (interval <= 0 && interval > -(15*60))
8088 // Don't automatic refresh if:
8089 // - We already refreshed recently.
8090 // - We already auto-refreshed this launch.
8091 // - Auto-refresh is disabled.
8092 if (recently || loaded_ || ManualRefresh) {
8093 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8095 // If we are cancelling due to ManualRefresh or a recent refresh
8096 // we need to make sure it knows it's already loaded.
8100 // We are going to load, so remember that.
8104 SCNetworkReachabilityFlags flags; {
8105 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8106 SCNetworkReachabilityGetFlags(reachability, &flags);
8107 CFRelease(reachability);
8110 // XXX: this elaborate mess is what Apple is using to determine this? :(
8111 // XXX: do we care if the user has to intervene? maybe that's ok?
8113 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8114 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8115 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8116 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8117 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8118 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8122 // If we can reach the server, auto-refresh!
8124 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8129 - (void) refreshIfPossible {
8130 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8133 - (void) _reloadData {
8134 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8135 [hud setText:UCLocalize("RELOADING_DATA")];
8137 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8140 if (hud) [self removeProgressHUD:hud];
8144 [essential_ removeAllObjects];
8145 [broken_ removeAllObjects];
8147 NSArray *packages([database_ packages]);
8148 for (Package *package in packages) {
8150 [broken_ addObject:package];
8151 if ([package upgradableAndEssential:NO]) {
8152 if ([package essential])
8153 [essential_ addObject:package];
8158 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8160 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8161 [changesItem setBadgeValue:badge];
8162 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8164 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8165 [self setApplicationBadge:badge];
8167 [self setApplicationBadgeString:badge];
8169 [changesItem setBadgeValue:nil];
8170 [changesItem setAnimatedBadge:NO];
8172 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8173 [self removeApplicationBadge];
8174 else // XXX: maybe use setApplicationBadgeString also?
8175 [self setApplicationIconBadgeNumber:0];
8180 [self refreshIfPossible];
8183 - (void) updateData {
8184 [database_ setVisible];
8193 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8194 _assert(file != NULL);
8196 for (NSString *key in [Sources_ allKeys]) {
8197 NSDictionary *source([Sources_ objectForKey:key]);
8199 fprintf(file, "%s %s %s\n",
8200 [[source objectForKey:@"Type"] UTF8String],
8201 [[source objectForKey:@"URI"] UTF8String],
8202 [[source objectForKey:@"Distribution"] UTF8String]
8210 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8211 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8212 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8213 [container_ presentModalViewController:navigation animated:YES];
8216 detachNewThreadSelector:@selector(update_)
8219 title:UCLocalize("UPDATING_SOURCES")
8223 - (void) reloadData {
8224 @synchronized (self) {
8230 pkgProblemResolver *resolver = [database_ resolver];
8232 resolver->InstallProtect();
8233 if (!resolver->Resolve(true))
8237 - (CGRect) popUpBounds {
8238 return [[tabbar_ view] bounds];
8242 if (![database_ prepare])
8245 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8246 [page setDelegate:self];
8247 CYNavigationController *confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8248 [confirm_ setDelegate:self];
8250 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8251 [container_ presentModalViewController:confirm_ animated:YES];
8257 @synchronized (self) {
8262 - (void) clearPackage:(Package *)package {
8263 @synchronized (self) {
8270 - (void) installPackages:(NSArray *)packages {
8271 @synchronized (self) {
8272 for (Package *package in packages)
8279 - (void) installPackage:(Package *)package {
8280 @synchronized (self) {
8287 - (void) removePackage:(Package *)package {
8288 @synchronized (self) {
8295 - (void) distUpgrade {
8296 @synchronized (self) {
8297 if (![database_ upgrade])
8304 @synchronized (self) {
8309 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8310 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8312 if (navigation != nil) {
8313 [navigation pushViewController:progress animated:YES];
8315 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8316 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8317 [container_ presentModalViewController:navigation animated:YES];
8321 detachNewThreadSelector:@selector(perform)
8324 title:UCLocalize("RUNNING")
8328 - (void) progressControllerIsComplete:(ProgressController *)progress {
8332 - (void) setPage:(CYViewController *)page {
8333 [page setDelegate:self];
8335 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8336 [navController setViewControllers:[NSArray arrayWithObject:page]];
8337 for (CYNavigationController *page in [tabbar_ viewControllers]) {
8338 if (page != navController) [page setViewControllers:nil];
8342 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8343 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8344 [browser loadURL:url];
8348 - (SectionsController *) sectionsController {
8349 if (sections_ == nil)
8350 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8354 - (ChangesController *) changesController {
8355 if (changes_ == nil)
8356 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8360 - (ManageController *) manageController {
8361 if (manage_ == nil) {
8362 manage_ = (ManageController *) [[self
8363 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8364 withClass:[ManageController class]
8366 if (!IsWildcat_) queueDelegate_ = manage_;
8371 - (SearchController *) searchController {
8373 search_ = [[SearchController alloc] initWithDatabase:database_];
8377 - (SourceTable *) sourcesController {
8378 if (sources_ == nil)
8379 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8383 - (InstalledController *) installedController {
8384 if (installed_ == nil) {
8385 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8386 if (IsWildcat_) queueDelegate_ = installed_;
8391 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8392 int tag = [[viewController tabBarItem] tag];
8394 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8396 } else if (tag_ == 1) {
8397 [[self sectionsController] resetView];
8401 case kCydiaTag: _setHomePage(self); break;
8403 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8404 case kChangesTag: [self setPage:[self changesController]]; break;
8405 case kManageTag: [self setPage:[self manageController]]; break;
8406 case kInstalledTag: [self setPage:[self installedController]]; break;
8407 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8408 case kSearchTag: [self setPage:[self searchController]]; break;
8416 - (void) showSettings {
8417 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8418 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
8419 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8420 [container_ presentModalViewController:nav animated:YES];
8423 - (void) setPackageController:(PackageController *)view {
8425 [view setPackage:nil];
8429 - (PackageController *) _packageController {
8430 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8433 - (PackageController *) packageController {
8434 return [self _packageController];
8437 // Returns the navigation controller for the queuing badge.
8438 - (id) queueBadgeController {
8439 int index = [self indexOfTabWithTag:kManageTag];
8440 if (index == -1) index = [self indexOfTabWithTag:kInstalledTag];
8442 return [[tabbar_ viewControllers] objectAtIndex:index];
8445 - (void) cancelAndClear:(bool)clear {
8446 @synchronized (self) {
8449 pkgCacheFile &cache([database_ cache]);
8450 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8451 // Unmark method taken from Synaptic Package Manager.
8452 // Thanks for being sane, unlike Aptitude.
8453 if (!cache[iterator].Keep()) {
8454 cache->MarkKeep(iterator, false);
8455 cache->SetReInstall(iterator, false);
8461 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8465 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8468 // Show the changes in the current view.
8469 [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
8470 [queueDelegate_ queueStatusDidChange];
8474 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8475 NSString *context([alert context]);
8477 if ([context isEqualToString:@"fixhalf"]) {
8478 if (button == [alert firstOtherButtonIndex]) {
8479 @synchronized (self) {
8480 for (Package *broken in broken_) {
8483 NSString *id = [broken id];
8484 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8485 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8486 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8487 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8493 } else if (button == [alert cancelButtonIndex]) {
8494 [broken_ removeAllObjects];
8498 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8499 } else if ([context isEqualToString:@"upgrade"]) {
8500 if (button == [alert firstOtherButtonIndex]) {
8501 @synchronized (self) {
8502 for (Package *essential in essential_)
8503 [essential install];
8508 } else if (button == [alert firstOtherButtonIndex] + 1) {
8510 } else if (button == [alert cancelButtonIndex]) {
8514 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8518 - (void) system:(NSString *)command { _pooled
8519 system([command UTF8String]);
8522 - (void) applicationWillSuspend {
8524 [super applicationWillSuspend];
8527 - (void) applicationSuspend:(__GSEvent *)event {
8528 // Use external process status API internally.
8529 // This is probably a really bad idea.
8530 uint64_t status = 0;
8532 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8533 notify_get_state(notify_token, &status);
8534 notify_cancel(notify_token);
8537 if (hud_ == nil && status == 0)
8538 [super applicationSuspend:event];
8541 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8543 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8546 - (void) _setSuspended:(BOOL)value {
8548 [super _setSuspended:value];
8551 - (UIProgressHUD *) addProgressHUD {
8552 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8553 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8555 [window_ setUserInteractionEnabled:NO];
8558 UIViewController *target = container_;
8559 while ([target modalViewController] != nil) target = [target modalViewController];
8560 [[target view] addSubview:hud];
8565 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8567 [hud removeFromSuperview];
8568 [window_ setUserInteractionEnabled:YES];
8571 - (CYViewController *) pageForPackage:(NSString *)name {
8572 if (Package *package = [database_ packageWithName:name]) {
8573 PackageController *view([self packageController]);
8574 [view setPackage:package];
8577 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8578 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8579 return [self _pageForURL:url withClass:[CYBrowserController class]];
8583 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8587 NSString *href([url absoluteString]);
8588 if ([href hasPrefix:@"apptapp://package/"])
8589 return [self pageForPackage:[href substringFromIndex:18]];
8591 NSString *scheme([[url scheme] lowercaseString]);
8592 if (![scheme isEqualToString:@"cydia"])
8594 NSString *path([url absoluteString]);
8595 if ([path length] < 8)
8597 path = [path substringFromIndex:8];
8598 if (![path hasPrefix:@"/"])
8599 path = [@"/" stringByAppendingString:path];
8601 if ([path isEqualToString:@"/add-source"])
8602 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8603 else if ([path isEqualToString:@"/storage"])
8604 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8605 else if ([path isEqualToString:@"/sources"])
8606 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8607 else if ([path isEqualToString:@"/packages"])
8608 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8609 else if ([path hasPrefix:@"/url/"])
8610 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8611 else if ([path hasPrefix:@"/launch/"])
8612 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8613 else if ([path hasPrefix:@"/package-settings/"])
8614 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8615 else if ([path hasPrefix:@"/package-signature/"])
8616 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8617 else if ([path hasPrefix:@"/package/"])
8618 return [self pageForPackage:[path substringFromIndex:9]];
8619 else if ([path hasPrefix:@"/files/"]) {
8620 NSString *name = [path substringFromIndex:7];
8622 if (Package *package = [database_ packageWithName:name]) {
8623 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8624 [files setPackage:package];
8632 - (void) applicationOpenURL:(NSURL *)url {
8633 [super applicationOpenURL:url];
8635 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8636 [self setPage:page];
8638 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8642 - (void) applicationWillResignActive:(UIApplication *)application {
8643 // Stop refreshing if you get a phone call or lock the device.
8644 if ([container_ updating]) [container_ cancelUpdate];
8646 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8647 [super applicationWillResignActive:application];
8650 - (void) addStashController {
8651 stash_ = [[CYStashController alloc] init];
8652 [window_ addSubview:[stash_ view]];
8655 - (void) removeStashController {
8656 [[stash_ view] removeFromSuperview];
8661 [self setIdleTimerDisabled:YES];
8663 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8664 [self setStatusBarShowsProgress:YES];
8665 UpdateExternalStatus(1);
8667 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8669 UpdateExternalStatus(0);
8670 [self setStatusBarShowsProgress:NO];
8672 [self removeStashController];
8674 if (ExecFork() == 0) {
8675 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8676 perror("launchctl stop");
8680 - (void) setupTabBarController {
8681 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8682 [tabbar_ setDelegate:self];
8684 NSMutableArray *items([NSMutableArray arrayWithObjects:
8685 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8686 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8687 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8688 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8692 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8693 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8695 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8698 NSMutableArray *controllers([NSMutableArray array]);
8700 for (UITabBarItem *item in items) {
8701 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8702 [controller setTabBarItem:item];
8703 [controllers addObject:controller];
8706 [tabbar_ setViewControllers:controllers];
8707 [tabbar_ setSelectedIndex:0];
8710 - (void) applicationDidFinishLaunching:(id)unused {
8711 [CYBrowserController _initialize];
8713 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8715 Font12_ = [[UIFont systemFontOfSize:12] retain];
8716 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8717 Font14_ = [[UIFont systemFontOfSize:14] retain];
8718 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8719 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8723 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8724 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8726 UIScreen *screen([UIScreen mainScreen]);
8728 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8729 [window_ orderFront:self];
8730 [window_ makeKey:self];
8731 [window_ setHidden:NO];
8734 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8735 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8736 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8737 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8738 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8739 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8740 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8741 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8742 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8745 [self addStashController];
8746 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8750 database_ = [Database sharedInstance];
8752 [self setupTabBarController];
8754 container_ = [[CYContainer alloc] initWithDatabase:database_];
8755 [container_ setUpdateDelegate:self];
8756 [container_ setTabBarController:tabbar_];
8757 [window_ addSubview:[container_ view]];
8759 // Show pinstripes while loading data.
8760 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8762 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8767 [self showSettings];
8771 [UIKeyboard initImplementationNow];
8773 [window_ setUserInteractionEnabled:NO];
8775 UIView *container = [[UIView alloc] init];
8776 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8778 UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
8779 [spinner startAnimating];
8780 [container addSubview:spinner];
8783 UILabel *label = [[UILabel alloc] init];
8784 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8785 [label setBackgroundColor:[UIColor clearColor]];
8786 [label setTextColor:[UIColor blackColor]];
8787 [label setShadowColor:[UIColor whiteColor]];
8788 [label setShadowOffset:CGSizeMake(0, 1)];
8789 [label setText:UCLocalize("LOADING_DATA")];
8790 [container addSubview:label];
8793 CGSize viewsize = [[tabbar_ view] frame].size;
8794 CGSize spinnersize = [spinner bounds].size;
8795 CGSize textsize = [[label text] sizeWithFont:[label font]];
8796 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8798 CGRect containrect = {
8799 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8800 CGSizeMake(bothwidth, spinnersize.height)
8803 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8811 [container setFrame:containrect];
8812 [spinner setFrame:spinrect];
8813 [label setFrame:textrect];
8814 [[container_ view] addSubview:container];
8815 [container release];
8820 // Show the home page
8822 [window_ setUserInteractionEnabled:YES];
8824 // XXX: does this actually slow anything down?
8825 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8826 [container removeFromSuperview];
8829 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8830 if (item != nil && IsWildcat_) {
8831 [sheet showFromBarButtonItem:item animated:YES];
8833 [sheet showInView:window_];
8840 id Alloc_(id self, SEL selector) {
8841 id object = alloc_(self, selector);
8842 lprintf("[%s]A-%p\n", self->isa->name, object);
8847 id Dealloc_(id self, SEL selector) {
8848 id object = dealloc_(self, selector);
8849 lprintf("[%s]D-%p\n", self->isa->name, object);
8853 Class $WebDefaultUIKitDelegate;
8855 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8856 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8857 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8858 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8861 static NSNumber *shouldPlayKeyboardSounds;
8865 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8867 case 1104: // Keyboard Button Clicked
8868 case 1105: // Keyboard Delete Repeated
8869 if (shouldPlayKeyboardSounds == nil) {
8870 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8871 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8874 if (![shouldPlayKeyboardSounds boolValue])
8878 _UIHardware$_playSystemSound$(self, _cmd, sound);
8882 int main(int argc, char *argv[]) { _pooled
8885 if (Class $UIDevice = objc_getClass("UIDevice")) {
8886 UIDevice *device([$UIDevice currentDevice]);
8887 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8891 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8893 /* Library Hacks {{{ */
8894 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8896 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8897 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8898 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8899 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8900 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8903 $UIHardware = objc_getClass("UIHardware");
8904 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8905 if (UIHardware$_playSystemSound$ != NULL) {
8906 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8907 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8910 /* Set Locale {{{ */
8911 Locale_ = CFLocaleCopyCurrent();
8912 Languages_ = [NSLocale preferredLanguages];
8913 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8914 //NSLog(@"%@", [Languages_ description]);
8917 if (Languages_ == nil || [Languages_ count] == 0)
8918 // XXX: consider just setting to C and then falling through?
8921 lang = [[Languages_ objectAtIndex:0] UTF8String];
8922 setenv("LANG", lang, true);
8925 //std::setlocale(LC_ALL, lang);
8926 NSLog(@"Setting Language: %s", lang);
8929 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8931 /* Parse Arguments {{{ */
8932 bool substrate(false);
8938 for (int argi(1); argi != argc; ++argi)
8939 if (strcmp(argv[argi], "--") == 0) {
8941 argv[argi] = argv[0];
8947 for (int argi(1); argi != arge; ++argi)
8948 if (strcmp(args[argi], "--substrate") == 0)
8951 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8955 App_ = [[NSBundle mainBundle] bundlePath];
8956 Home_ = NSHomeDirectory();
8962 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8963 alloc_ = alloc->method_imp;
8964 alloc->method_imp = (IMP) &Alloc_;*/
8966 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8967 dealloc_ = dealloc->method_imp;
8968 dealloc->method_imp = (IMP) &Dealloc_;*/
8970 /* System Information {{{ */
8974 size = sizeof(maxproc);
8975 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8976 perror("sysctlbyname(\"kern.maxproc\", ?)");
8977 else if (maxproc < 64) {
8979 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8980 perror("sysctlbyname(\"kern.maxproc\", #)");
8983 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8984 char *osversion = new char[size];
8985 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8986 perror("sysctlbyname(\"kern.osversion\", ?)");
8988 System_ = [NSString stringWithUTF8String:osversion];
8990 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8991 char *machine = new char[size];
8992 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8993 perror("sysctlbyname(\"hw.machine\", ?)");
8997 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8998 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8999 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9000 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9004 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9005 NSData *data((NSData *) ecid);
9006 size_t length([data length]);
9007 uint8_t bytes[length];
9008 [data getBytes:bytes];
9009 char string[length * 2 + 1];
9010 for (size_t i(0); i != length; ++i)
9011 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9012 ChipID_ = [NSString stringWithUTF8String:string];
9016 IOObjectRelease(service);
9020 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9022 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9023 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9024 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9026 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9027 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9028 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9030 if (mcc != NULL && mnc != NULL)
9031 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9038 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9039 Build_ = [system objectForKey:@"ProductBuildVersion"];
9040 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9041 Product_ = [info objectForKey:@"SafariProductVersion"];
9042 Safari_ = [info objectForKey:@"CFBundleVersion"];
9045 /* Load Database {{{ */
9047 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9049 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9052 if (Metadata_ == NULL)
9053 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9055 Settings_ = [Metadata_ objectForKey:@"Settings"];
9057 Packages_ = [Metadata_ objectForKey:@"Packages"];
9058 Sections_ = [Metadata_ objectForKey:@"Sections"];
9059 Sources_ = [Metadata_ objectForKey:@"Sources"];
9061 Token_ = [Metadata_ objectForKey:@"Token"];
9064 if (Settings_ != nil)
9065 Role_ = [Settings_ objectForKey:@"Role"];
9067 if (Packages_ == nil) {
9068 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9069 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9072 if (Sections_ == nil) {
9073 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9074 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9077 if (Sources_ == nil) {
9078 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9079 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9083 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9085 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9086 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9087 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9088 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9089 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9090 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9092 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9094 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9095 unlink("/tmp/.cydia.fw");
9097 } else if (access("/User", F_OK) != 0 || version < 2) {
9100 system("/usr/libexec/cydia/firmware.sh");
9104 _assert([[NSFileManager defaultManager]
9105 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9106 withIntermediateDirectories:YES
9111 if (access("/tmp/cydia.chk", F_OK) == 0) {
9112 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9113 _assert(errno == ENOENT);
9114 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9115 _assert(errno == ENOENT);
9118 /* APT Initialization {{{ */
9119 _assert(pkgInitConfig(*_config));
9120 _assert(pkgInitSystem(*_config, _system));
9123 _config->Set("APT::Acquire::Translation", lang);
9125 // XXX: this timeout might be important :(
9126 //_config->Set("Acquire::http::Timeout", 15);
9128 _config->Set("Acquire::http::MaxParallel", 3);
9130 /* Color Choices {{{ */
9131 space_ = CGColorSpaceCreateDeviceRGB();
9133 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9134 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9135 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9136 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9137 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9138 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9139 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9140 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9141 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9143 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9144 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9146 /* UIKit Configuration {{{ */
9147 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9148 if ($GSFontSetUseLegacyFontMetrics != NULL)
9149 $GSFontSetUseLegacyFontMetrics(YES);
9151 // XXX: I have a feeling this was important
9152 //UIKeyboardDisableAutomaticAppearance();
9155 Colon_ = UCLocalize("COLON_DELIMITED");
9156 Error_ = UCLocalize("ERROR");
9157 Warning_ = UCLocalize("WARNING");
9160 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9162 CGColorSpaceRelease(space_);