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]))
1956 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1958 /* XXX: ntohl may be more honest */
1959 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1962 CYString &(*PackageName)(Package *self, SEL sel);
1964 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1965 _profile(PackageNameCompare)
1966 CYString &lhi(PackageName(lhs, @selector(cyname)));
1967 CYString &rhi(PackageName(rhs, @selector(cyname)));
1968 CFStringRef lhn(lhi), rhn(rhi);
1971 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1972 else if (rhn == NULL)
1973 return NSOrderedDescending;
1975 _profile(PackageNameCompare$NumbersLast)
1976 if (!lhi.empty() && !rhi.empty()) {
1977 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1978 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1979 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1980 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1981 return lha ? NSOrderedAscending : NSOrderedDescending;
1985 CFIndex length = CFStringGetLength(lhn);
1987 _profile(PackageNameCompare$Compare)
1988 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1993 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1994 return PackageNameCompare(*lhs, *rhs, context);
1997 struct PackageNameOrdering :
1998 std::binary_function<Package *, Package *, bool>
2000 _finline bool operator ()(Package *lhs, Package *rhs) const {
2001 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2005 @implementation Package
2007 - (NSString *) description {
2008 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2014 if (section$_ != nil)
2015 [section$_ release];
2020 if (sponsor$_ != nil)
2021 [sponsor$_ release];
2022 if (author$_ != nil)
2029 if (relationships_ != nil)
2030 [relationships_ release];
2031 if (metadata_ != nil)
2032 [metadata_ release];
2037 + (NSString *) webScriptNameForSelector:(SEL)selector {
2038 if (selector == @selector(hasTag:))
2044 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2045 return [self webScriptNameForSelector:selector] == nil;
2048 + (NSArray *) _attributeKeys {
2049 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];
2052 - (NSArray *) attributeKeys {
2053 return [[self class] _attributeKeys];
2056 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2057 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2067 _profile(Package$parse)
2068 pkgRecords::Parser *parser;
2070 _profile(Package$parse$Lookup)
2071 parser = &[database_ records]->Lookup(file_);
2076 _profile(Package$parse$Find)
2082 {"depiction", &depiction_},
2083 {"homepage", &homepage_},
2084 {"website", &website},
2086 {"support", &support_},
2087 {"sponsor", &sponsor_},
2088 {"author", &author_},
2091 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2092 const char *start, *end;
2094 if (parser->Find(names[i].name_, start, end)) {
2095 CYString &value(*names[i].value_);
2096 _profile(Package$parse$Value)
2097 value.set(pool_, start, end - start);
2103 _profile(Package$parse$Tagline)
2104 const char *start, *end;
2105 if (parser->ShortDesc(start, end)) {
2106 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2109 while (stop != start && stop[-1] == '\r')
2111 tagline_.set(pool_, start, stop - start);
2115 _profile(Package$parse$Retain)
2116 if (homepage_.empty())
2117 homepage_ = website;
2118 if (homepage_ == depiction_)
2124 - (void) setVisible {
2125 visible_ = required_ && [self unfiltered];
2128 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2129 if ((self = [super init]) != nil) {
2130 _profile(Package$initWithVersion)
2131 era_ = [database era];
2135 iterator_ = version.ParentPkg();
2136 database_ = database;
2138 _profile(Package$initWithVersion$Latest)
2139 latest_ = (NSString *) StripVersion(version_.VerStr());
2142 pkgCache::VerIterator current;
2143 _profile(Package$initWithVersion$Versions)
2144 current = iterator_.CurrentVer();
2146 installed_.set(pool_, StripVersion_(current.VerStr()));
2148 if (!version_.end())
2149 file_ = version_.FileList();
2151 pkgCache &cache([database_ cache]);
2152 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2156 _profile(Package$initWithVersion$Name)
2157 id_.set(pool_, iterator_.Name());
2158 name_.set(pool, iterator_.Display());
2161 _profile(Package$lowercaseString)
2162 char *data(id_.data());
2163 for (size_t i(0), e(id_.size()); i != e; ++i)
2164 // XXX: do not use tolower() as this is not locale-specific? :(
2169 _profile(Package$initWithVersion$Source)
2170 source_ = [database_ getSource:file_.File()];
2179 _profile(Package$initWithVersion$Tags)
2180 pkgCache::TagIterator tag(iterator_.TagList());
2182 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2184 const char *name(tag.Name());
2185 [tags_ addObject:(NSString *)CFCString(name)];
2186 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2187 role_ = (NSString *) CFCString(name + 6);
2188 if (required_ && strncmp(name, "require::", 9) == 0 && (
2193 } while (!tag.end());
2197 bool changed(false);
2199 _profile(Package$initWithVersion$Metadata)
2200 metadata_ = [Packages_ objectForKey:id_];
2202 if (metadata_ == nil) {
2205 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2206 firstSeen_, @"FirstSeen",
2207 latest_, @"LastVersion",
2212 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2213 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2215 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2216 subscribed_ = [subscribed boolValue];
2218 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2220 if (firstSeen_ == nil) {
2221 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2222 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2226 if (version == nil) {
2227 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2229 } else if (![version isEqualToString:latest_]) {
2230 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2232 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2237 metadata_ = [metadata_ retain];
2240 [Packages_ setObject:metadata_ forKey:id_];
2245 _profile(Package$initWithVersion$Section)
2246 section_.set(pool_, iterator_.Section());
2249 obsolete_ = [self hasTag:@"cydia::obsolete"];
2250 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2255 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2256 pkgCache::VerIterator version;
2258 _profile(Package$packageWithIterator$GetCandidateVer)
2259 version = [database policy]->GetCandidateVer(iterator);
2265 return [[[Package alloc]
2266 initWithVersion:version
2273 - (pkgCache::PkgIterator) iterator {
2277 - (NSString *) section {
2278 if (section$_ == nil) {
2279 if (section_.empty())
2282 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2283 NSString *name(section_);
2286 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2287 if (NSString *rename = [value objectForKey:@"Rename"]) {
2292 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2296 - (NSString *) simpleSection {
2297 if (NSString *section = [self section])
2298 return Simplify(section);
2303 - (NSString *) longSection {
2304 return LocalizeSection([self section]);
2307 - (NSString *) shortSection {
2308 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2311 - (NSString *) uri {
2314 pkgIndexFile *index;
2315 pkgCache::PkgFileIterator file(file_.File());
2316 if (![database_ list].FindIndex(file, index))
2318 return [NSString stringWithUTF8String:iterator_->Path];
2319 //return [NSString stringWithUTF8String:file.Site()];
2320 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2324 - (Address *) maintainer {
2327 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2328 const std::string &maintainer(parser->Maintainer());
2329 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2333 return version_.end() ? 0 : version_->InstalledSize;
2336 - (NSString *) longDescription {
2337 @synchronized (database_) {
2338 if ([database_ era] != era_ || file_.end())
2341 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2342 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2344 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2345 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2346 if ([lines count] < 2)
2349 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2350 for (size_t i(1), e([lines count]); i != e; ++i) {
2351 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2352 [trimmed addObject:trim];
2355 return [trimmed componentsJoinedByString:@"\n"];
2358 - (NSString *) shortDescription {
2363 _profile(Package$index)
2364 CFStringRef name((CFStringRef) [self name]);
2365 if (CFStringGetLength(name) == 0)
2367 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2368 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2370 return toupper(character);
2374 - (NSMutableDictionary *) metadata {
2379 if (subscribed_ && lastSeen_ != nil)
2384 - (BOOL) subscribed {
2389 NSDictionary *metadata([self metadata]);
2390 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2391 return [ignored boolValue];
2396 - (NSString *) latest {
2400 - (NSString *) installed {
2404 - (BOOL) uninstalled {
2405 return installed_.empty();
2409 return !version_.end();
2412 - (BOOL) upgradableAndEssential:(BOOL)essential {
2413 _profile(Package$upgradableAndEssential)
2414 pkgCache::VerIterator current(iterator_.CurrentVer());
2416 return essential && essential_ && visible_;
2418 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2422 - (BOOL) essential {
2427 return [database_ cache][iterator_].InstBroken();
2430 - (BOOL) unfiltered {
2431 NSString *section([self section]);
2432 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2440 unsigned char current(iterator_->CurrentState);
2441 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2444 - (BOOL) halfConfigured {
2445 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2448 - (BOOL) halfInstalled {
2449 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2453 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2454 return state.Mode != pkgDepCache::ModeKeep;
2457 - (NSString *) mode {
2458 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2460 switch (state.Mode) {
2461 case pkgDepCache::ModeDelete:
2462 if ((state.iFlags & pkgDepCache::Purge) != 0)
2466 case pkgDepCache::ModeKeep:
2467 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2468 return @"REINSTALL";
2469 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2473 case pkgDepCache::ModeInstall:
2474 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2475 return @"REINSTALL";
2476 else*/ switch (state.Status) {
2478 return @"DOWNGRADE";
2484 return @"NEW_INSTALL";
2495 - (NSString *) name {
2496 return name_.empty() ? id_ : name_;
2499 - (UIImage *) icon {
2500 NSString *section = [self simpleSection];
2504 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2505 // XXX: correct escaping
2506 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2507 if (icon == nil) if (section != nil)
2508 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2509 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2510 if ([dicon hasPrefix:@"file:///"])
2511 // XXX: correct escaping
2512 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2514 icon = [UIImage applicationImageNamed:@"unknown.png"];
2518 - (NSString *) homepage {
2522 - (NSString *) depiction {
2523 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2526 - (Address *) sponsor {
2527 if (sponsor$_ == nil) {
2528 if (sponsor_.empty())
2530 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2534 - (Address *) author {
2535 if (author$_ == nil) {
2536 if (author_.empty())
2538 author$_ = [[Address addressWithString:author_] retain];
2542 - (NSString *) support {
2543 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2546 - (NSArray *) files {
2547 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2548 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2551 fin.open([path UTF8String]);
2556 while (std::getline(fin, line))
2557 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2562 - (NSArray *) relationships {
2563 return relationships_;
2566 - (NSArray *) warnings {
2567 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2568 const char *name(iterator_.Name());
2570 size_t length(strlen(name));
2571 if (length < 2) invalid:
2572 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2573 else for (size_t i(0); i != length; ++i)
2575 /* XXX: technically this is not allowed */
2576 (name[i] < 'A' || name[i] > 'Z') &&
2577 (name[i] < 'a' || name[i] > 'z') &&
2578 (name[i] < '0' || name[i] > '9') &&
2579 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2582 if (strcmp(name, "cydia") != 0) {
2585 bool _private = false;
2588 bool repository = [[self section] isEqualToString:@"Repositories"];
2590 if (NSArray *files = [self files])
2591 for (NSString *file in files)
2592 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2594 else if (!user && [file isEqualToString:@"/User"])
2596 else if (!_private && [file isEqualToString:@"/private"])
2598 else if (!stash && [file isEqualToString:@"/var/stash"])
2601 /* XXX: this is not sensitive enough. only some folders are valid. */
2602 if (cydia && !repository)
2603 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2605 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2607 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2609 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2612 return [warnings count] == 0 ? nil : warnings;
2615 - (NSArray *) applications {
2616 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2618 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2620 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2621 if (NSArray *files = [self files])
2622 for (NSString *file in files)
2623 if (application_r(file)) {
2624 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2625 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2626 if ([id isEqualToString:me])
2629 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2631 display = application_r[1];
2633 NSString *bundle([file stringByDeletingLastPathComponent]);
2634 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2635 if (icon == nil || [icon length] == 0)
2637 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2639 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2640 [applications addObject:application];
2642 [application addObject:id];
2643 [application addObject:display];
2644 [application addObject:url];
2647 return [applications count] == 0 ? nil : applications;
2650 - (Source *) source {
2652 @synchronized (database_) {
2653 if ([database_ era] != era_ || file_.end())
2656 source_ = [database_ getSource:file_.File()];
2668 - (NSString *) role {
2672 - (BOOL) matches:(NSString *)text {
2678 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2679 if (range.location != NSNotFound)
2682 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2683 if (range.location != NSNotFound)
2686 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2687 if (range.location != NSNotFound)
2693 - (bool) hasSupportingRole {
2696 if ([role_ isEqualToString:@"enduser"])
2698 if ([Role_ isEqualToString:@"User"])
2700 if ([role_ isEqualToString:@"hacker"])
2702 if ([Role_ isEqualToString:@"Hacker"])
2704 if ([role_ isEqualToString:@"developer"])
2706 if ([Role_ isEqualToString:@"Developer"])
2711 - (BOOL) hasTag:(NSString *)tag {
2712 return tags_ == nil ? NO : [tags_ containsObject:tag];
2715 - (NSString *) primaryPurpose {
2716 for (NSString *tag in tags_)
2717 if ([tag hasPrefix:@"purpose::"])
2718 return [tag substringFromIndex:9];
2722 - (NSArray *) purposes {
2723 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2724 for (NSString *tag in tags_)
2725 if ([tag hasPrefix:@"purpose::"])
2726 [purposes addObject:[tag substringFromIndex:9]];
2727 return [purposes count] == 0 ? nil : purposes;
2730 - (bool) isCommercial {
2731 return [self hasTag:@"cydia::commercial"];
2734 - (CYString &) cyname {
2735 return name_.empty() ? id_ : name_;
2738 - (uint32_t) compareBySection:(NSArray *)sections {
2739 NSString *section([self section]);
2740 for (size_t i(0), e([sections count]); i != e; ++i) {
2741 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2745 return _not(uint32_t);
2748 - (uint32_t) compareForChanges {
2753 uint32_t timestamp : 30;
2754 uint32_t ignored : 1;
2755 uint32_t upgradable : 1;
2759 bool upgradable([self upgradableAndEssential:YES]);
2760 value.bits.upgradable = upgradable ? 1 : 0;
2763 value.bits.timestamp = 0;
2764 value.bits.ignored = [self ignored] ? 0 : 1;
2765 value.bits.upgradable = 1;
2767 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2768 value.bits.ignored = 0;
2769 value.bits.upgradable = 0;
2772 return _not(uint32_t) - value.key;
2776 pkgProblemResolver *resolver = [database_ resolver];
2777 resolver->Clear(iterator_);
2778 resolver->Protect(iterator_);
2782 pkgProblemResolver *resolver = [database_ resolver];
2783 resolver->Clear(iterator_);
2784 resolver->Protect(iterator_);
2785 pkgCacheFile &cache([database_ cache]);
2786 cache->MarkInstall(iterator_, false);
2787 pkgDepCache::StateCache &state((*cache)[iterator_]);
2788 if (!state.Install())
2789 cache->SetReInstall(iterator_, true);
2793 pkgProblemResolver *resolver = [database_ resolver];
2794 resolver->Clear(iterator_);
2795 resolver->Protect(iterator_);
2796 resolver->Remove(iterator_);
2797 [database_ cache]->MarkDelete(iterator_, true);
2800 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2801 _profile(Package$isUnfilteredAndSearchedForBy)
2804 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2805 value &= [self unfiltered];
2808 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2809 value &= [self matches:search];
2816 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2817 if ([search length] == 0)
2820 _profile(Package$isUnfilteredAndSelectedForBy)
2823 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2824 value &= [self unfiltered];
2827 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2828 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2835 - (bool) isInstalledAndVisible:(NSNumber *)number {
2836 return (![number boolValue] || [self visible]) && ![self uninstalled];
2839 - (bool) isVisibleInSection:(NSString *)name {
2840 NSString *section = [self section];
2845 section == nil && [name length] == 0 ||
2846 [name isEqualToString:section]
2850 - (bool) isVisibleInSource:(Source *)source {
2851 return [self source] == source && [self visible];
2856 /* Section Class {{{ */
2857 @interface Section : NSObject {
2862 NSString *localized_;
2865 - (NSComparisonResult) compareByLocalized:(Section *)section;
2866 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2867 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2868 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2869 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2870 - (NSString *) name;
2877 - (void) addToCount;
2879 - (void) setCount:(size_t)count;
2880 - (NSString *) localized;
2884 @implementation Section
2888 if (localized_ != nil)
2889 [localized_ release];
2893 - (NSComparisonResult) compareByLocalized:(Section *)section {
2894 NSString *lhs(localized_);
2895 NSString *rhs([section localized]);
2897 /*if ([lhs length] != 0 && [rhs length] != 0) {
2898 unichar lhc = [lhs characterAtIndex:0];
2899 unichar rhc = [rhs characterAtIndex:0];
2901 if (isalpha(lhc) && !isalpha(rhc))
2902 return NSOrderedAscending;
2903 else if (!isalpha(lhc) && isalpha(rhc))
2904 return NSOrderedDescending;
2907 return [lhs compare:rhs options:LaxCompareOptions_];
2910 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2911 if ((self = [self initWithName:name localize:NO]) != nil) {
2912 if (localized != nil)
2913 localized_ = [localized retain];
2917 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2918 return [self initWithName:name row:0 localize:localize];
2921 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2922 if ((self = [super init]) != nil) {
2923 name_ = [name retain];
2927 localized_ = [LocalizeSection(name_) retain];
2931 /* XXX: localize the index thingees */
2932 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2933 if ((self = [super init]) != nil) {
2934 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2940 - (NSString *) name {
2960 - (void) addToCount {
2964 - (void) setCount:(size_t)count {
2968 - (NSString *) localized {
2975 static NSString *Colon_;
2976 static NSString *Error_;
2977 static NSString *Warning_;
2979 /* Database Implementation {{{ */
2980 @implementation Database
2982 + (Database *) sharedInstance {
2983 static Database *instance;
2984 if (instance == nil)
2985 instance = [[Database alloc] init];
2995 NSRecycleZone(zone_);
2996 // XXX: malloc_destroy_zone(zone_);
2997 apr_pool_destroy(pool_);
3001 - (void) _readCydia:(NSNumber *)fd { _pooled
3002 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3003 std::istream is(&ib);
3006 static Pcre finish_r("^finish:([^:]*)$");
3008 while (std::getline(is, line)) {
3009 const char *data(line.c_str());
3010 size_t size = line.size();
3011 lprintf("C:%s\n", data);
3013 if (finish_r(data, size)) {
3014 NSString *finish = finish_r[1];
3015 int index = [Finishes_ indexOfObject:finish];
3016 if (index != INT_MAX && index > Finish_)
3024 - (void) _readStatus:(NSNumber *)fd { _pooled
3025 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3026 std::istream is(&ib);
3029 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3030 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3032 while (std::getline(is, line)) {
3033 const char *data(line.c_str());
3034 size_t size(line.size());
3035 lprintf("S:%s\n", data);
3037 if (conffile_r(data, size)) {
3038 [delegate_ setConfigurationData:conffile_r[1]];
3039 } else if (strncmp(data, "status: ", 8) == 0) {
3040 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3041 [delegate_ setProgressTitle:string];
3042 } else if (pmstatus_r(data, size)) {
3043 std::string type([pmstatus_r[1] UTF8String]);
3044 NSString *id = pmstatus_r[2];
3046 float percent([pmstatus_r[3] floatValue]);
3047 [delegate_ setProgressPercent:(percent / 100)];
3049 NSString *string = pmstatus_r[4];
3051 if (type == "pmerror")
3052 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3053 withObject:[NSArray arrayWithObjects:string, id, nil]
3056 else if (type == "pmstatus") {
3057 [delegate_ setProgressTitle:string];
3058 } else if (type == "pmconffile")
3059 [delegate_ setConfigurationData:string];
3061 lprintf("E:unknown pmstatus\n");
3063 lprintf("E:unknown status\n");
3069 - (void) _readOutput:(NSNumber *)fd { _pooled
3070 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3071 std::istream is(&ib);
3074 while (std::getline(is, line)) {
3075 lprintf("O:%s\n", line.c_str());
3076 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3086 - (Package *) packageWithName:(NSString *)name {
3087 @synchronized (self) {
3088 if (static_cast<pkgDepCache *>(cache_) == NULL)
3090 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3091 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3095 if ((self = [super init]) != nil) {
3102 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3103 apr_pool_create(&pool_, NULL);
3105 packages_ = [[NSMutableArray alloc] init];
3109 _assert(pipe(fds) != -1);
3112 _config->Set("APT::Keep-Fds::", cydiafd_);
3113 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3116 detachNewThreadSelector:@selector(_readCydia:)
3118 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3121 _assert(pipe(fds) != -1);
3125 detachNewThreadSelector:@selector(_readStatus:)
3127 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3130 _assert(pipe(fds) != -1);
3131 _assert(dup2(fds[0], 0) != -1);
3132 _assert(close(fds[0]) != -1);
3134 input_ = fdopen(fds[1], "a");
3136 _assert(pipe(fds) != -1);
3137 _assert(dup2(fds[1], 1) != -1);
3138 _assert(close(fds[1]) != -1);
3141 detachNewThreadSelector:@selector(_readOutput:)
3143 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3148 - (pkgCacheFile &) cache {
3152 - (pkgDepCache::Policy *) policy {
3156 - (pkgRecords *) records {
3160 - (pkgProblemResolver *) resolver {
3164 - (pkgAcquire &) fetcher {
3168 - (pkgSourceList &) list {
3172 - (NSArray *) packages {
3176 - (NSArray *) sources {
3177 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3178 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3179 [sources addObject:i->second];
3183 - (NSArray *) issues {
3184 if (cache_->BrokenCount() == 0)
3187 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3189 for (Package *package in packages_) {
3190 if (![package broken])
3192 pkgCache::PkgIterator pkg([package iterator]);
3194 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3195 [entry addObject:[package name]];
3196 [issues addObject:entry];
3198 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3202 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3203 pkgCache::DepIterator start;
3204 pkgCache::DepIterator end;
3205 dep.GlobOr(start, end); // ++dep
3207 if (!cache_->IsImportantDep(end))
3209 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3212 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3213 [entry addObject:failure];
3214 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3216 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3217 if (Package *package = [self packageWithName:name])
3218 name = [package name];
3219 [failure addObject:name];
3221 pkgCache::PkgIterator target(start.TargetPkg());
3222 if (target->ProvidesList != 0)
3223 [failure addObject:@"?"];
3225 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3227 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3228 else if (!cache_[target].CandidateVerIter(cache_).end())
3229 [failure addObject:@"-"];
3230 else if (target->ProvidesList == 0)
3231 [failure addObject:@"!"];
3233 [failure addObject:@"%"];
3237 if (start.TargetVer() != 0)
3238 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3249 - (bool) popErrorWithTitle:(NSString *)title {
3251 std::string message;
3253 while (!_error->empty()) {
3255 bool warning(!_error->PopMessage(error));
3259 size_t size(error.size());
3260 if (size == 0 || error[size - 1] != '\n')
3262 error.resize(size - 1);
3264 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3266 if (!message.empty())
3271 if (fatal && !message.empty())
3272 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3277 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3278 return [self popErrorWithTitle:title] || !success;
3281 - (void) reloadData { CYPoolStart() {
3282 @synchronized (self) {
3285 [packages_ removeAllObjects];
3311 apr_pool_clear(pool_);
3312 NSRecycleZone(zone_);
3314 int chk(creat("/tmp/cydia.chk", 0644));
3318 NSString *title(UCLocalize("DATABASE"));
3321 if (!cache_.Open(progress_, true)) { pop:
3323 bool warning(!_error->PopMessage(error));
3324 lprintf("cache_.Open():[%s]\n", error.c_str());
3326 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3327 [delegate_ repairWithSelector:@selector(configure)];
3328 else if (error == "The package lists or status file could not be parsed or opened.")
3329 [delegate_ repairWithSelector:@selector(update)];
3330 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3331 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3332 // else if (error == "The list of sources could not be read.")
3334 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3343 unlink("/tmp/cydia.chk");
3345 now_ = [[NSDate date] retain];
3347 policy_ = new pkgDepCache::Policy();
3348 records_ = new pkgRecords(cache_);
3349 resolver_ = new pkgProblemResolver(cache_);
3350 fetcher_ = new pkgAcquire(&status_);
3353 list_ = new pkgSourceList();
3354 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3357 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3358 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3362 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3365 if (cache_->BrokenCount() != 0) {
3366 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3369 if (cache_->BrokenCount() != 0) {
3370 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3374 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3380 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3381 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3382 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3383 // XXX: this could be more intelligent
3384 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3385 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3387 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3394 /*std::vector<Package *> packages;
3395 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3396 [packages_ release];
3401 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3402 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3403 //packages.push_back(package);
3404 [packages_ addObject:package];
3408 /*if (packages.empty())
3409 packages_ = [[NSArray alloc] init];
3411 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3414 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3415 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3416 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3424 /*if (!packages.empty())
3425 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3426 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3428 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3430 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3432 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3439 - (void) configure {
3440 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3441 system([dpkg UTF8String]);
3445 // XXX: I don't remember this condition
3450 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3452 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3454 if ([self popErrorWithTitle:title])
3458 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3461 public pkgArchiveCleaner
3464 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3469 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3476 fetcher_->Shutdown();
3478 pkgRecords records(cache_);
3480 lock_ = new FileFd();
3481 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3483 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3485 if ([self popErrorWithTitle:title])
3489 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3492 manager_ = (_system->CreatePM(cache_));
3493 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3500 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3502 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3504 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3506 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3507 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3510 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3515 bool failed = false;
3516 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3517 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3519 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3522 std::string uri = (*item)->DescURI();
3523 std::string error = (*item)->ErrorText;
3525 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3528 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3529 withObject:[NSArray arrayWithObjects:
3530 [NSString stringWithUTF8String:error.c_str()],
3542 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3544 if (_error->PendingError()) {
3549 if (result == pkgPackageManager::Failed) {
3554 if (result != pkgPackageManager::Completed) {
3559 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3561 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3563 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3564 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3567 if (![before isEqualToArray:after])
3572 NSString *title(UCLocalize("UPGRADE"));
3573 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3579 [self updateWithStatus:status_];
3582 - (void) setVisible {
3583 for (Package *package in packages_)
3584 [package setVisible];
3587 - (void) updateWithStatus:(Status &)status {
3588 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3589 NSString *title(UCLocalize("REFRESHING_DATA"));
3592 if (!list.ReadMainList())
3593 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3596 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3597 if ([self popErrorWithTitle:title])
3600 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3601 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3602 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3604 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3608 - (void) setDelegate:(id)delegate {
3609 delegate_ = delegate;
3610 status_.setDelegate(delegate);
3611 progress_.setDelegate(delegate);
3614 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3615 SourceMap::const_iterator i(sources_.find(file->ID));
3616 return i == sources_.end() ? nil : i->second;
3622 /* Confirmation Controller {{{ */
3623 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3624 if (!iterator.end())
3625 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3626 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3628 pkgCache::PkgIterator package(dep.TargetPkg());
3631 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3639 /* Web Scripting {{{ */
3640 @interface CydiaObject : NSObject {
3645 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3648 @implementation CydiaObject
3651 [indirect_ release];
3655 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3656 if ((self = [super init]) != nil) {
3657 indirect_ = [indirect retain];
3661 - (void) setDelegate:(id)delegate {
3662 delegate_ = delegate;
3665 + (NSArray *) _attributeKeys {
3666 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3669 - (NSArray *) attributeKeys {
3670 return [[self class] _attributeKeys];
3673 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3674 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3677 - (NSString *) device {
3678 return [[UIDevice currentDevice] uniqueIdentifier];
3681 #if 0 // XXX: implement!
3682 - (NSString *) mac {
3683 if (![indirect_ promptForSensitive:@"Mac Address"])
3687 - (NSString *) serial {
3688 if (![indirect_ promptForSensitive:@"Serial #"])
3692 - (NSString *) firewire {
3693 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3697 - (NSString *) imei {
3698 if (![indirect_ promptForSensitive:@"IMEI"])
3703 + (NSString *) webScriptNameForSelector:(SEL)selector {
3704 if (selector == @selector(close))
3706 else if (selector == @selector(getInstalledPackages))
3707 return @"getInstalledPackages";
3708 else if (selector == @selector(getPackageById:))
3709 return @"getPackageById";
3710 else if (selector == @selector(installPackages:))
3711 return @"installPackages";
3712 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3713 return @"setButtonImage";
3714 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3715 return @"setButtonTitle";
3716 else if (selector == @selector(setPopupHook:))
3717 return @"setPopupHook";
3718 else if (selector == @selector(setSpecial:))
3719 return @"setSpecial";
3720 else if (selector == @selector(setToken:))
3722 else if (selector == @selector(setViewportWidth:))
3723 return @"setViewportWidth";
3724 else if (selector == @selector(supports:))
3726 else if (selector == @selector(stringWithFormat:arguments:))
3728 else if (selector == @selector(localizedStringForKey:value:table:))
3730 else if (selector == @selector(du:))
3732 else if (selector == @selector(statfs:))
3738 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3739 return [self webScriptNameForSelector:selector] == nil;
3742 - (BOOL) supports:(NSString *)feature {
3743 return [feature isEqualToString:@"window.open"];
3746 - (NSArray *) getInstalledPackages {
3747 NSArray *packages([[Database sharedInstance] packages]);
3748 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3749 for (Package *package in packages)
3750 if ([package installed] != nil)
3751 [installed addObject:package];
3755 - (Package *) getPackageById:(NSString *)id {
3756 Package *package([[Database sharedInstance] packageWithName:id]);
3761 - (NSArray *) statfs:(NSString *)path {
3764 if (path == nil || statfs([path UTF8String], &stat) == -1)
3767 return [NSArray arrayWithObjects:
3768 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3769 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3770 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3774 - (NSNumber *) du:(NSString *)path {
3775 NSNumber *value(nil);
3778 _assert(pipe(fds) != -1);
3780 pid_t pid(ExecFork());
3782 _assert(dup2(fds[1], 1) != -1);
3783 _assert(close(fds[0]) != -1);
3784 _assert(close(fds[1]) != -1);
3785 /* XXX: this should probably not use du */
3786 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3791 _assert(close(fds[1]) != -1);
3793 if (FILE *du = fdopen(fds[0], "r")) {
3795 while (fgets(line, sizeof(line), du) != NULL) {
3796 size_t length(strlen(line));
3797 while (length != 0 && line[length - 1] == '\n')
3798 line[--length] = '\0';
3799 if (char *tab = strchr(line, '\t')) {
3801 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3806 } else _assert(close(fds[0]));
3810 if (waitpid(pid, &status, 0) == -1)
3813 else _assert(false);
3822 - (void) installPackages:(NSArray *)packages {
3823 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3826 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3827 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3830 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3831 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3834 - (void) setSpecial:(id)function {
3835 [indirect_ setSpecial:function];
3838 - (void) setToken:(NSString *)token {
3841 Token_ = [token retain];
3843 [Metadata_ setObject:Token_ forKey:@"Token"];
3847 - (void) setPopupHook:(id)function {
3848 [indirect_ setPopupHook:function];
3851 - (void) setViewportWidth:(float)width {
3852 [indirect_ setViewportWidth:width];
3855 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3856 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3857 unsigned count([arguments count]);
3859 for (unsigned i(0); i != count; ++i)
3860 values[i] = [arguments objectAtIndex:i];
3861 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3864 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3865 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3867 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3869 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3875 /* Cydia Browser Controller {{{ */
3876 @interface CYBrowserController : BrowserController {
3877 CydiaObject *cydia_;
3882 @implementation CYBrowserController
3889 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3892 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3893 [super webView:view didClearWindowObject:window forFrame:frame];
3895 WebDataSource *source([frame dataSource]);
3896 NSURLResponse *response([source response]);
3897 NSURL *url([response URL]);
3898 NSString *scheme([url scheme]);
3900 NSHTTPURLResponse *http;
3901 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3902 http = (NSHTTPURLResponse *) response;
3906 NSDictionary *headers([http allHeaderFields]);
3907 NSString *host([url host]);
3908 [self setHeaders:headers forHost:host];
3911 [host isEqualToString:@"cydia.saurik.com"] ||
3912 [host hasSuffix:@".cydia.saurik.com"] ||
3913 [scheme isEqualToString:@"file"]
3915 [window setValue:cydia_ forKey:@"cydia"];
3918 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3919 if (System_ != NULL)
3920 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3921 if (Machine_ != NULL)
3922 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3924 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3926 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3929 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3930 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3931 [self _setMoreHeaders:copy];
3935 - (void) setDelegate:(id)delegate {
3936 [super setDelegate:delegate];
3937 [cydia_ setDelegate:delegate];
3941 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3942 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3944 WebView *webview([[webview_ _documentView] webView]);
3946 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3948 NSString *application = package == nil ? @"Cydia" : [NSString
3949 stringWithFormat:@"Cydia/%@",
3954 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3956 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3957 if (Product_ != nil)
3958 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3960 [webview setApplicationNameForUserAgent:application];
3967 /* Confirmation {{{ */
3968 @protocol ConfirmationControllerDelegate
3969 - (void) cancelAndClear:(bool)clear;
3970 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3974 @interface ConfirmationController : CYBrowserController {
3975 _transient Database *database_;
3976 UIAlertView *essential_;
3983 - (id) initWithDatabase:(Database *)database;
3987 @implementation ConfirmationController
3994 if (essential_ != nil)
3995 [essential_ release];
3999 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4000 NSString *context([alert context]);
4002 if ([context isEqualToString:@"remove"]) {
4003 if (button == [alert cancelButtonIndex]) {
4004 [self dismissModalViewControllerAnimated:YES];
4005 } else if (button == [alert firstOtherButtonIndex]) {
4008 [delegate_ confirmWithNavigationController:[self navigationController]];
4011 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4012 } else if ([context isEqualToString:@"unable"]) {
4013 [self dismissModalViewControllerAnimated:YES];
4014 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4016 [super alertView:alert clickedButtonAtIndex:button];
4020 - (void) _doContinue {
4021 [self dismissModalViewControllerAnimated:YES];
4022 [delegate_ cancelAndClear:NO];
4025 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4026 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4030 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4031 [super webView:view didClearWindowObject:window forFrame:frame];
4032 [window setValue:changes_ forKey:@"changes"];
4033 [window setValue:issues_ forKey:@"issues"];
4034 [window setValue:sizes_ forKey:@"sizes"];
4035 [window setValue:self forKey:@"queue"];
4038 - (id) initWithDatabase:(Database *)database {
4039 if ((self = [super init]) != nil) {
4040 database_ = database;
4042 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4044 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4045 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4046 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4047 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4048 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4052 pkgDepCache::Policy *policy([database_ policy]);
4054 pkgCacheFile &cache([database_ cache]);
4055 NSArray *packages = [database_ packages];
4056 for (Package *package in packages) {
4057 pkgCache::PkgIterator iterator = [package iterator];
4058 pkgDepCache::StateCache &state(cache[iterator]);
4060 NSString *name([package name]);
4062 if (state.NewInstall())
4063 [installing addObject:name];
4064 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4065 [reinstalling addObject:name];
4066 else if (state.Upgrade())
4067 [upgrading addObject:name];
4068 else if (state.Downgrade())
4069 [downgrading addObject:name];
4070 else if (state.Delete()) {
4071 if ([package essential])
4073 [removing addObject:name];
4076 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4077 substrate_ |= DepSubstrate(iterator.CurrentVer());
4082 else if (Advanced_) {
4083 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4085 essential_ = [[UIAlertView alloc]
4086 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4087 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4089 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4090 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4093 [essential_ setContext:@"remove"];
4095 essential_ = [[UIAlertView alloc]
4096 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4097 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4099 cancelButtonTitle:UCLocalize("OKAY")
4100 otherButtonTitles:nil
4103 [essential_ setContext:@"unable"];
4106 changes_ = [[NSArray alloc] initWithObjects:
4114 issues_ = [database_ issues];
4116 issues_ = [issues_ retain];
4118 sizes_ = [[NSArray alloc] initWithObjects:
4119 SizeString([database_ fetcher].FetchNeeded()),
4120 SizeString([database_ fetcher].PartialPresent()),
4123 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4125 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4126 initWithTitle:UCLocalize("CANCEL")
4127 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4128 style:UIBarButtonItemStylePlain
4130 action:@selector(cancelButtonClicked)
4132 [[self navigationItem] setLeftBarButtonItem:leftItem];
4137 - (void) applyRightButton {
4138 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4139 initWithTitle:UCLocalize("CONFIRM")
4140 style:UIBarButtonItemStylePlain
4142 action:@selector(confirmButtonClicked)
4144 #if !AlwaysReload && !IgnoreInstall
4145 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4146 else [super applyRightButton];
4148 [[self navigationItem] setRightBarButtonItem:nil];
4150 [rightItem release];
4153 - (void) cancelButtonClicked {
4154 [self dismissModalViewControllerAnimated:YES];
4155 [delegate_ cancelAndClear:YES];
4159 - (void) confirmButtonClicked {
4163 if (essential_ != nil)
4168 [delegate_ confirmWithNavigationController:[self navigationController]];
4176 /* Progress Data {{{ */
4177 @interface ProgressData : NSObject {
4183 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4190 @implementation ProgressData
4192 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4193 if ((self = [super init]) != nil) {
4194 selector_ = selector;
4214 /* Progress Controller {{{ */
4215 @interface ProgressController : CYViewController <
4216 ConfigurationDelegate,
4219 _transient Database *database_;
4220 UIProgressBar *progress_;
4221 UITextView *output_;
4222 UITextLabel *status_;
4223 UIPushButton *close_;
4225 SHA1SumValue springlist_;
4226 SHA1SumValue notifyconf_;
4230 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4232 - (void) _retachThread;
4233 - (void) _detachNewThreadData:(ProgressData *)data;
4234 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4240 @protocol ProgressControllerDelegate
4241 - (void) progressControllerIsComplete:(ProgressController *)sender;
4244 @implementation ProgressController
4247 [database_ setDelegate:nil];
4248 [progress_ release];
4257 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4258 if ((self = [super init]) != nil) {
4259 database_ = database;
4260 [database_ setDelegate:self];
4261 delegate_ = delegate;
4263 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4265 progress_ = [[UIProgressBar alloc] init];
4266 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4267 [progress_ setStyle:0];
4269 status_ = [[UITextLabel alloc] init];
4270 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4271 [status_ setColor:[UIColor whiteColor]];
4272 [status_ setBackgroundColor:[UIColor clearColor]];
4273 [status_ setCentersHorizontally:YES];
4274 //[status_ setFont:font];
4276 output_ = [[UITextView alloc] init];
4278 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4279 //[output_ setTextFont:@"Courier New"];
4280 [output_ setFont:[[output_ font] fontWithSize:12]];
4281 [output_ setTextColor:[UIColor whiteColor]];
4282 [output_ setBackgroundColor:[UIColor clearColor]];
4283 [output_ setMarginTop:0];
4284 [output_ setAllowsRubberBanding:YES];
4285 [output_ setEditable:NO];
4286 [[self view] addSubview:output_];
4288 close_ = [[UIPushButton alloc] init];
4289 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4290 [close_ setAutosizesToFit:NO];
4291 [close_ setDrawsShadow:YES];
4292 [close_ setStretchBackground:YES];
4293 [close_ setEnabled:YES];
4294 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4295 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4296 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4297 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4301 - (void) positionViews {
4302 CGRect bounds = [[self view] bounds];
4303 CGSize prgsize = [UIProgressBar defaultSize];
4306 (bounds.size.width - prgsize.width) / 2,
4307 bounds.size.height - prgsize.height - 20
4310 float closewidth = bounds.size.width - 20;
4311 if (closewidth > 300) closewidth = 300;
4313 [progress_ setFrame:prgrect];
4314 [status_ setFrame:CGRectMake(
4316 bounds.size.height - prgsize.height - 50,
4317 bounds.size.width - 20,
4320 [output_ setFrame:CGRectMake(
4323 bounds.size.width - 20,
4324 bounds.size.height - 62
4326 [close_ setFrame:CGRectMake(
4327 (bounds.size.width - closewidth) / 2,
4328 bounds.size.height - prgsize.height - 50,
4334 - (void) viewWillAppear:(BOOL)animated {
4335 [super viewDidAppear:animated];
4336 [[self navigationItem] setHidesBackButton:YES];
4337 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4339 [self positionViews];
4342 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4343 [self positionViews];
4346 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4347 NSString *context([alert context]);
4349 if ([context isEqualToString:@"conffile"]) {
4350 FILE *input = [database_ input];
4351 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4352 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4357 - (void) closeButtonPushed {
4360 UpdateExternalStatus(0);
4364 [self dismissModalViewControllerAnimated:YES];
4368 [delegate_ terminateWithSuccess];
4369 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4370 [delegate_ suspendWithAnimation:YES];
4372 [delegate_ suspend];*/
4376 system("launchctl stop com.apple.SpringBoard");
4380 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4389 - (void) _retachThread {
4390 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4392 [[self view] addSubview:close_];
4393 [progress_ removeFromSuperview];
4394 [status_ removeFromSuperview];
4396 [database_ popErrorWithTitle:title_];
4397 [delegate_ progressControllerIsComplete:self];
4401 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4404 MMap mmap(file, MMap::ReadOnly);
4406 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4407 if (!(notifyconf_ == sha1.Result()))
4414 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4417 MMap mmap(file, MMap::ReadOnly);
4419 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4420 if (!(springlist_ == sha1.Result()))
4426 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4427 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4428 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4429 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4430 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4433 system("su -c /usr/bin/uicache mobile");
4435 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4437 [delegate_ setStatusBarShowsProgress:NO];
4440 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4441 [[data target] performSelector:[data selector] withObject:[data object]];
4444 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4447 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4448 UpdateExternalStatus(1);
4455 title_ = [title retain];
4457 [[self navigationItem] setTitle:title_];
4459 [status_ setText:nil];
4460 [output_ setText:@""];
4461 [progress_ setProgress:0];
4463 [close_ removeFromSuperview];
4464 [[self view] addSubview:progress_];
4465 [[self view] addSubview:status_];
4467 [delegate_ setStatusBarShowsProgress:YES];
4472 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4475 MMap mmap(file, MMap::ReadOnly);
4477 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4478 notifyconf_ = sha1.Result();
4484 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4487 MMap mmap(file, MMap::ReadOnly);
4489 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4490 springlist_ = sha1.Result();
4495 detachNewThreadSelector:@selector(_detachNewThreadData:)
4497 withObject:[[ProgressData alloc]
4498 initWithSelector:selector
4505 - (void) repairWithSelector:(SEL)selector {
4507 detachNewThreadSelector:selector
4510 title:UCLocalize("REPAIRING")
4514 - (void) setConfigurationData:(NSString *)data {
4516 performSelectorOnMainThread:@selector(_setConfigurationData:)
4522 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4523 CYActionSheet *sheet([[[CYActionSheet alloc]
4525 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4526 defaultButtonIndex:0
4529 [sheet setMessage:error];
4530 [sheet yieldToPopupAlertAnimated:YES];
4534 - (void) setProgressTitle:(NSString *)title {
4536 performSelectorOnMainThread:@selector(_setProgressTitle:)
4542 - (void) setProgressPercent:(float)percent {
4544 performSelectorOnMainThread:@selector(_setProgressPercent:)
4545 withObject:[NSNumber numberWithFloat:percent]
4550 - (void) startProgress {
4553 - (void) addProgressOutput:(NSString *)output {
4555 performSelectorOnMainThread:@selector(_addProgressOutput:)
4561 - (bool) isCancelling:(size_t)received {
4565 - (void) _setConfigurationData:(NSString *)data {
4566 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4568 if (!conffile_r(data)) {
4569 lprintf("E:invalid conffile\n");
4573 NSString *ofile = conffile_r[1];
4574 //NSString *nfile = conffile_r[2];
4576 UIAlertView *alert = [[[UIAlertView alloc]
4577 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4578 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4580 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4581 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4582 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4586 [alert setContext:@"conffile"];
4590 - (void) _setProgressTitle:(NSString *)title {
4591 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4592 for (size_t i(0), e([words count]); i != e; ++i) {
4593 NSString *word([words objectAtIndex:i]);
4594 if (Package *package = [database_ packageWithName:word])
4595 [words replaceObjectAtIndex:i withObject:[package name]];
4598 [status_ setText:[words componentsJoinedByString:@" "]];
4601 - (void) _setProgressPercent:(NSNumber *)percent {
4602 [progress_ setProgress:[percent floatValue]];
4605 - (void) _addProgressOutput:(NSString *)output {
4606 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4607 CGSize size = [output_ contentSize];
4608 CGRect rect = {{0, size.height}, {size.width, 0}};
4609 [output_ scrollRectToVisible:rect animated:YES];
4612 - (BOOL) isRunning {
4619 /* Cell Content View {{{ */
4620 @protocol ContentDelegate
4621 - (void) drawContentRect:(CGRect)rect;
4624 @interface ContentView : UIView {
4625 _transient id<ContentDelegate> delegate_;
4630 @implementation ContentView
4631 - (id) initWithFrame:(CGRect)frame {
4632 if ((self = [super initWithFrame:frame]) != nil) {
4633 /* Fix landscape stretching. */
4634 [self setNeedsDisplayOnBoundsChange:YES];
4638 - (void) setDelegate:(id<ContentDelegate>)delegate {
4639 delegate_ = delegate;
4642 - (void) drawRect:(CGRect)rect {
4643 [super drawRect:rect];
4644 [delegate_ drawContentRect:rect];
4648 /* Package Cell {{{ */
4649 @interface PackageCell : UITableViewCell <
4654 NSString *description_;
4660 ContentView *content_;
4666 - (PackageCell *) init;
4667 - (void) setPackage:(Package *)package;
4669 + (int) heightForPackage:(Package *)package;
4670 - (void) drawContentRect:(CGRect)rect;
4674 @implementation PackageCell
4676 - (void) clearPackage {
4687 if (description_ != nil) {
4688 [description_ release];
4692 if (source_ != nil) {
4697 if (badge_ != nil) {
4702 if (placard_ != nil) {
4712 [self clearPackage];
4719 return faded_ ? [self selectionPercent] : fade_;
4722 - (PackageCell *) init {
4723 CGRect frame(CGRectMake(0, 0, 320, 74));
4724 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4725 UIView *content([self contentView]);
4726 CGRect bounds([content bounds]);
4728 content_ = [[ContentView alloc] initWithFrame:bounds];
4729 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4730 [content addSubview:content_];
4732 [content_ setDelegate:self];
4733 [content_ setOpaque:YES];
4734 if ([self respondsToSelector:@selector(selectionPercent)])
4739 - (void) _setBackgroundColor {
4741 if (NSString *mode = [package_ mode]) {
4742 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4743 color = remove ? RemovingColor_ : InstallingColor_;
4745 color = [UIColor whiteColor];
4747 [content_ setBackgroundColor:color];
4748 [self setNeedsDisplay];
4751 - (void) setPackage:(Package *)package {
4752 [self clearPackage];
4755 Source *source = [package source];
4757 icon_ = [[package icon] retain];
4758 name_ = [[package name] retain];
4761 description_ = [package longDescription];
4762 if (description_ == nil)
4763 description_ = [package shortDescription];
4764 if (description_ != nil)
4765 description_ = [description_ retain];
4767 commercial_ = [package isCommercial];
4769 package_ = [package retain];
4771 NSString *label = nil;
4772 bool trusted = false;
4774 if (source != nil) {
4775 label = [source label];
4776 trusted = [source trusted];
4777 } else if ([[package id] isEqualToString:@"firmware"])
4778 label = UCLocalize("APPLE");
4780 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4782 NSString *from(label);
4784 NSString *section = [package simpleSection];
4785 if (section != nil && ![section isEqualToString:label]) {
4786 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4787 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4790 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4791 source_ = [from retain];
4793 if (NSString *purpose = [package primaryPurpose])
4794 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4795 badge_ = [badge_ retain];
4797 if ([package installed] != nil)
4798 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4799 placard_ = [placard_ retain];
4801 [self _setBackgroundColor];
4802 [content_ setNeedsDisplay];
4805 - (void) drawContentRect:(CGRect)rect {
4806 bool selected([self isSelected]);
4807 float width([self bounds].size.width);
4810 CGContextRef context(UIGraphicsGetCurrentContext());
4811 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4812 CGContextFillRect(context, rect);
4817 rect.size = [icon_ size];
4819 rect.size.width /= 2;
4820 rect.size.height /= 2;
4822 rect.origin.x = 25 - rect.size.width / 2;
4823 rect.origin.y = 25 - rect.size.height / 2;
4825 [icon_ drawInRect:rect];
4828 if (badge_ != nil) {
4829 CGSize size = [badge_ size];
4831 [badge_ drawAtPoint:CGPointMake(
4832 36 - size.width / 2,
4833 36 - size.height / 2
4841 UISetColor(commercial_ ? Purple_ : Black_);
4842 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4843 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4846 UISetColor(commercial_ ? Purplish_ : Gray_);
4847 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4849 if (placard_ != nil)
4850 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4853 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4854 //[self _setBackgroundColor];
4855 [super setSelected:selected animated:fade];
4856 [content_ setNeedsDisplay];
4859 + (int) heightForPackage:(Package *)package {
4865 /* Section Cell {{{ */
4866 @interface SectionCell : UITableViewCell <
4874 ContentView *content_;
4879 - (void) setSection:(Section *)section editing:(BOOL)editing;
4883 @implementation SectionCell
4885 - (void) clearSection {
4886 if (basic_ != nil) {
4891 if (section_ != nil) {
4901 if (count_ != nil) {
4908 [self clearSection];
4916 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4917 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4918 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4919 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4920 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4922 UIView *content([self contentView]);
4923 CGRect bounds([content bounds]);
4925 content_ = [[ContentView alloc] initWithFrame:bounds];
4926 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4927 [content addSubview:content_];
4928 [content_ setBackgroundColor:[UIColor whiteColor]];
4930 [content_ setDelegate:self];
4934 - (void) onSwitch:(id)sender {
4935 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4936 if (metadata == nil) {
4937 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4938 [Sections_ setObject:metadata forKey:basic_];
4942 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4945 - (void) setSection:(Section *)section editing:(BOOL)editing {
4946 if (editing != editing_) {
4948 [switch_ removeFromSuperview];
4950 [self addSubview:switch_];
4954 [self clearSection];
4956 if (section == nil) {
4957 name_ = [UCLocalize("ALL_PACKAGES") retain];
4960 basic_ = [section name];
4962 basic_ = [basic_ retain];
4964 section_ = [section localized];
4965 if (section_ != nil)
4966 section_ = [section_ retain];
4968 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4969 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4972 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4975 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4976 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4978 [content_ setNeedsDisplay];
4981 - (void) setFrame:(CGRect)frame {
4982 [super setFrame:frame];
4984 CGRect rect([switch_ frame]);
4985 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4988 - (void) drawContentRect:(CGRect)rect {
4989 BOOL selected = [self isSelected];
4991 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4999 float width(rect.size.width);
5003 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5005 CGSize size = [count_ sizeWithFont:Font14_];
5009 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5015 /* File Table {{{ */
5016 @interface FileTable : CYViewController <
5017 UITableViewDataSource,
5020 _transient Database *database_;
5023 NSMutableArray *files_;
5027 - (id) initWithDatabase:(Database *)database;
5028 - (void) setPackage:(Package *)package;
5032 @implementation FileTable
5035 if (package_ != nil)
5044 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5045 return files_ == nil ? 0 : [files_ count];
5048 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5052 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5053 static NSString *reuseIdentifier = @"Cell";
5055 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5057 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5058 [cell setFont:[UIFont systemFontOfSize:16]];
5060 [cell setText:[files_ objectAtIndex:indexPath.row]];
5061 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5066 - (id) initWithDatabase:(Database *)database {
5067 if ((self = [super init]) != nil) {
5068 database_ = database;
5070 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5072 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5074 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5075 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5076 [list_ setRowHeight:24.0f];
5077 [[self view] addSubview:list_];
5079 [list_ setDataSource:self];
5080 [list_ setDelegate:self];
5084 - (void) setPackage:(Package *)package {
5085 if (package_ != nil) {
5086 [package_ autorelease];
5095 [files_ removeAllObjects];
5097 if (package != nil) {
5098 package_ = [package retain];
5099 name_ = [[package id] retain];
5101 if (NSArray *files = [package files])
5102 [files_ addObjectsFromArray:files];
5104 if ([files_ count] != 0) {
5105 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5106 [files_ removeObjectAtIndex:0];
5107 [files_ sortUsingSelector:@selector(compareByPath:)];
5109 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5110 [stack addObject:@"/"];
5112 for (int i(0), e([files_ count]); i != e; ++i) {
5113 NSString *file = [files_ objectAtIndex:i];
5114 while (![file hasPrefix:[stack lastObject]])
5115 [stack removeLastObject];
5116 NSString *directory = [stack lastObject];
5117 [stack addObject:[file stringByAppendingString:@"/"]];
5118 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5119 ([stack count] - 2) * 3, "",
5120 [file substringFromIndex:[directory length]]
5129 - (void) reloadData {
5130 [self setPackage:[database_ packageWithName:name_]];
5135 /* Package Controller {{{ */
5136 @interface PackageController : CYBrowserController <
5137 UIActionSheetDelegate
5139 _transient Database *database_;
5143 NSMutableArray *buttons_;
5144 UIBarButtonItem *button_;
5147 - (id) initWithDatabase:(Database *)database;
5148 - (void) setPackage:(Package *)package;
5152 @implementation PackageController
5155 if (package_ != nil)
5169 if ([self retainCount] == 1)
5170 [delegate_ setPackageController:self];
5174 /* XXX: this is not safe at all... localization of /fail/ */
5175 - (void) _clickButtonWithName:(NSString *)name {
5176 if ([name isEqualToString:UCLocalize("CLEAR")])
5177 [delegate_ clearPackage:package_];
5178 else if ([name isEqualToString:UCLocalize("INSTALL")])
5179 [delegate_ installPackage:package_];
5180 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5181 [delegate_ installPackage:package_];
5182 else if ([name isEqualToString:UCLocalize("REMOVE")])
5183 [delegate_ removePackage:package_];
5184 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5185 [delegate_ installPackage:package_];
5186 else _assert(false);
5189 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5190 NSString *context([sheet context]);
5192 if ([context isEqualToString:@"modify"]) {
5193 if (button != [sheet cancelButtonIndex]) {
5194 NSString *buttonName = [buttons_ objectAtIndex:button];
5195 [self _clickButtonWithName:buttonName];
5198 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5202 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5203 [super webView:view didClearWindowObject:window forFrame:frame];
5204 [window setValue:package_ forKey:@"package"];
5207 - (bool) _allowJavaScriptPanel {
5212 - (void) _customButtonClicked {
5213 int count([buttons_ count]);
5218 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5220 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5221 [buttons addObjectsFromArray:buttons_];
5223 UIActionSheet *sheet = [[[UIActionSheet alloc]
5226 cancelButtonTitle:nil
5227 destructiveButtonTitle:nil
5228 otherButtonTitles:nil
5231 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5233 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5234 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5236 [sheet setContext:@"modify"];
5238 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5242 // We don't want to allow non-commercial packages to do custom things to the install button,
5243 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5244 - (void) customButtonClicked {
5246 [super customButtonClicked];
5248 [self _customButtonClicked];
5251 - (void) reloadButtonClicked {
5252 // Don't reload a package view by clicking the button.
5255 - (void) applyLoadingTitle {
5256 // Don't show "Loading" as the title. Ever.
5259 - (UIBarButtonItem *) rightButton {
5264 - (id) initWithDatabase:(Database *)database {
5265 if ((self = [super init]) != nil) {
5266 database_ = database;
5267 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5268 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5272 - (void) setPackage:(Package *)package {
5273 if (package_ != nil) {
5274 [package_ autorelease];
5283 [buttons_ removeAllObjects];
5285 if (package != nil) {
5288 package_ = [package retain];
5289 name_ = [[package id] retain];
5290 commercial_ = [package isCommercial];
5292 if ([package_ mode] != nil)
5293 [buttons_ addObject:UCLocalize("CLEAR")];
5294 if ([package_ source] == nil);
5295 else if ([package_ upgradableAndEssential:NO])
5296 [buttons_ addObject:UCLocalize("UPGRADE")];
5297 else if ([package_ uninstalled])
5298 [buttons_ addObject:UCLocalize("INSTALL")];
5300 [buttons_ addObject:UCLocalize("REINSTALL")];
5301 if (![package_ uninstalled])
5302 [buttons_ addObject:UCLocalize("REMOVE")];
5309 switch ([buttons_ count]) {
5310 case 0: title = nil; break;
5311 case 1: title = [buttons_ objectAtIndex:0]; break;
5312 default: title = UCLocalize("MODIFY"); break;
5315 button_ = [[UIBarButtonItem alloc]
5317 style:UIBarButtonItemStylePlain
5319 action:@selector(customButtonClicked)
5323 - (bool) isLoading {
5324 return commercial_ ? [super isLoading] : false;
5327 - (void) reloadData {
5328 [self setPackage:[database_ packageWithName:name_]];
5333 /* Package Table {{{ */
5334 @interface PackageTable : UIView <
5335 UITableViewDataSource,
5338 _transient Database *database_;
5339 NSMutableArray *packages_;
5340 NSMutableArray *sections_;
5342 NSMutableArray *index_;
5343 NSMutableDictionary *indices_;
5349 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5351 - (void) setDelegate:(id)delegate;
5353 - (void) reloadData;
5354 - (void) resetCursor;
5356 - (UITableView *) list;
5358 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5360 - (void) deselectWithAnimation:(BOOL)animated;
5364 @implementation PackageTable
5367 [packages_ release];
5368 [sections_ release];
5376 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5377 NSInteger count([sections_ count]);
5378 return count == 0 ? 1 : count;
5381 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5382 if ([sections_ count] == 0)
5384 return [[sections_ objectAtIndex:section] name];
5387 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5388 if ([sections_ count] == 0)
5390 return [[sections_ objectAtIndex:section] count];
5393 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5394 Section *section([sections_ objectAtIndex:[path section]]);
5395 NSInteger row([path row]);
5396 Package *package([packages_ objectAtIndex:([section row] + row)]);
5400 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5401 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5403 cell = [[[PackageCell alloc] init] autorelease];
5404 [cell setPackage:[self packageAtIndexPath:path]];
5408 - (void) deselectWithAnimation:(BOOL)animated {
5409 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5412 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5413 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5416 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5417 Package *package([self packageAtIndexPath:path]);
5418 package = [database_ packageWithName:[package id]];
5419 [target_ performSelector:action_ withObject:package];
5423 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5424 return [packages_ count] > 20 ? index_ : nil;
5427 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5431 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5432 if ((self = [super initWithFrame:frame]) != nil) {
5433 database_ = database;
5438 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5439 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5441 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5442 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5444 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5445 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5446 [list_ setRowHeight:73.0f];
5447 [self addSubview:list_];
5449 [list_ setDataSource:self];
5450 [list_ setDelegate:self];
5454 - (void) setDelegate:(id)delegate {
5455 delegate_ = delegate;
5458 - (bool) hasPackage:(Package *)package {
5462 - (void) reloadData {
5463 NSArray *packages = [database_ packages];
5465 [packages_ removeAllObjects];
5466 [sections_ removeAllObjects];
5468 _profile(PackageTable$reloadData$Filter)
5469 for (Package *package in packages)
5470 if ([self hasPackage:package])
5471 [packages_ addObject:package];
5474 [index_ removeAllObjects];
5475 [indices_ removeAllObjects];
5477 Section *section = nil;
5479 _profile(PackageTable$reloadData$Section)
5480 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5484 _profile(PackageTable$reloadData$Section$Package)
5485 package = [packages_ objectAtIndex:offset];
5486 index = [package index];
5489 if (section == nil || [section index] != index) {
5490 _profile(PackageTable$reloadData$Section$Allocate)
5491 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5494 [index_ addObject:[section name]];
5495 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5497 _profile(PackageTable$reloadData$Section$Add)
5498 [sections_ addObject:section];
5502 [section addToCount];
5506 _profile(PackageTable$reloadData$List)
5511 - (void) resetCursor {
5512 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5515 - (UITableView *) list {
5519 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5520 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5525 /* Filtered Package Table {{{ */
5526 @interface FilteredPackageTable : PackageTable {
5532 - (void) setObject:(id)object;
5533 - (void) setObject:(id)object forFilter:(SEL)filter;
5535 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5539 @implementation FilteredPackageTable
5547 - (void) setFilter:(SEL)filter {
5550 /* XXX: this is an unsafe optimization of doomy hell */
5551 Method method(class_getInstanceMethod([Package class], filter));
5552 _assert(method != NULL);
5553 imp_ = method_getImplementation(method);
5554 _assert(imp_ != NULL);
5557 - (void) setObject:(id)object {
5563 object_ = [object retain];
5566 - (void) setObject:(id)object forFilter:(SEL)filter {
5567 [self setFilter:filter];
5568 [self setObject:object];
5571 - (bool) hasPackage:(Package *)package {
5572 _profile(FilteredPackageTable$hasPackage)
5573 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5577 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5578 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5579 [self setFilter:filter];
5580 object_ = [object retain];
5588 /* Filtered Package Controller {{{ */
5589 @interface FilteredPackageController : CYViewController {
5590 _transient Database *database_;
5591 FilteredPackageTable *packages_;
5595 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5599 @implementation FilteredPackageController
5602 [packages_ release];
5608 - (void) viewDidAppear:(BOOL)animated {
5609 [super viewDidAppear:animated];
5610 [packages_ deselectWithAnimation:animated];
5613 - (void) didSelectPackage:(Package *)package {
5614 PackageController *view([delegate_ packageController]);
5615 [view setPackage:package];
5616 [view setDelegate:delegate_];
5617 [[self navigationController] pushViewController:view animated:YES];
5620 - (NSString *) title { return title_; }
5622 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5623 if ((self = [super init]) != nil) {
5624 database_ = database;
5625 title_ = [title copy];
5626 [[self navigationItem] setTitle:title_];
5628 packages_ = [[FilteredPackageTable alloc]
5629 initWithFrame:[[self view] bounds]
5632 action:@selector(didSelectPackage:)
5637 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5638 [[self view] addSubview:packages_];
5642 - (void) reloadData {
5643 [packages_ reloadData];
5646 - (void) setDelegate:(id)delegate {
5647 [super setDelegate:delegate];
5648 [packages_ setDelegate:delegate];
5655 /* Add Source Controller {{{ */
5656 @interface AddSourceController : CYViewController {
5657 _transient Database *database_;
5660 - (id) initWithDatabase:(Database *)database;
5664 @implementation AddSourceController
5666 - (id) initWithDatabase:(Database *)database {
5667 if ((self = [super init]) != nil) {
5668 database_ = database;
5674 /* Source Cell {{{ */
5675 @interface SourceCell : UITableViewCell <
5680 NSString *description_;
5682 ContentView *content_;
5685 - (void) setSource:(Source *)source;
5689 @implementation SourceCell
5691 - (void) clearSource {
5694 [description_ release];
5703 - (void) setSource:(Source *)source {
5707 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5709 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5710 icon_ = [icon_ retain];
5712 origin_ = [[source name] retain];
5713 label_ = [[source uri] retain];
5714 description_ = [[source description] retain];
5716 [content_ setNeedsDisplay];
5725 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5726 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5727 UIView *content([self contentView]);
5728 CGRect bounds([content bounds]);
5730 content_ = [[ContentView alloc] initWithFrame:bounds];
5731 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5732 [content_ setBackgroundColor:[UIColor whiteColor]];
5733 [content addSubview:content_];
5735 [content_ setDelegate:self];
5736 [content_ setOpaque:YES];
5740 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5741 [super setSelected:selected animated:animated];
5742 [content_ setNeedsDisplay];
5745 - (void) drawContentRect:(CGRect)rect {
5746 bool selected([self isSelected]);
5747 float width(rect.size.width);
5750 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5757 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5761 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5765 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5770 /* Source Table {{{ */
5771 @interface SourceTable : CYViewController <
5772 UITableViewDataSource,
5775 _transient Database *database_;
5777 NSMutableArray *sources_;
5781 UIProgressHUD *hud_;
5784 //NSURLConnection *installer_;
5785 NSURLConnection *trivial_;
5786 NSURLConnection *trivial_bz2_;
5787 NSURLConnection *trivial_gz_;
5788 //NSURLConnection *automatic_;
5793 - (id) initWithDatabase:(Database *)database;
5795 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5799 @implementation SourceTable
5801 - (void) _deallocConnection:(NSURLConnection *)connection {
5802 if (connection != nil) {
5803 [connection cancel];
5804 //[connection setDelegate:nil];
5805 [connection release];
5817 //[self _deallocConnection:installer_];
5818 [self _deallocConnection:trivial_];
5819 [self _deallocConnection:trivial_gz_];
5820 [self _deallocConnection:trivial_bz2_];
5821 //[self _deallocConnection:automatic_];
5828 - (void) viewDidAppear:(BOOL)animated {
5829 [super viewDidAppear:animated];
5830 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5833 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5834 return offset_ == 0 ? 1 : 2;
5837 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5838 switch (section + (offset_ == 0 ? 1 : 0)) {
5839 case 0: return UCLocalize("ENTERED_BY_USER");
5840 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5846 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5847 int count = [sources_ count];
5849 case 0: return (offset_ == 0 ? count : offset_);
5850 case 1: return count - offset_;
5856 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5858 switch (indexPath.section) {
5859 case 0: idx = indexPath.row; break;
5860 case 1: idx = indexPath.row + offset_; break;
5864 return [sources_ objectAtIndex:idx];
5867 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5868 Source *source = [self sourceAtIndexPath:indexPath];
5869 return [source description] == nil ? 56 : 73;
5872 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5873 static NSString *cellIdentifier = @"SourceCell";
5875 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5876 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5877 [cell setSource:[self sourceAtIndexPath:indexPath]];
5882 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5883 return UITableViewCellAccessoryDisclosureIndicator;
5886 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5887 Source *source = [self sourceAtIndexPath:indexPath];
5889 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5890 initWithDatabase:database_
5891 title:[source label]
5892 filter:@selector(isVisibleInSource:)
5896 [packages setDelegate:delegate_];
5898 [[self navigationController] pushViewController:packages animated:YES];
5901 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5902 Source *source = [self sourceAtIndexPath:indexPath];
5903 return [source record] != nil;
5906 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5907 Source *source = [self sourceAtIndexPath:indexPath];
5908 [Sources_ removeObjectForKey:[source key]];
5909 [delegate_ syncData];
5913 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5916 @"./", @"Distribution",
5917 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5919 [delegate_ syncData];
5922 - (NSString *) getWarning {
5923 NSString *href(href_);
5924 NSRange colon([href rangeOfString:@"://"]);
5925 if (colon.location != NSNotFound)
5926 href = [href substringFromIndex:(colon.location + 3)];
5927 href = [href stringByAddingPercentEscapes];
5928 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5929 href = [href stringByCachingURLWithCurrentCDN];
5931 NSURL *url([NSURL URLWithString:href]);
5933 NSStringEncoding encoding;
5934 NSError *error(nil);
5936 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5937 return [warning length] == 0 ? nil : warning;
5941 - (void) _endConnection:(NSURLConnection *)connection {
5942 NSURLConnection **field = NULL;
5943 if (connection == trivial_)
5945 else if (connection == trivial_bz2_)
5946 field = &trivial_bz2_;
5947 else if (connection == trivial_gz_)
5948 field = &trivial_gz_;
5949 _assert(field != NULL);
5950 [connection release];
5955 trivial_bz2_ == nil &&
5961 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5964 UIAlertView *alert = [[[UIAlertView alloc]
5965 initWithTitle:UCLocalize("SOURCE_WARNING")
5968 cancelButtonTitle:UCLocalize("CANCEL")
5969 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5972 [alert setContext:@"warning"];
5973 [alert setNumberOfRows:1];
5977 } else if (error_ != nil) {
5978 UIAlertView *alert = [[[UIAlertView alloc]
5979 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5980 message:[error_ localizedDescription]
5982 cancelButtonTitle:UCLocalize("OK")
5983 otherButtonTitles:nil
5986 [alert setContext:@"urlerror"];
5989 UIAlertView *alert = [[[UIAlertView alloc]
5990 initWithTitle:UCLocalize("NOT_REPOSITORY")
5991 message:UCLocalize("NOT_REPOSITORY_EX")
5993 cancelButtonTitle:UCLocalize("OK")
5994 otherButtonTitles:nil
5997 [alert setContext:@"trivial"];
6001 [delegate_ setStatusBarShowsProgress:NO];
6002 [delegate_ removeProgressHUD:hud_];
6012 if (error_ != nil) {
6019 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6020 switch ([response statusCode]) {
6026 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6027 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6029 error_ = [error retain];
6030 [self _endConnection:connection];
6033 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6034 [self _endConnection:connection];
6037 - (NSString *) title { return UCLocalize("SOURCES"); }
6039 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6040 NSMutableURLRequest *request = [NSMutableURLRequest
6041 requestWithURL:[NSURL URLWithString:href]
6042 cachePolicy:NSURLRequestUseProtocolCachePolicy
6043 timeoutInterval:120.0
6046 [request setHTTPMethod:method];
6048 if (Machine_ != NULL)
6049 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6050 if (UniqueID_ != nil)
6051 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6053 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6055 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6058 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6059 NSString *context([alert context]);
6061 if ([context isEqualToString:@"source"]) {
6064 NSString *href = [[alert textField] text];
6066 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6068 if (![href hasSuffix:@"/"])
6069 href_ = [href stringByAppendingString:@"/"];
6072 href_ = [href_ retain];
6074 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6075 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6076 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6077 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6081 hud_ = [[delegate_ addProgressHUD] retain];
6082 [hud_ setText:UCLocalize("VERIFYING_URL")];
6091 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6092 } else if ([context isEqualToString:@"trivial"])
6093 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6094 else if ([context isEqualToString:@"urlerror"])
6095 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6096 else if ([context isEqualToString:@"warning"]) {
6111 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6115 - (id) initWithDatabase:(Database *)database {
6116 if ((self = [super init]) != nil) {
6117 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6118 [self updateButtonsForEditingStatus:NO animated:NO];
6120 database_ = database;
6121 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6123 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6124 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6125 [[self view] addSubview:list_];
6127 [list_ setDataSource:self];
6128 [list_ setDelegate:self];
6134 - (void) reloadData {
6136 if (!list.ReadMainList())
6139 [sources_ removeAllObjects];
6140 [sources_ addObjectsFromArray:[database_ sources]];
6142 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6145 int count([sources_ count]);
6147 for (int i = 0; i != count; i++) {
6148 if ([[sources_ objectAtIndex:i] record] == nil) break;
6152 [list_ setEditing:NO];
6153 [self updateButtonsForEditingStatus:NO animated:NO];
6157 - (void) addButtonClicked {
6158 /*[book_ pushPage:[[[AddSourceController alloc]
6163 UIAlertView *alert = [[[UIAlertView alloc]
6164 initWithTitle:UCLocalize("ENTER_APT_URL")
6167 cancelButtonTitle:UCLocalize("CANCEL")
6168 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6171 [alert setContext:@"source"];
6172 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6174 [alert setNumberOfRows:1];
6175 [alert addTextFieldWithValue:@"http://" label:@""];
6177 UITextInputTraits *traits = [[alert textField] textInputTraits];
6178 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6179 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6180 [traits setKeyboardType:UIKeyboardTypeURL];
6181 // XXX: UIReturnKeyDone
6182 [traits setReturnKeyType:UIReturnKeyNext];
6187 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6188 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6189 initWithTitle:UCLocalize("ADD")
6190 style:UIBarButtonItemStylePlain
6192 action:@selector(addButtonClicked)
6194 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6197 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6198 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6199 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6201 action:@selector(editButtonClicked)
6203 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6204 [rightItem release];
6206 if (IsWildcat_ && !editing) {
6207 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6208 initWithTitle:UCLocalize("SETTINGS")
6209 style:UIBarButtonItemStylePlain
6211 action:@selector(settingsButtonClicked)
6213 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6214 [settingsItem release];
6218 - (void) settingsButtonClicked {
6219 [delegate_ showSettings];
6222 - (void) editButtonClicked {
6223 [list_ setEditing:![list_ isEditing] animated:YES];
6225 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6231 /* Installed Controller {{{ */
6232 @interface InstalledController : FilteredPackageController {
6236 - (id) initWithDatabase:(Database *)database;
6238 - (void) updateRoleButton;
6239 - (void) queueStatusDidChange;
6243 @implementation InstalledController
6249 - (NSString *) title { return UCLocalize("INSTALLED"); }
6251 - (id) initWithDatabase:(Database *)database {
6252 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6253 [self updateRoleButton];
6254 [self queueStatusDidChange];
6259 - (void) queueButtonClicked {
6264 - (void) queueStatusDidChange {
6267 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6268 initWithTitle:UCLocalize("QUEUE")
6269 style:UIBarButtonItemStyleDone
6271 action:@selector(queueButtonClicked)
6273 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6274 else [[self navigationItem] setLeftBarButtonItem:nil];
6275 [queueItem release];
6280 - (void) reloadData {
6281 [packages_ reloadData];
6284 - (void) updateRoleButton {
6285 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6286 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6287 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6289 action:@selector(roleButtonClicked)
6291 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6292 [rightItem release];
6295 - (void) roleButtonClicked {
6296 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6297 [packages_ reloadData];
6300 [self updateRoleButton];
6303 - (void) setDelegate:(id)delegate {
6304 [super setDelegate:delegate];
6305 [packages_ setDelegate:delegate];
6311 /* Home Controller {{{ */
6312 @interface HomeController : CYBrowserController {
6317 @implementation HomeController
6319 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6320 [super _setMoreHeaders:request];
6323 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6324 if (UniqueID_ != nil)
6325 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6327 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6330 - (void) aboutButtonClicked {
6331 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6333 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6334 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6335 [alert setCancelButtonIndex:0];
6338 @"Copyright (C) 2008-2010\n"
6339 "Jay Freeman (saurik)\n"
6340 "saurik@saurik.com\n"
6341 "http://www.saurik.com/"
6347 - (void) viewWillAppear:(BOOL)animated {
6348 [super viewWillAppear:animated];
6349 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6352 - (void) viewWillDisappear:(BOOL)animated {
6353 [super viewWillDisappear:animated];
6354 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6358 if ((self = [super init]) != nil) {
6359 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6360 initWithTitle:UCLocalize("ABOUT")
6361 style:UIBarButtonItemStylePlain
6363 action:@selector(aboutButtonClicked)
6370 /* Manage Controller {{{ */
6371 @interface ManageController : CYBrowserController {
6374 - (void) queueStatusDidChange;
6377 @implementation ManageController
6380 if ((self = [super init]) != nil) {
6381 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6383 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6384 initWithTitle:UCLocalize("SETTINGS")
6385 style:UIBarButtonItemStylePlain
6387 action:@selector(settingsButtonClicked)
6389 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6390 [settingsItem release];
6392 [self queueStatusDidChange];
6396 - (void) settingsButtonClicked {
6397 [delegate_ showSettings];
6401 - (void) queueButtonClicked {
6405 - (void) applyLoadingTitle {
6406 // No "Loading" title.
6409 - (void) applyRightButton {
6414 - (void) queueStatusDidChange {
6416 if (!IsWildcat_ && Queuing_) {
6417 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6418 initWithTitle:UCLocalize("QUEUE")
6419 style:UIBarButtonItemStyleDone
6421 action:@selector(queueButtonClicked)
6423 [[self navigationItem] setRightBarButtonItem:queueItem];
6425 [queueItem release];
6427 [[self navigationItem] setRightBarButtonItem:nil];
6432 - (bool) isLoading {
6439 /* Refresh Bar {{{ */
6440 @interface RefreshBar : UINavigationBar {
6441 UIProgressIndicator *indicator_;
6442 UITextLabel *prompt_;
6443 UIProgressBar *progress_;
6444 UINavigationButton *cancel_;
6449 @implementation RefreshBar
6451 - (void) positionViews {
6452 CGRect frame = [cancel_ frame];
6453 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6454 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6455 [cancel_ setFrame:frame];
6457 CGSize prgsize = {75, 100};
6459 [self frame].size.width - prgsize.width - 10,
6460 ([self frame].size.height - prgsize.height) / 2
6462 [progress_ setFrame:prgrect];
6464 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6465 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6466 CGRect indrect = {{indoffset, indoffset}, indsize};
6467 [indicator_ setFrame:indrect];
6469 CGSize prmsize = {215, indsize.height + 4};
6471 indoffset * 2 + indsize.width,
6472 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6474 [prompt_ setFrame:prmrect];
6477 - (void)setFrame:(CGRect)frame {
6478 [super setFrame:frame];
6480 [self positionViews];
6483 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6484 if ((self = [super initWithFrame:frame])) {
6485 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6487 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6488 [self setBarStyle:UIBarStyleBlack];
6490 UIBarStyle barstyle([self _barStyle:NO]);
6491 bool ugly(barstyle == UIBarStyleDefault);
6493 UIProgressIndicatorStyle style = ugly ?
6494 UIProgressIndicatorStyleMediumBrown :
6495 UIProgressIndicatorStyleMediumWhite;
6497 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6498 [indicator_ setStyle:style];
6499 [indicator_ startAnimation];
6500 [self addSubview:indicator_];
6502 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6503 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6504 [prompt_ setBackgroundColor:[UIColor clearColor]];
6505 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6506 [self addSubview:prompt_];
6508 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6509 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6510 [progress_ setStyle:0];
6511 [self addSubview:progress_];
6513 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6514 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6515 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6516 [cancel_ setBarStyle:barstyle];
6518 [self positionViews];
6523 [cancel_ removeFromSuperview];
6527 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6528 [progress_ setProgress:0];
6529 [self addSubview:cancel_];
6533 [cancel_ removeFromSuperview];
6536 - (void) setPrompt:(NSString *)prompt {
6537 [prompt_ setText:prompt];
6540 - (void) setProgress:(float)progress {
6541 [progress_ setProgress:progress];
6547 @class CYNavigationController;
6549 /* Cydia Tab Bar Controller {{{ */
6550 @interface CYTabBarController : UITabBarController {
6551 Database *database_;
6556 @implementation CYTabBarController
6558 /* XXX: some logic should probably go here related to
6559 freeing the view controllers on tab change */
6561 - (void) reloadData {
6562 size_t count([[self viewControllers] count]);
6563 for (size_t i(0); i != count; ++i) {
6564 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6569 - (id) initWithDatabase:(Database *)database {
6570 if ((self = [super init]) != nil) {
6571 database_ = database;
6578 /* Cydia Navigation Controller {{{ */
6579 @interface CYNavigationController : UINavigationController {
6580 _transient Database *database_;
6581 id<UINavigationControllerDelegate> delegate_;
6584 - (id) initWithDatabase:(Database *)database;
6585 - (void) reloadData;
6590 @implementation CYNavigationController
6592 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6593 // Inherit autorotation settings for modal parents.
6594 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6595 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6597 return [super shouldAutorotateToInterfaceOrientation:orientation];
6605 - (void) reloadData {
6606 size_t count([[self viewControllers] count]);
6607 for (size_t i(0); i != count; ++i) {
6608 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6613 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6614 delegate_ = delegate;
6617 - (id) initWithDatabase:(Database *)database {
6618 if ((self = [super init]) != nil) {
6619 database_ = database;
6625 /* Cydia:// Protocol {{{ */
6626 @interface CydiaURLProtocol : NSURLProtocol {
6631 @implementation CydiaURLProtocol
6633 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6634 NSURL *url([request URL]);
6637 NSString *scheme([[url scheme] lowercaseString]);
6638 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6643 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6647 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6648 id<NSURLProtocolClient> client([self client]);
6650 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6652 NSData *data(UIImagePNGRepresentation(icon));
6654 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6655 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6656 [client URLProtocol:self didLoadData:data];
6657 [client URLProtocolDidFinishLoading:self];
6661 - (void) startLoading {
6662 id<NSURLProtocolClient> client([self client]);
6663 NSURLRequest *request([self request]);
6665 NSURL *url([request URL]);
6666 NSString *href([url absoluteString]);
6668 NSString *path([href substringFromIndex:8]);
6669 NSRange slash([path rangeOfString:@"/"]);
6672 if (slash.location == NSNotFound) {
6676 command = [path substringToIndex:slash.location];
6677 path = [path substringFromIndex:(slash.location + 1)];
6680 Database *database([Database sharedInstance]);
6682 if ([command isEqualToString:@"package-icon"]) {
6685 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6686 Package *package([database packageWithName:path]);
6689 UIImage *icon([package icon]);
6690 [self _returnPNGWithImage:icon forRequest:request];
6691 } else if ([command isEqualToString:@"source-icon"]) {
6694 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6695 NSString *source(Simplify(path));
6696 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6698 icon = [UIImage applicationImageNamed:@"unknown.png"];
6699 [self _returnPNGWithImage:icon forRequest:request];
6700 } else if ([command isEqualToString:@"uikit-image"]) {
6703 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6704 UIImage *icon(_UIImageWithName(path));
6705 [self _returnPNGWithImage:icon forRequest:request];
6706 } else if ([command isEqualToString:@"section-icon"]) {
6709 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6710 NSString *section(Simplify(path));
6711 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6713 icon = [UIImage applicationImageNamed:@"unknown.png"];
6714 [self _returnPNGWithImage:icon forRequest:request];
6716 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6720 - (void) stopLoading {
6726 /* Sections Controller {{{ */
6727 @interface SectionsController : CYViewController <
6728 UITableViewDataSource,
6731 _transient Database *database_;
6732 NSMutableArray *sections_;
6733 NSMutableArray *filtered_;
6739 - (id) initWithDatabase:(Database *)database;
6740 - (void) reloadData;
6743 - (void) editButtonClicked;
6747 @implementation SectionsController
6750 [list_ setDataSource:nil];
6751 [list_ setDelegate:nil];
6753 [sections_ release];
6754 [filtered_ release];
6756 [accessory_ release];
6760 - (void) viewDidAppear:(BOOL)animated {
6761 [super viewDidAppear:animated];
6762 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6765 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6766 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6770 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6771 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6774 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6778 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6779 static NSString *reuseIdentifier = @"SectionCell";
6781 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6782 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6783 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6788 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6792 Section *section = [self sectionAtIndexPath:indexPath];
6793 NSString *name = [section name];
6796 if ([indexPath row] == 0) {
6799 title = UCLocalize("ALL_PACKAGES");
6802 name = [NSString stringWithString:name];
6803 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6806 title = UCLocalize("NO_SECTION");
6810 FilteredPackageController *table = [[[FilteredPackageController alloc]
6811 initWithDatabase:database_
6813 filter:@selector(isVisibleInSection:)
6817 [table setDelegate:delegate_];
6819 [[self navigationController] pushViewController:table animated:YES];
6822 - (NSString *) title { return UCLocalize("SECTIONS"); }
6824 - (id) initWithDatabase:(Database *)database {
6825 if ((self = [super init]) != nil) {
6826 database_ = database;
6828 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6830 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6831 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6833 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6834 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6835 [list_ setRowHeight:45.0f];
6836 [[self view] addSubview:list_];
6838 [list_ setDataSource:self];
6839 [list_ setDelegate:self];
6845 - (void) reloadData {
6846 NSArray *packages = [database_ packages];
6848 [sections_ removeAllObjects];
6849 [filtered_ removeAllObjects];
6852 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6853 SectionMap sections;
6854 sections.resize(64);
6856 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6860 for (Package *package in packages) {
6861 NSString *name([package section]);
6862 NSString *key(name == nil ? @"" : name);
6867 _profile(SectionsView$reloadData$Section)
6868 section = §ions[key];
6869 if (*section == nil) {
6870 _profile(SectionsView$reloadData$Section$Allocate)
6871 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6876 [*section addToCount];
6878 _profile(SectionsView$reloadData$Filter)
6879 if (![package valid] || ![package visible])
6883 [*section addToRow];
6887 _profile(SectionsView$reloadData$Section)
6888 section = [sections objectForKey:key];
6889 if (section == nil) {
6890 _profile(SectionsView$reloadData$Section$Allocate)
6891 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6892 [sections setObject:section forKey:key];
6897 [section addToCount];
6899 _profile(SectionsView$reloadData$Filter)
6900 if (![package valid] || ![package visible])
6910 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6911 [sections_ addObject:i->second];
6913 [sections_ addObjectsFromArray:[sections allValues]];
6916 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6918 for (Section *section in sections_) {
6919 size_t count([section row]);
6923 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6924 [section setCount:count];
6925 [filtered_ addObject:section];
6928 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6929 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6930 style:UIBarButtonItemStylePlain
6932 action:@selector(editButtonClicked)
6934 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6935 [rightItem release];
6941 - (void) resetView {
6943 [self editButtonClicked];
6946 - (void) editButtonClicked {
6947 if ((editing_ = !editing_))
6950 [delegate_ updateData];
6952 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6953 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6954 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6957 - (UIView *) accessoryView {
6963 /* Changes Controller {{{ */
6964 @interface ChangesController : CYViewController <
6965 UITableViewDataSource,
6968 _transient Database *database_;
6969 NSMutableArray *packages_;
6970 NSMutableArray *sections_;
6973 BOOL hasSentFirstLoad_;
6976 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6977 - (void) reloadData;
6981 @implementation ChangesController
6984 [list_ setDelegate:nil];
6985 [list_ setDataSource:nil];
6987 [packages_ release];
6988 [sections_ release];
6993 - (void) viewDidAppear:(BOOL)animated {
6994 [super viewDidAppear:animated];
6995 if (!hasSentFirstLoad_) {
6996 hasSentFirstLoad_ = YES;
6997 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6999 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7003 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7004 NSInteger count([sections_ count]);
7005 return count == 0 ? 1 : count;
7008 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7009 if ([sections_ count] == 0)
7011 return [[sections_ objectAtIndex:section] name];
7014 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7015 if ([sections_ count] == 0)
7017 return [[sections_ objectAtIndex:section] count];
7020 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7021 Section *section([sections_ objectAtIndex:[path section]]);
7022 NSInteger row([path row]);
7023 return [packages_ objectAtIndex:([section row] + row)];
7026 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7027 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7029 cell = [[[PackageCell alloc] init] autorelease];
7030 [cell setPackage:[self packageAtIndexPath:path]];
7034 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7035 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7038 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7039 Package *package([self packageAtIndexPath:path]);
7040 PackageController *view([delegate_ packageController]);
7041 [view setDelegate:delegate_];
7042 [view setPackage:package];
7043 [[self navigationController] pushViewController:view animated:YES];
7047 - (void) refreshButtonClicked {
7048 [delegate_ beginUpdate];
7049 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7052 - (void) upgradeButtonClicked {
7053 [delegate_ distUpgrade];
7056 - (NSString *) title { return UCLocalize("CHANGES"); }
7058 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7059 if ((self = [super init]) != nil) {
7060 database_ = database;
7061 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7063 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7064 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7066 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7067 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7068 [list_ setRowHeight:73.0f];
7069 [[self view] addSubview:list_];
7071 [list_ setDataSource:self];
7072 [list_ setDelegate:self];
7074 delegate_ = delegate;
7078 - (void) _reloadPackages:(NSArray *)packages {
7080 for (Package *package in packages)
7082 [package uninstalled] && [package valid] && [package visible] ||
7083 [package upgradableAndEssential:YES]
7085 [packages_ addObject:package];
7088 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7092 - (void) reloadData {
7093 NSArray *packages = [database_ packages];
7095 [packages_ removeAllObjects];
7096 [sections_ removeAllObjects];
7098 UIProgressHUD *hud([delegate_ addProgressHUD]);
7100 [hud setText:@"Loading Changes"];
7101 //NSLog(@"HUD:%@::%@", delegate_, hud);
7102 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7103 [delegate_ removeProgressHUD:hud];
7105 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7106 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7107 Section *section = nil;
7111 bool unseens = false;
7113 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7115 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7116 Package *package = [packages_ objectAtIndex:offset];
7118 BOOL uae = [package upgradableAndEssential:YES];
7124 _profile(ChangesController$reloadData$Remember)
7125 seen = [package seen];
7128 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7133 name = UCLocalize("UNKNOWN");
7135 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7139 _profile(ChangesController$reloadData$Allocate)
7140 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7141 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7142 [sections_ addObject:section];
7146 [section addToCount];
7147 } else if ([package ignored])
7148 [ignored addToCount];
7151 [upgradable addToCount];
7156 CFRelease(formatter);
7159 Section *last = [sections_ lastObject];
7160 size_t count = [last count];
7161 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7162 [sections_ removeLastObject];
7165 if ([ignored count] != 0)
7166 [sections_ insertObject:ignored atIndex:0];
7168 [sections_ insertObject:upgradable atIndex:0];
7172 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7173 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7174 style:UIBarButtonItemStylePlain
7176 action:@selector(upgradeButtonClicked)
7178 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7179 [rightItem release];
7181 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7182 initWithTitle:UCLocalize("REFRESH")
7183 style:UIBarButtonItemStylePlain
7185 action:@selector(refreshButtonClicked)
7187 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7193 /* Search Controller {{{ */
7194 @interface SearchController : FilteredPackageController <
7197 UISearchBar *search_;
7200 - (id) initWithDatabase:(Database *)database;
7201 - (void) reloadData;
7205 @implementation SearchController
7212 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7213 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7214 [search_ resignFirstResponder];
7218 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7219 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7223 - (NSString *) title { return nil; }
7225 - (id) initWithDatabase:(Database *)database {
7226 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7229 - (void)viewDidAppear:(BOOL)animated {
7230 [super viewDidAppear:animated];
7232 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7233 [search_ layoutSubviews];
7234 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7235 UITextField *textField = [search_ searchField];
7236 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7237 [search_ setDelegate:self];
7238 [textField setEnablesReturnKeyAutomatically:NO];
7239 [[self navigationItem] setTitleView:textField];
7243 - (void) _reloadData {
7246 - (void) reloadData {
7247 _profile(SearchController$reloadData)
7248 [packages_ reloadData];
7251 [packages_ resetCursor];
7254 - (void) didSelectPackage:(Package *)package {
7255 [search_ resignFirstResponder];
7256 [super didSelectPackage:package];
7261 /* Settings Controller {{{ */
7262 @interface SettingsController : CYViewController <
7263 UITableViewDataSource,
7266 _transient Database *database_;
7269 UITableView *table_;
7270 id subscribedSwitch_;
7272 UITableViewCell *subscribedCell_;
7273 UITableViewCell *ignoredCell_;
7276 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7280 @implementation SettingsController
7284 if (package_ != nil)
7287 [subscribedSwitch_ release];
7288 [ignoredSwitch_ release];
7289 [subscribedCell_ release];
7290 [ignoredCell_ release];
7295 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7296 if (package_ == nil)
7302 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7303 if (package_ == nil)
7309 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7310 return UCLocalize("SHOW_ALL_CHANGES_EX");
7313 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7314 if (package_ == nil)
7317 NSMutableDictionary *metadata([package_ metadata]);
7320 if (NSNumber *number = [metadata objectForKey:key])
7321 before = [number boolValue];
7325 if (value != before) {
7326 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7328 [delegate_ updateData];
7332 - (void) onSubscribed:(id)control {
7333 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7336 - (void) onIgnored:(id)control {
7337 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7340 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7341 if (package_ == nil)
7344 switch ([indexPath row]) {
7345 case 0: return subscribedCell_;
7346 case 1: return ignoredCell_;
7354 - (NSString *) title { return UCLocalize("SETTINGS"); }
7356 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7357 if ((self = [super init])) {
7358 database_ = database;
7359 name_ = [package retain];
7361 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7363 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7364 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7365 [[self view] addSubview:table_];
7367 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7368 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7369 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7371 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7372 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7373 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7375 subscribedCell_ = [[UITableViewCell alloc] init];
7376 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7377 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7378 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7380 ignoredCell_ = [[UITableViewCell alloc] init];
7381 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7382 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7383 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7385 [table_ setDataSource:self];
7386 [table_ setDelegate:self];
7391 - (void) reloadData {
7392 if (package_ != nil)
7393 [package_ autorelease];
7394 package_ = [database_ packageWithName:name_];
7395 if (package_ != nil) {
7397 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7398 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7401 [table_ reloadData];
7406 /* Signature Controller {{{ */
7407 @interface SignatureController : CYBrowserController {
7408 _transient Database *database_;
7412 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7416 @implementation SignatureController
7423 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7425 [super webView:view didClearWindowObject:window forFrame:frame];
7428 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7429 if ((self = [super init]) != nil) {
7430 database_ = database;
7431 package_ = [package retain];
7436 - (void) reloadData {
7437 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7443 /* Role Controller {{{ */
7444 @interface RoleController : CYViewController <
7445 UITableViewDataSource,
7448 _transient Database *database_;
7450 UITableView *table_;
7451 UISegmentedControl *segment_;
7455 - (void) showDoneButton;
7456 - (void) resizeSegmentedControl;
7460 @implementation RoleController
7464 [container_ release];
7469 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7470 if ((self = [super init])) {
7471 database_ = database;
7472 roledelegate_ = delegate;
7474 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7476 NSArray *items = [NSArray arrayWithObjects:
7478 UCLocalize("HACKER"),
7479 UCLocalize("DEVELOPER"),
7481 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7482 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7483 [container_ addSubview:segment_];
7486 if ([Role_ isEqualToString:@"User"]) index = 0;
7487 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7488 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7490 [segment_ setSelectedSegmentIndex:index];
7491 [self showDoneButton];
7494 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7495 [self resizeSegmentedControl];
7497 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7498 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7499 [table_ setDelegate:self];
7500 [table_ setDataSource:self];
7501 [[self view] addSubview:table_];
7502 [table_ reloadData];
7506 - (void) resizeSegmentedControl {
7507 CGFloat width = [[self view] frame].size.width;
7508 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7511 - (void) viewWillAppear:(BOOL)animated {
7512 [super viewWillAppear:animated];
7514 [self resizeSegmentedControl];
7517 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7518 [self resizeSegmentedControl];
7521 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7522 [self resizeSegmentedControl];
7526 NSString *role(nil);
7528 switch ([segment_ selectedSegmentIndex]) {
7529 case 0: role = @"User"; break;
7530 case 1: role = @"Hacker"; break;
7531 case 2: role = @"Developer"; break;
7536 if (![role isEqualToString:Role_]) {
7537 bool rolling(Role_ == nil);
7540 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7544 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7549 [roledelegate_ loadData];
7551 [roledelegate_ updateData];
7555 - (void) segmentChanged:(UISegmentedControl *)control {
7556 [self showDoneButton];
7559 - (void) doneButtonClicked {
7561 [[self navigationController] dismissModalViewControllerAnimated:YES];
7564 - (void) showDoneButton {
7565 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7566 initWithTitle:UCLocalize("DONE")
7567 style:UIBarButtonItemStyleDone
7569 action:@selector(doneButtonClicked)
7571 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7572 [rightItem release];
7575 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7576 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7580 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7584 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7585 return nil; // This method is required by the protocol.
7588 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7590 return UCLocalize("ROLE_EX");
7592 return [NSString stringWithFormat:
7593 @"%@: %@\n%@: %@\n%@: %@",
7594 UCLocalize("USER"), UCLocalize("USER_EX"),
7595 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7596 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7601 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7602 if (section == 3) return 44.0f;
7606 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7607 if (section == 3) return container_;
7613 /* Stash Controller {{{ */
7614 @interface CYStashController : CYViewController {
7615 UIActivityIndicatorView *spinner_;
7621 @implementation CYStashController
7623 if ((self = [super init])) {
7624 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7626 spinner_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
7627 CGRect spinrect = [spinner_ frame];
7628 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7629 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7630 [spinner_ setFrame:spinrect];
7631 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7632 [[self view] addSubview:spinner_];
7634 [spinner_ startAnimating];
7637 captrect.size.width = [[self view] frame].size.width;
7638 captrect.size.height = 40.0f;
7639 captrect.origin.x = 0;
7640 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7641 caption_ = [[UILabel alloc] initWithFrame:captrect];
7642 [caption_ setText:@"Initializing Filesystem"];
7643 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7644 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7645 [caption_ setTextColor:[UIColor whiteColor]];
7646 [caption_ setBackgroundColor:[UIColor clearColor]];
7647 [caption_ setShadowColor:[UIColor blackColor]];
7648 [caption_ setTextAlignment:UITextAlignmentCenter];
7649 [[self view] addSubview:caption_];
7653 statusrect.size.width = [[self view] frame].size.width;
7654 statusrect.size.height = 30.0f;
7655 statusrect.origin.x = 0;
7656 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7657 status_ = [[UILabel alloc] initWithFrame:statusrect];
7658 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7659 [status_ setText:@"(Cydia will exit when complete.)"];
7660 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7661 [status_ setTextColor:[UIColor whiteColor]];
7662 [status_ setBackgroundColor:[UIColor clearColor]];
7663 [status_ setShadowColor:[UIColor blackColor]];
7664 [status_ setTextAlignment:UITextAlignmentCenter];
7665 [[self view] addSubview:status_];
7670 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7671 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7676 /* Cydia Container {{{ */
7677 @interface CYContainer : UIViewController <ProgressDelegate> {
7678 _transient Database *database_;
7679 RefreshBar *refreshbar_;
7684 UITabBarController *root_;
7687 - (void) setTabBarController:(UITabBarController *)controller;
7689 - (void) dropBar:(BOOL)animated;
7690 - (void) beginUpdate;
7691 - (void) raiseBar:(BOOL)animated;
7696 @implementation CYContainer
7698 - (BOOL) _reallyWantsFullScreenLayout {
7702 // NOTE: UIWindow only sends the top controller these messages,
7703 // So we have to forward them on.
7705 - (void) viewDidAppear:(BOOL)animated {
7706 [super viewDidAppear:animated];
7707 [root_ viewDidAppear:animated];
7710 - (void) viewWillAppear:(BOOL)animated {
7711 [super viewWillAppear:animated];
7712 [root_ viewWillAppear:animated];
7715 - (void) viewDidDisappear:(BOOL)animated {
7716 [super viewDidDisappear:animated];
7717 [root_ viewDidDisappear:animated];
7720 - (void) viewWillDisappear:(BOOL)animated {
7721 [super viewWillDisappear:animated];
7722 [root_ viewWillDisappear:animated];
7725 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7726 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7729 - (void) setTabBarController:(UITabBarController *)controller {
7731 [[self view] addSubview:[root_ view]];
7734 - (void) setUpdate:(NSDate *)date {
7738 - (void) beginUpdate {
7740 [refreshbar_ start];
7745 detachNewThreadSelector:@selector(performUpdate)
7751 - (void) performUpdate { _pooled
7753 status.setDelegate(self);
7754 [database_ updateWithStatus:status];
7757 performSelectorOnMainThread:@selector(completeUpdate)
7763 - (void) completeUpdate {
7764 if (!updating_) return;
7767 [self raiseBar:YES];
7769 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7772 - (void) cancelUpdate {
7774 [self raiseBar:YES];
7776 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7779 - (void) cancelPressed {
7780 [self cancelUpdate];
7787 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7788 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7791 - (void) startProgress {
7794 - (void) setProgressTitle:(NSString *)title {
7796 performSelectorOnMainThread:@selector(_setProgressTitle:)
7802 - (bool) isCancelling:(size_t)received {
7806 - (void) setProgressPercent:(float)percent {
7808 performSelectorOnMainThread:@selector(_setProgressPercent:)
7809 withObject:[NSNumber numberWithFloat:percent]
7814 - (void) addProgressOutput:(NSString *)output {
7816 performSelectorOnMainThread:@selector(_addProgressOutput:)
7822 - (void) _setProgressTitle:(NSString *)title {
7823 [refreshbar_ setPrompt:title];
7826 - (void) _setProgressPercent:(NSNumber *)percent {
7827 [refreshbar_ setProgress:[percent floatValue]];
7830 - (void) _addProgressOutput:(NSString *)output {
7833 - (void) setUpdateDelegate:(id)delegate {
7834 updatedelegate_ = delegate;
7837 - (CGFloat) statusBarHeight {
7838 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7839 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7841 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7845 - (void) dropBar:(BOOL)animated {
7846 if (dropped_) return;
7849 [[self view] addSubview:refreshbar_];
7851 CGFloat sboffset = [self statusBarHeight];
7853 CGRect barframe = [refreshbar_ frame];
7854 barframe.origin.y = sboffset;
7855 [refreshbar_ setFrame:barframe];
7857 if (animated) [UIView beginAnimations:nil context:NULL];
7858 CGRect viewframe = [[root_ view] frame];
7859 viewframe.origin.y += barframe.size.height + sboffset;
7860 viewframe.size.height -= barframe.size.height + sboffset;
7861 [[root_ view] setFrame:viewframe];
7862 if (animated) [UIView commitAnimations];
7864 // Ensure bar has the proper width for our view, it might have changed
7865 barframe.size.width = viewframe.size.width;
7866 [refreshbar_ setFrame:barframe];
7868 // XXX: fix Apple's layout bug
7869 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7872 - (void) raiseBar:(BOOL)animated {
7873 if (!dropped_) return;
7876 [refreshbar_ removeFromSuperview];
7878 CGFloat sboffset = [self statusBarHeight];
7880 if (animated) [UIView beginAnimations:nil context:NULL];
7881 CGRect barframe = [refreshbar_ frame];
7882 CGRect viewframe = [[root_ view] frame];
7883 viewframe.origin.y -= barframe.size.height + sboffset;
7884 viewframe.size.height += barframe.size.height + sboffset;
7885 [[root_ view] setFrame:viewframe];
7886 if (animated) [UIView commitAnimations];
7888 // XXX: fix Apple's layout bug
7889 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7892 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7893 // XXX: fix Apple's layout bug
7894 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7897 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7903 // XXX: fix Apple's layout bug
7904 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7907 - (void) statusBarFrameChanged:(NSNotification *)notification {
7915 [refreshbar_ release];
7916 [[NSNotificationCenter defaultCenter] removeObserver:self];
7920 - (id) initWithDatabase:(Database *)database {
7921 if ((self = [super init]) != nil) {
7922 database_ = database;
7924 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7925 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7927 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7944 @interface Cydia : UIApplication <
7945 ConfirmationControllerDelegate,
7946 ProgressControllerDelegate,
7948 UINavigationControllerDelegate
7951 CYContainer *container_;
7954 NSMutableArray *essential_;
7955 NSMutableArray *broken_;
7957 Database *database_;
7961 UIKeyboard *keyboard_;
7962 UIProgressHUD *hud_;
7964 SectionsController *sections_;
7965 ChangesController *changes_;
7966 ManageController *manage_;
7967 SearchController *search_;
7968 SourceTable *sources_;
7969 InstalledController *installed_;
7972 CYStashController *stash_;
7977 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7978 - (void) setPage:(CYViewController *)page;
7983 static _finline void _setHomePage(Cydia *self) {
7984 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7987 @implementation Cydia
7989 - (void) beginUpdate {
7990 [container_ beginUpdate];
7994 return [container_ updating];
7997 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8002 if ([broken_ count] != 0) {
8003 int count = [broken_ count];
8005 UIAlertView *alert = [[[UIAlertView alloc]
8006 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8007 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8009 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8010 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8013 [alert setContext:@"fixhalf"];
8015 } else if (!Ignored_ && [essential_ count] != 0) {
8016 int count = [essential_ count];
8018 UIAlertView *alert = [[[UIAlertView alloc]
8019 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8020 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8022 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8023 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8026 [alert setContext:@"upgrade"];
8031 - (void) _saveConfig {
8034 NSString *error(nil);
8035 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8037 NSError *error(nil);
8038 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8039 NSLog(@"failure to save metadata data: %@", error);
8042 NSLog(@"failure to serialize metadata: %@", error);
8050 - (void) _updateData {
8053 /* XXX: this is just stupid */
8054 if (tag_ != 1 && sections_ != nil)
8055 [sections_ reloadData];
8056 if (tag_ != 2 && changes_ != nil)
8057 [changes_ reloadData];
8058 if (tag_ != 4 && search_ != nil)
8059 [search_ reloadData];
8061 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8064 - (int)indexOfTabWithTag:(int)tag {
8066 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8067 if ([[controller tabBarItem] tag] == tag) return i;
8074 - (void) _refreshIfPossible {
8075 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8077 bool recently = false;
8078 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8079 if (update != nil) {
8080 NSTimeInterval interval([update timeIntervalSinceNow]);
8081 if (interval <= 0 && interval > -(15*60))
8085 // Don't automatic refresh if:
8086 // - We already refreshed recently.
8087 // - We already auto-refreshed this launch.
8088 // - Auto-refresh is disabled.
8089 if (recently || loaded_ || ManualRefresh) {
8090 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8092 // If we are cancelling due to ManualRefresh or a recent refresh
8093 // we need to make sure it knows it's already loaded.
8097 // We are going to load, so remember that.
8101 SCNetworkReachabilityFlags flags; {
8102 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8103 SCNetworkReachabilityGetFlags(reachability, &flags);
8104 CFRelease(reachability);
8107 // XXX: this elaborate mess is what Apple is using to determine this? :(
8108 // XXX: do we care if the user has to intervene? maybe that's ok?
8110 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8111 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8112 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8113 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8114 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8115 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8119 // If we can reach the server, auto-refresh!
8121 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8126 - (void) refreshIfPossible {
8127 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8130 - (void) _reloadData {
8131 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8132 [hud setText:UCLocalize("RELOADING_DATA")];
8134 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8137 if (hud) [self removeProgressHUD:hud];
8141 [essential_ removeAllObjects];
8142 [broken_ removeAllObjects];
8144 NSArray *packages([database_ packages]);
8145 for (Package *package in packages) {
8147 [broken_ addObject:package];
8148 if ([package upgradableAndEssential:NO]) {
8149 if ([package essential])
8150 [essential_ addObject:package];
8155 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8157 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8158 [changesItem setBadgeValue:badge];
8159 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8161 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8162 [self setApplicationBadge:badge];
8164 [self setApplicationBadgeString:badge];
8166 [changesItem setBadgeValue:nil];
8167 [changesItem setAnimatedBadge:NO];
8169 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8170 [self removeApplicationBadge];
8171 else // XXX: maybe use setApplicationBadgeString also?
8172 [self setApplicationIconBadgeNumber:0];
8177 [self refreshIfPossible];
8180 - (void) updateData {
8181 [database_ setVisible];
8190 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8191 _assert(file != NULL);
8193 for (NSString *key in [Sources_ allKeys]) {
8194 NSDictionary *source([Sources_ objectForKey:key]);
8196 fprintf(file, "%s %s %s\n",
8197 [[source objectForKey:@"Type"] UTF8String],
8198 [[source objectForKey:@"URI"] UTF8String],
8199 [[source objectForKey:@"Distribution"] UTF8String]
8207 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8208 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8209 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8210 [container_ presentModalViewController:navigation animated:YES];
8213 detachNewThreadSelector:@selector(update_)
8216 title:UCLocalize("UPDATING_SOURCES")
8220 - (void) reloadData {
8221 @synchronized (self) {
8227 pkgProblemResolver *resolver = [database_ resolver];
8229 resolver->InstallProtect();
8230 if (!resolver->Resolve(true))
8234 - (CGRect) popUpBounds {
8235 return [[tabbar_ view] bounds];
8239 if (![database_ prepare])
8242 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8243 [page setDelegate:self];
8244 CYNavigationController *confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8245 [confirm_ setDelegate:self];
8247 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8248 [container_ presentModalViewController:confirm_ animated:YES];
8254 @synchronized (self) {
8259 - (void) clearPackage:(Package *)package {
8260 @synchronized (self) {
8267 - (void) installPackages:(NSArray *)packages {
8268 @synchronized (self) {
8269 for (Package *package in packages)
8276 - (void) installPackage:(Package *)package {
8277 @synchronized (self) {
8284 - (void) removePackage:(Package *)package {
8285 @synchronized (self) {
8292 - (void) distUpgrade {
8293 @synchronized (self) {
8294 if (![database_ upgrade])
8301 @synchronized (self) {
8306 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8307 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8309 if (navigation != nil) {
8310 [navigation pushViewController:progress animated:YES];
8312 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8313 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8314 [container_ presentModalViewController:navigation animated:YES];
8318 detachNewThreadSelector:@selector(perform)
8321 title:UCLocalize("RUNNING")
8325 - (void) progressControllerIsComplete:(ProgressController *)progress {
8329 - (void) setPage:(CYViewController *)page {
8330 [page setDelegate:self];
8332 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8333 [navController setViewControllers:[NSArray arrayWithObject:page]];
8334 for (CYNavigationController *page in [tabbar_ viewControllers]) {
8335 if (page != navController) [page setViewControllers:nil];
8339 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8340 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8341 [browser loadURL:url];
8345 - (SectionsController *) sectionsController {
8346 if (sections_ == nil)
8347 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8351 - (ChangesController *) changesController {
8352 if (changes_ == nil)
8353 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8357 - (ManageController *) manageController {
8358 if (manage_ == nil) {
8359 manage_ = (ManageController *) [[self
8360 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8361 withClass:[ManageController class]
8363 if (!IsWildcat_) queueDelegate_ = manage_;
8368 - (SearchController *) searchController {
8370 search_ = [[SearchController alloc] initWithDatabase:database_];
8374 - (SourceTable *) sourcesController {
8375 if (sources_ == nil)
8376 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8380 - (InstalledController *) installedController {
8381 if (installed_ == nil) {
8382 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8383 if (IsWildcat_) queueDelegate_ = installed_;
8388 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8389 int tag = [[viewController tabBarItem] tag];
8391 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8393 } else if (tag_ == 1) {
8394 [[self sectionsController] resetView];
8398 case kCydiaTag: _setHomePage(self); break;
8400 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8401 case kChangesTag: [self setPage:[self changesController]]; break;
8402 case kManageTag: [self setPage:[self manageController]]; break;
8403 case kInstalledTag: [self setPage:[self installedController]]; break;
8404 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8405 case kSearchTag: [self setPage:[self searchController]]; break;
8413 - (void) showSettings {
8414 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8415 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
8416 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8417 [container_ presentModalViewController:nav animated:YES];
8420 - (void) setPackageController:(PackageController *)view {
8422 [view setPackage:nil];
8426 - (PackageController *) _packageController {
8427 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8430 - (PackageController *) packageController {
8431 return [self _packageController];
8434 // Returns the navigation controller for the queuing badge.
8435 - (id) queueBadgeController {
8436 int index = [self indexOfTabWithTag:kManageTag];
8437 if (index == -1) index = [self indexOfTabWithTag:kInstalledTag];
8439 return [[tabbar_ viewControllers] objectAtIndex:index];
8442 - (void) cancelAndClear:(bool)clear {
8443 @synchronized (self) {
8446 pkgCacheFile &cache([database_ cache]);
8447 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8448 // Unmark method taken from Synaptic Package Manager.
8449 // Thanks for being sane, unlike Aptitude.
8450 if (!cache[iterator].Keep()) {
8451 cache->MarkKeep(iterator, false);
8452 cache->SetReInstall(iterator, false);
8458 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8462 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8465 // Show the changes in the current view.
8466 [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
8467 [queueDelegate_ queueStatusDidChange];
8471 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8472 NSString *context([alert context]);
8474 if ([context isEqualToString:@"fixhalf"]) {
8475 if (button == [alert firstOtherButtonIndex]) {
8476 @synchronized (self) {
8477 for (Package *broken in broken_) {
8480 NSString *id = [broken id];
8481 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8482 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8483 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8484 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8490 } else if (button == [alert cancelButtonIndex]) {
8491 [broken_ removeAllObjects];
8495 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8496 } else if ([context isEqualToString:@"upgrade"]) {
8497 if (button == [alert firstOtherButtonIndex]) {
8498 @synchronized (self) {
8499 for (Package *essential in essential_)
8500 [essential install];
8505 } else if (button == [alert firstOtherButtonIndex] + 1) {
8507 } else if (button == [alert cancelButtonIndex]) {
8511 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8515 - (void) system:(NSString *)command { _pooled
8516 system([command UTF8String]);
8519 - (void) applicationWillSuspend {
8521 [super applicationWillSuspend];
8524 - (void) applicationSuspend:(__GSEvent *)event {
8525 // Use external process status API internally.
8526 // This is probably a really bad idea.
8527 uint64_t status = 0;
8529 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8530 notify_get_state(notify_token, &status);
8531 notify_cancel(notify_token);
8534 if (hud_ == nil && status == 0)
8535 [super applicationSuspend:event];
8538 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8540 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8543 - (void) _setSuspended:(BOOL)value {
8545 [super _setSuspended:value];
8548 - (UIProgressHUD *) addProgressHUD {
8549 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8550 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8552 [window_ setUserInteractionEnabled:NO];
8555 UIViewController *target = container_;
8556 while ([target modalViewController] != nil) target = [target modalViewController];
8557 [[target view] addSubview:hud];
8562 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8564 [hud removeFromSuperview];
8565 [window_ setUserInteractionEnabled:YES];
8568 - (CYViewController *) pageForPackage:(NSString *)name {
8569 if (Package *package = [database_ packageWithName:name]) {
8570 PackageController *view([self packageController]);
8571 [view setPackage:package];
8574 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8575 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8576 return [self _pageForURL:url withClass:[CYBrowserController class]];
8580 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8584 NSString *href([url absoluteString]);
8585 if ([href hasPrefix:@"apptapp://package/"])
8586 return [self pageForPackage:[href substringFromIndex:18]];
8588 NSString *scheme([[url scheme] lowercaseString]);
8589 if (![scheme isEqualToString:@"cydia"])
8591 NSString *path([url absoluteString]);
8592 if ([path length] < 8)
8594 path = [path substringFromIndex:8];
8595 if (![path hasPrefix:@"/"])
8596 path = [@"/" stringByAppendingString:path];
8598 if ([path isEqualToString:@"/add-source"])
8599 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8600 else if ([path isEqualToString:@"/storage"])
8601 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8602 else if ([path isEqualToString:@"/sources"])
8603 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8604 else if ([path isEqualToString:@"/packages"])
8605 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8606 else if ([path hasPrefix:@"/url/"])
8607 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8608 else if ([path hasPrefix:@"/launch/"])
8609 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8610 else if ([path hasPrefix:@"/package-settings/"])
8611 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8612 else if ([path hasPrefix:@"/package-signature/"])
8613 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8614 else if ([path hasPrefix:@"/package/"])
8615 return [self pageForPackage:[path substringFromIndex:9]];
8616 else if ([path hasPrefix:@"/files/"]) {
8617 NSString *name = [path substringFromIndex:7];
8619 if (Package *package = [database_ packageWithName:name]) {
8620 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8621 [files setPackage:package];
8629 - (void) applicationOpenURL:(NSURL *)url {
8630 [super applicationOpenURL:url];
8632 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8633 [self setPage:page];
8635 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8639 - (void) applicationWillResignActive:(UIApplication *)application {
8640 // Stop refreshing if you get a phone call or lock the device.
8641 if ([container_ updating]) [container_ cancelUpdate];
8643 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8644 [super applicationWillResignActive:application];
8647 - (void) addStashController {
8648 stash_ = [[CYStashController alloc] init];
8649 [window_ addSubview:[stash_ view]];
8652 - (void) removeStashController {
8653 [[stash_ view] removeFromSuperview];
8658 [self setIdleTimerDisabled:YES];
8660 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8661 [self setStatusBarShowsProgress:YES];
8662 UpdateExternalStatus(1);
8664 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8666 UpdateExternalStatus(0);
8667 [self setStatusBarShowsProgress:NO];
8669 [self removeStashController];
8671 if (ExecFork() == 0) {
8672 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8673 perror("launchctl stop");
8677 - (void) setupTabBarController {
8678 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8679 [tabbar_ setDelegate:self];
8681 NSMutableArray *items([NSMutableArray arrayWithObjects:
8682 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8683 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8684 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8685 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8689 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8690 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8692 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8695 NSMutableArray *controllers([NSMutableArray array]);
8697 for (UITabBarItem *item in items) {
8698 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8699 [controller setTabBarItem:item];
8700 [controllers addObject:controller];
8703 [tabbar_ setViewControllers:controllers];
8704 [tabbar_ setSelectedIndex:0];
8707 - (void) applicationDidFinishLaunching:(id)unused {
8708 [CYBrowserController _initialize];
8710 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8712 Font12_ = [[UIFont systemFontOfSize:12] retain];
8713 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8714 Font14_ = [[UIFont systemFontOfSize:14] retain];
8715 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8716 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8720 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8721 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8723 UIScreen *screen([UIScreen mainScreen]);
8725 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8726 [window_ orderFront:self];
8727 [window_ makeKey:self];
8728 [window_ setHidden:NO];
8731 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8732 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8733 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8734 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8735 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8736 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8737 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8738 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8739 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8742 [self addStashController];
8743 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8747 database_ = [Database sharedInstance];
8749 [self setupTabBarController];
8751 container_ = [[CYContainer alloc] initWithDatabase:database_];
8752 [container_ setUpdateDelegate:self];
8753 [container_ setTabBarController:tabbar_];
8754 [window_ addSubview:[container_ view]];
8756 // Show pinstripes while loading data.
8757 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8759 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8764 [self showSettings];
8768 [UIKeyboard initImplementationNow];
8770 [window_ setUserInteractionEnabled:NO];
8772 UIView *container = [[UIView alloc] init];
8773 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8775 UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
8776 [spinner startAnimating];
8777 [container addSubview:spinner];
8780 UILabel *label = [[UILabel alloc] init];
8781 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8782 [label setBackgroundColor:[UIColor clearColor]];
8783 [label setTextColor:[UIColor blackColor]];
8784 [label setShadowColor:[UIColor whiteColor]];
8785 [label setShadowOffset:CGSizeMake(0, 1)];
8786 [label setText:UCLocalize("LOADING_DATA")];
8787 [container addSubview:label];
8790 CGSize viewsize = [[tabbar_ view] frame].size;
8791 CGSize spinnersize = [spinner bounds].size;
8792 CGSize textsize = [[label text] sizeWithFont:[label font]];
8793 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8795 CGRect containrect = {
8796 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8797 CGSizeMake(bothwidth, spinnersize.height)
8800 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8808 [container setFrame:containrect];
8809 [spinner setFrame:spinrect];
8810 [label setFrame:textrect];
8811 [[container_ view] addSubview:container];
8812 [container release];
8817 // Show the home page
8819 [window_ setUserInteractionEnabled:YES];
8821 // XXX: does this actually slow anything down?
8822 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8823 [container removeFromSuperview];
8826 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8827 if (item != nil && IsWildcat_) {
8828 [sheet showFromBarButtonItem:item animated:YES];
8830 [sheet showInView:window_];
8837 id Alloc_(id self, SEL selector) {
8838 id object = alloc_(self, selector);
8839 lprintf("[%s]A-%p\n", self->isa->name, object);
8844 id Dealloc_(id self, SEL selector) {
8845 id object = dealloc_(self, selector);
8846 lprintf("[%s]D-%p\n", self->isa->name, object);
8850 Class $WebDefaultUIKitDelegate;
8852 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8853 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8854 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8855 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8858 static NSNumber *shouldPlayKeyboardSounds;
8862 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8864 case 1104: // Keyboard Button Clicked
8865 case 1105: // Keyboard Delete Repeated
8866 if (shouldPlayKeyboardSounds == nil) {
8867 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8868 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8871 if (![shouldPlayKeyboardSounds boolValue])
8875 _UIHardware$_playSystemSound$(self, _cmd, sound);
8879 int main(int argc, char *argv[]) { _pooled
8882 if (Class $UIDevice = objc_getClass("UIDevice")) {
8883 UIDevice *device([$UIDevice currentDevice]);
8884 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8888 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8890 /* Library Hacks {{{ */
8891 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8893 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8894 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8895 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8896 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8897 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8900 $UIHardware = objc_getClass("UIHardware");
8901 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8902 if (UIHardware$_playSystemSound$ != NULL) {
8903 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8904 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8907 /* Set Locale {{{ */
8908 Locale_ = CFLocaleCopyCurrent();
8909 Languages_ = [NSLocale preferredLanguages];
8910 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8911 //NSLog(@"%@", [Languages_ description]);
8914 if (Languages_ == nil || [Languages_ count] == 0)
8915 // XXX: consider just setting to C and then falling through?
8918 lang = [[Languages_ objectAtIndex:0] UTF8String];
8919 setenv("LANG", lang, true);
8922 //std::setlocale(LC_ALL, lang);
8923 NSLog(@"Setting Language: %s", lang);
8926 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8928 /* Parse Arguments {{{ */
8929 bool substrate(false);
8935 for (int argi(1); argi != argc; ++argi)
8936 if (strcmp(argv[argi], "--") == 0) {
8938 argv[argi] = argv[0];
8944 for (int argi(1); argi != arge; ++argi)
8945 if (strcmp(args[argi], "--substrate") == 0)
8948 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8952 App_ = [[NSBundle mainBundle] bundlePath];
8953 Home_ = NSHomeDirectory();
8959 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8960 alloc_ = alloc->method_imp;
8961 alloc->method_imp = (IMP) &Alloc_;*/
8963 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8964 dealloc_ = dealloc->method_imp;
8965 dealloc->method_imp = (IMP) &Dealloc_;*/
8967 /* System Information {{{ */
8971 size = sizeof(maxproc);
8972 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8973 perror("sysctlbyname(\"kern.maxproc\", ?)");
8974 else if (maxproc < 64) {
8976 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8977 perror("sysctlbyname(\"kern.maxproc\", #)");
8980 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8981 char *osversion = new char[size];
8982 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8983 perror("sysctlbyname(\"kern.osversion\", ?)");
8985 System_ = [NSString stringWithUTF8String:osversion];
8987 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8988 char *machine = new char[size];
8989 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8990 perror("sysctlbyname(\"hw.machine\", ?)");
8994 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8995 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8996 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8997 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9001 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9002 NSData *data((NSData *) ecid);
9003 size_t length([data length]);
9004 uint8_t bytes[length];
9005 [data getBytes:bytes];
9006 char string[length * 2 + 1];
9007 for (size_t i(0); i != length; ++i)
9008 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9009 ChipID_ = [NSString stringWithUTF8String:string];
9013 IOObjectRelease(service);
9017 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9019 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9020 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9021 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9023 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9024 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9025 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9027 if (mcc != NULL && mnc != NULL)
9028 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9035 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9036 Build_ = [system objectForKey:@"ProductBuildVersion"];
9037 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9038 Product_ = [info objectForKey:@"SafariProductVersion"];
9039 Safari_ = [info objectForKey:@"CFBundleVersion"];
9042 /* Load Database {{{ */
9044 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9046 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9049 if (Metadata_ == NULL)
9050 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9052 Settings_ = [Metadata_ objectForKey:@"Settings"];
9054 Packages_ = [Metadata_ objectForKey:@"Packages"];
9055 Sections_ = [Metadata_ objectForKey:@"Sections"];
9056 Sources_ = [Metadata_ objectForKey:@"Sources"];
9058 Token_ = [Metadata_ objectForKey:@"Token"];
9061 if (Settings_ != nil)
9062 Role_ = [Settings_ objectForKey:@"Role"];
9064 if (Packages_ == nil) {
9065 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9066 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9069 if (Sections_ == nil) {
9070 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9071 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9074 if (Sources_ == nil) {
9075 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9076 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9080 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9082 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9083 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9084 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9085 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9086 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9087 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9089 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9091 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9092 unlink("/tmp/.cydia.fw");
9094 } else if (access("/User", F_OK) != 0 || version < 2) {
9097 system("/usr/libexec/cydia/firmware.sh");
9101 _assert([[NSFileManager defaultManager]
9102 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9103 withIntermediateDirectories:YES
9108 if (access("/tmp/cydia.chk", F_OK) == 0) {
9109 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9110 _assert(errno == ENOENT);
9111 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9112 _assert(errno == ENOENT);
9115 /* APT Initialization {{{ */
9116 _assert(pkgInitConfig(*_config));
9117 _assert(pkgInitSystem(*_config, _system));
9120 _config->Set("APT::Acquire::Translation", lang);
9122 // XXX: this timeout might be important :(
9123 //_config->Set("Acquire::http::Timeout", 15);
9125 _config->Set("Acquire::http::MaxParallel", 3);
9127 /* Color Choices {{{ */
9128 space_ = CGColorSpaceCreateDeviceRGB();
9130 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9131 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9132 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9133 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9134 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9135 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9136 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9137 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9138 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9140 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9141 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9143 /* UIKit Configuration {{{ */
9144 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9145 if ($GSFontSetUseLegacyFontMetrics != NULL)
9146 $GSFontSetUseLegacyFontMetrics(YES);
9148 // XXX: I have a feeling this was important
9149 //UIKeyboardDisableAutomaticAppearance();
9152 Colon_ = UCLocalize("COLON_DELIMITED");
9153 Error_ = UCLocalize("ERROR");
9154 Warning_ = UCLocalize("WARNING");
9157 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9159 CGColorSpaceRelease(space_);