1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 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>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
122 #include <Cytore.hpp>
124 #include "UICaboodle/BrowserView.h"
125 #include "SDURLCache/SDURLCache.h"
127 #include "substrate.h"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
202 #define CYPoolStart() \
203 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
205 #define CYPoolEnd() \
209 // Hash Functions/Structures {{{
210 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
218 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
220 static _finline NSString *CydiaURL(NSString *path) {
222 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
223 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
224 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
225 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
226 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
227 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
230 static _finline void UpdateExternalStatus(uint64_t newStatus) {
232 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
233 notify_set_state(notify_token, newStatus);
234 notify_cancel(notify_token);
236 notify_post("com.saurik.Cydia.status");
239 /* [NSObject yieldToSelector:(withObject:)] {{{*/
240 @interface NSObject (Cydia)
241 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
242 - (id) yieldToSelector:(SEL)selector;
245 @implementation NSObject (Cydia)
250 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
251 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
252 id object([[context objectAtIndex:1] nonretainedObjectValue]);
253 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
255 /* XXX: deal with exceptions */
256 id value([self performSelector:selector withObject:object]);
258 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
259 [context removeAllObjects];
260 if ([signature methodReturnLength] != 0 && value != nil)
261 [context addObject:value];
266 performSelectorOnMainThread:@selector(doNothing)
272 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
273 volatile bool stopped(false);
275 NSMutableArray *context([NSMutableArray arrayWithObjects:
276 [NSValue valueWithPointer:selector],
277 [NSValue valueWithNonretainedObject:object],
278 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
281 NSThread *thread([[[NSThread alloc]
283 selector:@selector(_yieldToContext:)
289 NSRunLoop *loop([NSRunLoop currentRunLoop]);
290 NSDate *future([NSDate distantFuture]);
291 NSString *mode([loop currentMode] ?: NSDefaultRunLoopMode);
293 while (!stopped && [loop runMode:mode beforeDate:future]);
295 return [context count] == 0 ? nil : [context objectAtIndex:0];
298 - (id) yieldToSelector:(SEL)selector {
299 return [self yieldToSelector:selector withObject:nil];
305 /* Cydia Alert View {{{ */
306 @interface CYAlertView : UIAlertView {
310 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
314 @implementation CYAlertView
316 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
317 if ((self = [super init]) != nil) {
318 [self setTitle:title];
319 [self setDelegate:self];
320 for (NSString *button in buttons) [self addButtonWithTitle:button];
321 [self setCancelButtonIndex:index];
325 - (void) _updateFrameForDisplay {
326 [super _updateFrameForDisplay];
327 if ([self cancelButtonIndex] == -1) {
328 NSArray *buttons = [self buttons];
329 if ([buttons count]) {
330 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
331 for (UIThreePartButton *button in buttons)
332 [button setBackground:background forState:0];
337 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
338 button_ = buttonIndex + 1;
342 [self dismissWithClickedButtonIndex:-1 animated:YES];
345 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
346 [self setRunsModal:YES];
355 /* NSForcedOrderingSearch doesn't work on the iPhone */
356 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
357 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
358 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
360 #define lprintf(args...) fprintf(stderr, args)
363 #define TraceLogging (1 && !ForRelease)
364 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
365 #define ProfileTimes (0 && !ForRelease)
366 #define ForSaurik (0 && !ForRelease)
367 #define LogBrowser (0 && !ForRelease)
368 #define TrackResize (0 && !ForRelease)
369 #define ManualRefresh (1 && !ForRelease)
370 #define ShowInternals (0 && !ForRelease)
371 #define AlwaysReload (0 && !ForRelease)
372 #define TryIndexedCollation (0 && !ForRelease)
376 #define _trace(args...)
381 #define _profile(name) {
384 #define PrintTimes() do {} while (false)
388 typedef uint32_t (*SKRadixFunction)(id, void *);
390 @interface NSMutableArray (Radix)
391 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
399 @implementation NSMutableArray (Radix)
401 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
402 size_t count([self count]);
403 struct RadixItem_ *swap(new RadixItem_[count * 2]);
405 for (size_t i(0); i != count; ++i) {
406 RadixItem_ &item(swap[i]);
409 id object([self objectAtIndex:i]);
410 item.key = function(object, argument);
413 struct RadixItem_ *lhs(swap), *rhs(swap + count);
415 static const size_t width = 32;
416 static const size_t bits = 11;
417 static const size_t slots = 1 << bits;
418 static const size_t passes = (width + (bits - 1)) / bits;
420 size_t *hist(new size_t[slots]);
422 for (size_t pass(0); pass != passes; ++pass) {
423 memset(hist, 0, sizeof(size_t) * slots);
425 for (size_t i(0); i != count; ++i) {
426 uint32_t key(lhs[i].key);
428 key &= _not(uint32_t) >> width - bits;
433 for (size_t i(0); i != slots; ++i) {
434 size_t local(offset);
439 for (size_t i(0); i != count; ++i) {
440 uint32_t key(lhs[i].key);
442 key &= _not(uint32_t) >> width - bits;
443 rhs[hist[key]++] = lhs[i];
446 RadixItem_ *tmp(lhs);
453 const void **values(new const void *[count]);
454 for (size_t i(0); i != count; ++i)
455 values[i] = [self objectAtIndex:lhs[i].index];
456 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
464 /* Insertion Sort {{{ */
466 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
467 const char *ptr = (const char *)list;
469 CFIndex half = count / 2;
470 const char *probe = ptr + elementSize * half;
471 CFComparisonResult cr = comparator(element, probe, context);
472 if (0 == cr) return (probe - (const char *)list) / elementSize;
473 ptr = (cr < 0) ? ptr : probe + elementSize;
474 count = (cr < 0) ? half : (half + (count & 1) - 1);
476 return (ptr - (const char *)list) / elementSize;
479 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
480 const char *ptr = (const char *)list;
482 CFIndex half = count / 2;
483 const char *probe = ptr + elementSize * half;
484 CFComparisonResult cr = comparator(element, probe, context);
485 if (0 == cr) return (probe - (const char *)list) / elementSize;
486 ptr = (cr < 0) ? ptr : probe + elementSize;
487 count = (cr < 0) ? half : (half + (count & 1) - 1);
489 return (ptr - (const char *)list) / elementSize;
492 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
493 if (range.length == 0)
495 const void **values(new const void *[range.length]);
496 CFArrayGetValues(array, range, values);
498 #if HistogramInsertionSort > 0
499 uint32_t total(0), *offsets(new uint32_t[range.length]);
502 for (CFIndex index(1); index != range.length; ++index) {
503 const void *value(values[index]);
504 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
505 CFIndex correct(index);
506 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
507 #if HistogramInsertionSort > 1
508 NSLog(@"%@ < %@", value, values[correct - 1]);
513 if (correct != index) {
514 size_t offset(index - correct);
515 #if HistogramInsertionSort
519 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
521 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
522 values[correct] = value;
526 CFArrayReplaceValues(array, range, values, range.length);
529 #if HistogramInsertionSort > 0
530 for (CFIndex index(0); index != range.length; ++index)
531 if (offsets[index] != 0)
532 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
533 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
540 /* Apple Bug Fixes {{{ */
541 @implementation UIWebDocumentView (Cydia)
543 - (void) _setScrollerOffset:(CGPoint)offset {
544 UIScroller *scroller([self _scroller]);
546 CGSize size([scroller contentSize]);
547 CGSize bounds([scroller bounds].size);
550 max.x = size.width - bounds.width;
551 max.y = size.height - bounds.height;
559 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
560 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
562 [scroller setOffset:offset];
568 @interface NSInvocation (Cydia)
569 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target;
572 @implementation NSInvocation (Cydia)
574 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target {
575 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
576 [invocation setTarget:target];
577 [invocation setSelector:selector];
583 @implementation WebScriptObject (NSFastEnumeration)
585 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
586 size_t length([self count] - state->state);
589 else if (length > count)
591 for (size_t i(0); i != length; ++i)
592 objects[i] = [self objectAtIndex:state->state++];
593 state->itemsPtr = objects;
594 state->mutationsPtr = (unsigned long *) self;
600 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
601 size_t length([self length] - state->state);
604 else if (length > count)
606 for (size_t i(0); i != length; ++i)
607 objects[i] = [self item:state->state++];
608 state->itemsPtr = objects;
609 state->mutationsPtr = (unsigned long *) self;
613 /* Cydia NSString Additions {{{ */
614 @interface NSString (Cydia)
615 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
616 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
617 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
618 - (NSComparisonResult) compareByPath:(NSString *)other;
619 - (NSString *) stringByCachingURLWithCurrentCDN;
620 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
623 @implementation NSString (Cydia)
625 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
626 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
629 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
630 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
631 memcpy(data, bytes, length);
632 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
635 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
636 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
639 - (NSComparisonResult) compareByPath:(NSString *)other {
640 NSString *prefix = [self commonPrefixWithString:other options:0];
641 size_t length = [prefix length];
643 NSRange lrange = NSMakeRange(length, [self length] - length);
644 NSRange rrange = NSMakeRange(length, [other length] - length);
646 lrange = [self rangeOfString:@"/" options:0 range:lrange];
647 rrange = [other rangeOfString:@"/" options:0 range:rrange];
649 NSComparisonResult value;
651 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
652 value = NSOrderedSame;
653 else if (lrange.location == NSNotFound)
654 value = NSOrderedAscending;
655 else if (rrange.location == NSNotFound)
656 value = NSOrderedDescending;
658 value = NSOrderedSame;
660 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
661 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
662 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
663 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
665 NSComparisonResult result = [lpath compare:rpath];
666 return result == NSOrderedSame ? value : result;
669 - (NSString *) stringByCachingURLWithCurrentCDN {
671 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
672 withString:@"://cache.cydia.saurik.com/"
676 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
677 return [(id)CFURLCreateStringByAddingPercentEscapes(
682 kCFStringEncodingUTF8
689 /* C++ NSString Wrapper Cache {{{ */
690 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
691 return size == 0 ? NULL :
692 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
693 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
696 static _finline CFStringRef CYStringCreate(const char *data) {
697 return CYStringCreate(data, strlen(data));
706 _finline void clear_() {
707 if (cache_ != NULL) {
714 _finline bool empty() const {
718 _finline size_t size() const {
722 _finline char *data() const {
726 _finline void clear() {
731 _finline CYString() :
738 _finline ~CYString() {
742 void operator =(const CYString &rhs) {
746 if (rhs.cache_ == nil)
749 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
752 void copy(apr_pool_t *pool) {
753 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
754 memcpy(temp, data_, size_);
759 void set(apr_pool_t *pool, const char *data, size_t size) {
765 data_ = const_cast<char *>(data);
773 _finline void set(apr_pool_t *pool, const char *data) {
774 set(pool, data, data == NULL ? 0 : strlen(data));
777 _finline void set(apr_pool_t *pool, const std::string &rhs) {
778 set(pool, rhs.data(), rhs.size());
781 bool operator ==(const CYString &rhs) const {
782 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
785 _finline operator CFStringRef() {
787 cache_ = CYStringCreate(data_, size_);
791 _finline operator id() {
792 return (NSString *) static_cast<CFStringRef>(*this);
795 _finline operator const char *() {
796 return reinterpret_cast<const char *>(data_);
800 /* C++ NSString Algorithm Adapters {{{ */
802 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
805 struct NSStringMapHash :
806 std::unary_function<NSString *, size_t>
808 _finline size_t operator ()(NSString *value) const {
809 return CFStringHashNSString((CFStringRef) value);
813 struct NSStringMapLess :
814 std::binary_function<NSString *, NSString *, bool>
816 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
817 return [lhs compare:rhs] == NSOrderedAscending;
821 struct NSStringMapEqual :
822 std::binary_function<NSString *, NSString *, bool>
824 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
825 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
826 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
827 //[lhs isEqualToString:rhs];
832 /* Perl-Compatible RegEx {{{ */
842 Pcre(const char *regex) :
847 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
850 lprintf("%d:%s\n", offset, error);
854 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
855 matches_ = new int[(capture_ + 1) * 3];
863 NSString *operator [](size_t match) {
864 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
867 bool operator ()(NSString *data) {
868 // XXX: length is for characters, not for bytes
869 return operator ()([data UTF8String], [data length]);
872 bool operator ()(const char *data, size_t size) {
874 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
878 /* Mime Addresses {{{ */
879 @interface Address : NSObject {
885 - (NSString *) address;
887 - (void) setAddress:(NSString *)address;
889 + (Address *) addressWithString:(NSString *)string;
890 - (Address *) initWithString:(NSString *)string;
894 @implementation Address
903 - (NSString *) name {
907 - (NSString *) address {
911 - (void) setAddress:(NSString *)address {
913 [address_ autorelease];
917 address_ = [address retain];
920 + (Address *) addressWithString:(NSString *)string {
921 return [[[Address alloc] initWithString:string] autorelease];
924 + (NSArray *) _attributeKeys {
925 return [NSArray arrayWithObjects:
931 - (NSArray *) attributeKeys {
932 return [[self class] _attributeKeys];
935 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
936 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
939 - (Address *) initWithString:(NSString *)string {
940 if ((self = [super init]) != nil) {
941 const char *data = [string UTF8String];
942 size_t size = [string length];
944 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
946 if (address_r(data, size)) {
947 name_ = [address_r[1] retain];
948 address_ = [address_r[2] retain];
950 name_ = [string retain];
958 /* CoreGraphics Primitives {{{ */
963 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
964 CGFloat color[] = {red, green, blue, alpha};
965 return CGColorCreate(space, color);
974 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
975 color_(Create_(space, red, green, blue, alpha))
977 Set(space, red, green, blue, alpha);
982 CGColorRelease(color_);
989 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
991 color_ = Create_(space, red, green, blue, alpha);
994 operator CGColorRef() {
1000 /* Random Global Variables {{{ */
1001 static const int PulseInterval_ = 50000;
1003 static const NSString *UI_;
1006 static bool RestartSubstrate_;
1007 static NSArray *Finishes_;
1009 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1010 #define NotifyConfig_ "/etc/notify.conf"
1012 static bool Queuing_;
1014 static CYColor Blue_;
1015 static CYColor Blueish_;
1016 static CYColor Black_;
1017 static CYColor Off_;
1018 static CYColor White_;
1019 static CYColor Gray_;
1020 static CYColor Green_;
1021 static CYColor Purple_;
1022 static CYColor Purplish_;
1024 static UIColor *InstallingColor_;
1025 static UIColor *RemovingColor_;
1027 static NSString *App_;
1028 static NSString *Home_;
1030 static BOOL Advanced_;
1031 static BOOL Ignored_;
1033 static UIFont *Font12_;
1034 static UIFont *Font12Bold_;
1035 static UIFont *Font14_;
1036 static UIFont *Font18Bold_;
1037 static UIFont *Font22Bold_;
1039 static const char *Machine_ = NULL;
1040 static NSString *System_ = nil;
1041 static NSString *SerialNumber_ = nil;
1042 static NSString *ChipID_ = nil;
1043 static NSString *Token_ = nil;
1044 static NSString *UniqueID_ = nil;
1045 static NSString *PLMN_ = nil;
1046 static NSString *Build_ = nil;
1047 static NSString *Product_ = nil;
1048 static NSString *Safari_ = nil;
1050 static CFLocaleRef Locale_;
1051 static NSArray *Languages_;
1052 static CGColorSpaceRef space_;
1054 static NSDictionary *SectionMap_;
1055 static NSMutableDictionary *Metadata_;
1056 static _transient NSMutableDictionary *Settings_;
1057 static _transient NSString *Role_;
1058 static _transient NSMutableDictionary *Packages_;
1059 static _transient NSMutableDictionary *Sections_;
1060 static _transient NSMutableDictionary *Sources_;
1061 static bool Changed_;
1065 static CGFloat ScreenScale_;
1068 /* Display Helpers {{{ */
1069 inline float Interpolate(float begin, float end, float fraction) {
1070 return (end - begin) * fraction + begin;
1073 static _finline const char *StripVersion_(const char *version) {
1074 const char *colon(strchr(version, ':'));
1075 return colon == NULL ? version : colon + 1;
1078 NSString *LocalizeSection(NSString *section) {
1079 static Pcre title_r("^(.*?) \\((.*)\\)$");
1080 if (title_r(section)) {
1081 NSString *parent(title_r[1]);
1082 NSString *child(title_r[2]);
1084 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1085 LocalizeSection(parent),
1086 LocalizeSection(child)
1090 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1093 NSString *Simplify(NSString *title) {
1094 const char *data = [title UTF8String];
1095 size_t size = [title length];
1097 static Pcre square_r("^\\[(.*)\\]$");
1098 if (square_r(data, size))
1099 return Simplify(square_r[1]);
1101 static Pcre paren_r("^\\((.*)\\)$");
1102 if (paren_r(data, size))
1103 return Simplify(paren_r[1]);
1105 static Pcre title_r("^(.*?) \\((.*)\\)$");
1106 if (title_r(data, size))
1107 return Simplify(title_r[1]);
1113 NSString *GetLastUpdate() {
1114 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1117 return UCLocalize("NEVER_OR_UNKNOWN");
1119 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1120 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1122 CFRelease(formatter);
1124 return [(NSString *) formatted autorelease];
1127 bool isSectionVisible(NSString *section) {
1128 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1129 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1130 return hidden == nil || ![hidden boolValue];
1135 /* Delegate Prototypes {{{ */
1138 @class CydiaProgressEvent;
1140 @protocol DatabaseDelegate
1141 - (void) repairWithSelector:(SEL)selector;
1142 - (void) setConfigurationData:(NSString *)data;
1143 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1146 @class CYPackageController;
1148 @protocol CydiaDelegate
1149 - (void) retainNetworkActivityIndicator;
1150 - (void) releaseNetworkActivityIndicator;
1151 - (void) clearPackage:(Package *)package;
1152 - (void) installPackage:(Package *)package;
1153 - (void) installPackages:(NSArray *)packages;
1154 - (void) removePackage:(Package *)package;
1155 - (void) beginUpdate;
1157 - (void) distUpgrade;
1159 - (void) updateData;
1161 - (void) addTrivialSource:(NSString *)href;
1162 - (void) showSettings;
1163 - (UIProgressHUD *) addProgressHUD;
1164 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1165 - (CYViewController *) pageForPackage:(NSString *)name;
1166 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1167 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1171 /* ProgressEvent Interface/Delegate {{{ */
1172 @interface CydiaProgressEvent : NSObject {
1173 _H<NSString> message_;
1175 _H<NSString> package_;
1179 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1180 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1182 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1184 - (NSString *) message;
1185 - (NSString *) type;
1186 - (NSString *) package;
1189 - (void) setPackage:(NSString *)package;
1191 - (NSString *) compound:(NSString *)value;
1192 - (NSString *) compoundMessage;
1193 - (NSString *) compoundTitle;
1197 @protocol ProgressDelegate
1198 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1199 - (void) setProgressPercent:(NSNumber *)percent;
1200 - (void) setProgressCancellable:(NSNumber *)cancellable;
1201 - (bool) isProgressCancelled;
1202 - (void) setTitle:(NSString *)title;
1205 /* Status Delegation {{{ */
1207 public pkgAcquireStatus
1210 _transient NSObject<ProgressDelegate> *delegate_;
1220 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1221 delegate_ = delegate;
1224 NSObject<ProgressDelegate> *getDelegate() const {
1228 virtual bool MediaChange(std::string media, std::string drive) {
1232 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1235 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1236 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1237 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:@"STATUS"]);
1238 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1241 virtual void Done(pkgAcquire::ItemDesc &item) {
1244 virtual void Fail(pkgAcquire::ItemDesc &item) {
1246 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1247 item.Owner->Status == pkgAcquire::Item::StatDone
1251 std::string &error(item.Owner->ErrorText);
1255 //NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1256 //NSArray *fields([description componentsSeparatedByString:@" "]);
1257 //NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1259 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:@"ERROR"]);
1260 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1263 virtual bool Pulse(pkgAcquire *Owner) {
1264 bool value = pkgAcquireStatus::Pulse(Owner);
1267 double(CurrentBytes + CurrentItems) /
1268 double(TotalBytes + TotalItems)
1271 [delegate_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:percent] waitUntilDone:YES];
1272 if (value && ![delegate_ isProgressCancelled])
1280 _finline bool WasCancelled() const {
1284 virtual void Start() {
1285 pkgAcquireStatus::Start();
1286 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1289 virtual void Stop() {
1290 pkgAcquireStatus::Stop();
1291 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1295 /* Database Interface {{{ */
1296 typedef std::map< unsigned long, _H<Source> > SourceMap;
1298 @interface Database : NSObject {
1304 pkgCacheFile cache_;
1305 pkgDepCache::Policy *policy_;
1306 pkgRecords *records_;
1307 pkgProblemResolver *resolver_;
1308 pkgAcquire *fetcher_;
1310 SPtr<pkgPackageManager> manager_;
1311 pkgSourceList *list_;
1313 SourceMap sourceMap_;
1314 NSMutableArray *sourceList_;
1316 CFMutableArrayRef packages_;
1318 _transient NSObject<DatabaseDelegate> *delegate_;
1319 _transient NSObject<ProgressDelegate> *progress_;
1327 std::map<const char *, _H<NSString> > sections_;
1330 + (Database *) sharedInstance;
1333 - (void) _readCydia:(NSNumber *)fd;
1334 - (void) _readStatus:(NSNumber *)fd;
1335 - (void) _readOutput:(NSNumber *)fd;
1339 - (Package *) packageWithName:(NSString *)name;
1341 - (pkgCacheFile &) cache;
1342 - (pkgDepCache::Policy *) policy;
1343 - (pkgRecords *) records;
1344 - (pkgProblemResolver *) resolver;
1345 - (pkgAcquire &) fetcher;
1346 - (pkgSourceList &) list;
1347 - (NSArray *) packages;
1348 - (NSArray *) sources;
1349 - (Source *) sourceWithKey:(NSString *)key;
1350 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1358 - (void) updateWithStatus:(Status &)status;
1360 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1362 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1363 - (NSObject<ProgressDelegate> *) progressDelegate;
1365 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1367 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1371 /* ProgressEvent Implementation {{{ */
1372 @implementation CydiaProgressEvent
1374 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1375 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1378 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1379 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1380 [event setPackage:package];
1384 + (NSArray *) _attributeKeys {
1385 return [NSArray arrayWithObjects:
1393 - (NSArray *) attributeKeys {
1394 return [[self class] _attributeKeys];
1397 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1398 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1401 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1402 if ((self = [super init]) != nil) {
1408 - (NSString *) message {
1412 - (NSString *) type {
1416 - (NSString *) package {
1420 - (NSString *) uri {
1424 - (void) setPackage:(NSString *)package {
1428 - (NSString *) compound:(NSString *)value {
1430 NSString *mode(nil); {
1431 NSString *type([self type]);
1432 if ([type isEqualToString:@"ERROR"])
1433 mode = UCLocalize("ERROR");
1434 else if ([type isEqualToString:@"WARNING"])
1435 mode = UCLocalize("WARNING");
1439 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1445 - (NSString *) compoundMessage {
1446 return [self compound:[self message]];
1449 - (NSString *) compoundTitle {
1452 if (package_ == nil)
1454 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1455 title = [package name];
1459 return [self compound:title];
1465 // Cytore Definitions {{{
1466 struct PackageValue :
1469 Cytore::Offset<PackageValue> next_;
1471 uint32_t index_ : 23;
1472 uint32_t subscribed_ : 1;
1489 Cytore::Offset<PackageValue> packages_[1 << 16];
1492 static Cytore::File<MetaValue> MetaFile_;
1494 // Cytore Helper Functions {{{
1495 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1496 SplitHash nhash = { hashlittle(name, length) };
1498 PackageValue *metadata;
1500 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1501 offset: if (offset->IsNull()) {
1502 *offset = MetaFile_.New<PackageValue>(length + 1);
1503 metadata = &MetaFile_.Get(*offset);
1505 if (metadata == NULL) {
1509 metadata = new PackageValue();
1510 memset(metadata, 0, sizeof(*metadata));
1513 memcpy(metadata->name_, name, length + 1);
1514 metadata->nhash_ = nhash.u16[1];
1516 metadata = &MetaFile_.Get(*offset);
1518 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1519 offset = &metadata->next_;
1527 static void PackageImport(const void *key, const void *value, void *context) {
1528 bool &fail(*reinterpret_cast<bool *>(context));
1531 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1532 NSLog(@"failed to import package %@", key);
1536 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1537 NSDictionary *package((NSDictionary *) value);
1539 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1540 if ([subscribed boolValue] && !metadata->subscribed_)
1541 metadata->subscribed_ = true;
1543 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1544 time_t time([date timeIntervalSince1970]);
1545 if (metadata->first_ > time || metadata->first_ == 0)
1546 metadata->first_ = time;
1549 NSDate *date([package objectForKey:@"LastSeen"]);
1550 NSString *version([package objectForKey:@"LastVersion"]);
1552 if (date != nil && version != nil) {
1553 time_t time([date timeIntervalSince1970]);
1554 if (metadata->last_ < time || metadata->last_ == 0)
1555 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1556 size_t length(strlen(buffer));
1557 uint16_t vhash(hashlittle(buffer, length));
1559 size_t capped(std::min<size_t>(8, length));
1560 char *latest(buffer + length - capped);
1562 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1563 metadata->vhash_ = vhash;
1565 metadata->last_ = time;
1571 /* Source Class {{{ */
1572 @interface Source : NSObject {
1573 CYString depiction_;
1574 CYString description_;
1580 CYString distribution_;
1585 NSString *authority_;
1587 CYString defaultIcon_;
1589 NSDictionary *record_;
1593 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1595 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1597 - (NSString *) depictionForPackage:(NSString *)package;
1598 - (NSString *) supportForPackage:(NSString *)package;
1600 - (NSDictionary *) record;
1604 - (NSString *) distribution;
1605 - (NSString *) type;
1607 - (NSString *) host;
1609 - (NSString *) name;
1610 - (NSString *) description;
1611 - (NSString *) label;
1612 - (NSString *) origin;
1613 - (NSString *) version;
1615 - (NSString *) defaultIcon;
1619 @implementation Source
1623 distribution_.clear();
1626 description_.clear();
1632 defaultIcon_.clear();
1634 if (record_ != nil) {
1644 if (authority_ != nil) {
1645 [authority_ release];
1651 // XXX: this is a very inefficient way to call these deconstructors
1656 + (NSArray *) _attributeKeys {
1657 return [NSArray arrayWithObjects:
1672 - (NSArray *) attributeKeys {
1673 return [[self class] _attributeKeys];
1676 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1677 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1680 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1683 trusted_ = index->IsTrusted();
1685 uri_.set(pool, index->GetURI());
1686 distribution_.set(pool, index->GetDist());
1687 type_.set(pool, index->GetType());
1689 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1690 if (dindex != NULL) {
1692 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1695 pkgTagFile tags(&fd);
1697 pkgTagSection section;
1704 {"default-icon", &defaultIcon_},
1705 {"depiction", &depiction_},
1706 {"description", &description_},
1708 {"origin", &origin_},
1709 {"support", &support_},
1710 {"version", &version_},
1713 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1714 const char *start, *end;
1716 if (section.Find(names[i].name_, start, end)) {
1717 CYString &value(*names[i].value_);
1718 value.set(pool, start, end - start);
1724 record_ = [Sources_ objectForKey:[self key]];
1726 record_ = [record_ retain];
1728 NSURL *url([NSURL URLWithString:uri_]);
1732 host_ = [[host_ lowercaseString] retain];
1737 authority_ = [url path];
1739 if (authority_ != nil)
1740 authority_ = [authority_ retain];
1743 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1744 if ((self = [super init]) != nil) {
1745 [self setMetaIndex:index inPool:pool];
1749 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1750 NSDictionary *lhr = [self record];
1751 NSDictionary *rhr = [source record];
1754 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1756 NSString *lhs = [self name];
1757 NSString *rhs = [source name];
1759 if ([lhs length] != 0 && [rhs length] != 0) {
1760 unichar lhc = [lhs characterAtIndex:0];
1761 unichar rhc = [rhs characterAtIndex:0];
1763 if (isalpha(lhc) && !isalpha(rhc))
1764 return NSOrderedAscending;
1765 else if (!isalpha(lhc) && isalpha(rhc))
1766 return NSOrderedDescending;
1769 return [lhs compare:rhs options:LaxCompareOptions_];
1772 - (NSString *) depictionForPackage:(NSString *)package {
1773 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1776 - (NSString *) supportForPackage:(NSString *)package {
1777 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1780 - (NSDictionary *) record {
1788 - (NSString *) uri {
1792 - (NSString *) distribution {
1793 return distribution_;
1796 - (NSString *) type {
1800 - (NSString *) key {
1801 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1804 - (NSString *) host {
1808 - (NSString *) name {
1809 return origin_.empty() ? authority_ : origin_;
1812 - (NSString *) description {
1813 return description_;
1816 - (NSString *) label {
1817 return label_.empty() ? authority_ : label_;
1820 - (NSString *) origin {
1824 - (NSString *) version {
1828 - (NSString *) defaultIcon {
1829 return defaultIcon_;
1834 /* CydiaOperation Class {{{ */
1835 @interface CydiaOperation : NSObject {
1836 NSString *operator_;
1840 - (NSString *) operator;
1841 - (NSString *) value;
1845 @implementation CydiaOperation
1848 [operator_ release];
1853 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1854 if ((self = [super init]) != nil) {
1855 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1856 value_ = [[NSString alloc] initWithUTF8String:value];
1860 + (NSArray *) _attributeKeys {
1861 return [NSArray arrayWithObjects:
1867 - (NSArray *) attributeKeys {
1868 return [[self class] _attributeKeys];
1871 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1872 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1875 - (NSString *) operator {
1879 - (NSString *) value {
1885 /* CydiaClause Class {{{ */
1886 @interface CydiaClause : NSObject {
1888 CydiaOperation *version_;
1891 - (NSString *) package;
1892 - (CydiaOperation *) version;
1896 @implementation CydiaClause
1904 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1905 if ((self = [super init]) != nil) {
1906 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1908 if (const char *version = dep.TargetVer())
1909 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1911 version_ = [[NSNull null] retain];
1915 + (NSArray *) _attributeKeys {
1916 return [NSArray arrayWithObjects:
1922 - (NSArray *) attributeKeys {
1923 return [[self class] _attributeKeys];
1926 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1927 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1930 - (NSString *) package {
1934 - (CydiaOperation *) version {
1940 /* CydiaRelation Class {{{ */
1941 @interface CydiaRelation : NSObject {
1942 NSString *relationship_;
1943 NSMutableArray *clauses_;
1946 - (NSString *) relationship;
1947 - (NSArray *) clauses;
1951 @implementation CydiaRelation
1954 [relationship_ release];
1959 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1960 if ((self = [super init]) != nil) {
1961 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1962 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1964 pkgCache::DepIterator start;
1965 pkgCache::DepIterator end;
1966 dep.GlobOr(start, end); // ++dep
1969 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1971 // yes, seriously. (wtf?)
1979 + (NSArray *) _attributeKeys {
1980 return [NSArray arrayWithObjects:
1986 - (NSArray *) attributeKeys {
1987 return [[self class] _attributeKeys];
1990 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1991 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1994 - (NSString *) relationship {
1995 return relationship_;
1998 - (NSArray *) clauses {
2002 - (void) addClause:(CydiaClause *)clause {
2003 [clauses_ addObject:clause];
2008 /* Package Class {{{ */
2009 struct ParsedPackage {
2014 CYString depiction_;
2024 @interface Package : NSObject {
2027 uint32_t essential_ : 1;
2028 uint32_t obsolete_ : 1;
2029 uint32_t ignored_ : 1;
2033 _transient Database *database_;
2035 pkgCache::VerIterator version_;
2036 pkgCache::PkgIterator iterator_;
2037 pkgCache::VerFileIterator file_;
2043 CYString installed_;
2045 const char *section_;
2046 _transient NSString *section$_;
2050 PackageValue *metadata_;
2051 ParsedPackage *parsed_;
2053 NSMutableArray *tags_;
2056 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2057 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2059 - (pkgCache::PkgIterator) iterator;
2062 - (NSString *) section;
2063 - (NSString *) simpleSection;
2065 - (NSString *) longSection;
2066 - (NSString *) shortSection;
2070 - (Address *) maintainer;
2072 - (NSString *) longDescription;
2073 - (NSString *) shortDescription;
2076 - (PackageValue *) metadata;
2079 - (bool) subscribed;
2080 - (bool) setSubscribed:(bool)subscribed;
2084 - (NSString *) latest;
2085 - (NSString *) installed;
2086 - (BOOL) uninstalled;
2089 - (BOOL) upgradableAndEssential:(BOOL)essential;
2092 - (BOOL) unfiltered;
2096 - (BOOL) halfConfigured;
2097 - (BOOL) halfInstalled;
2099 - (NSString *) mode;
2102 - (NSString *) name;
2104 - (NSString *) homepage;
2105 - (NSString *) depiction;
2106 - (Address *) author;
2108 - (NSString *) support;
2110 - (NSArray *) files;
2111 - (NSArray *) warnings;
2112 - (NSArray *) applications;
2114 - (Source *) source;
2116 - (BOOL) matches:(NSString *)text;
2118 - (bool) hasSupportingRole;
2119 - (BOOL) hasTag:(NSString *)tag;
2120 - (NSString *) primaryPurpose;
2121 - (NSArray *) purposes;
2122 - (bool) isCommercial;
2124 - (void) setIndex:(size_t)index;
2126 - (CYString &) cyname;
2128 - (uint32_t) compareBySection:(NSArray *)sections;
2133 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2134 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2135 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2136 - (bool) isVisibleInSection:(NSString *)section;
2137 - (bool) isVisibleInSource:(Source *)source;
2141 uint32_t PackageChangesRadix(Package *self, void *) {
2146 uint32_t timestamp : 30;
2147 uint32_t ignored : 1;
2148 uint32_t upgradable : 1;
2152 bool upgradable([self upgradableAndEssential:YES]);
2153 value.bits.upgradable = upgradable ? 1 : 0;
2156 value.bits.timestamp = 0;
2157 value.bits.ignored = [self ignored] ? 0 : 1;
2158 value.bits.upgradable = 1;
2160 value.bits.timestamp = [self seen] >> 2;
2161 value.bits.ignored = 0;
2162 value.bits.upgradable = 0;
2165 return _not(uint32_t) - value.key;
2168 uint32_t PackagePrefixRadix(Package *self, void *context) {
2169 size_t offset(reinterpret_cast<size_t>(context));
2170 CYString &name([self cyname]);
2172 size_t size(name.size());
2175 char *text(name.data());
2178 if (!isdigit(text[0]))
2182 while (size != digits && isdigit(text[digits]))
2190 if (offset == 0 && zeros != 0) {
2191 memset(data, '0', zeros);
2192 memcpy(data + zeros, text, 4 - zeros);
2194 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2195 if (size <= offset - zeros)
2198 text += offset - zeros;
2199 size -= offset - zeros;
2202 memcpy(data, text, 4);
2204 memcpy(data, text, size);
2205 memset(data + size, 0, 4 - size);
2208 for (size_t i(0); i != 4; ++i)
2209 if (isalpha(data[i]))
2217 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2219 /* XXX: ntohl may be more honest */
2220 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2223 CYString &(*PackageName)(Package *self, SEL sel);
2225 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2226 _profile(PackageNameCompare)
2227 CYString &lhi(PackageName(lhs, @selector(cyname)));
2228 CYString &rhi(PackageName(rhs, @selector(cyname)));
2229 CFStringRef lhn(lhi), rhn(rhi);
2232 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2233 else if (rhn == NULL)
2234 return NSOrderedDescending;
2236 _profile(PackageNameCompare$NumbersLast)
2237 if (!lhi.empty() && !rhi.empty()) {
2238 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2239 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2240 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2241 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2242 return lha ? NSOrderedAscending : NSOrderedDescending;
2246 CFIndex length = CFStringGetLength(lhn);
2248 _profile(PackageNameCompare$Compare)
2249 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2254 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2255 return PackageNameCompare(*lhs, *rhs, context);
2258 struct PackageNameOrdering :
2259 std::binary_function<Package *, Package *, bool>
2261 _finline bool operator ()(Package *lhs, Package *rhs) const {
2262 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2266 @implementation Package
2268 - (NSString *) description {
2269 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2273 if (parsed_ != NULL)
2282 + (NSString *) webScriptNameForSelector:(SEL)selector {
2284 else if (selector == @selector(clear))
2286 else if (selector == @selector(getField:))
2288 else if (selector == @selector(hasTag:))
2290 else if (selector == @selector(install))
2292 else if (selector == @selector(remove))
2298 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2299 return [self webScriptNameForSelector:selector] == nil;
2302 + (NSArray *) _attributeKeys {
2303 return [NSArray arrayWithObjects:
2321 @"shortDescription",
2332 - (NSArray *) attributeKeys {
2333 return [[self class] _attributeKeys];
2336 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2337 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2340 - (NSArray *) relations {
2341 @synchronized (database_) {
2342 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2343 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2344 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2348 - (NSString *) getField:(NSString *)name {
2349 @synchronized (database_) {
2350 if ([database_ era] != era_ || file_.end())
2353 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2355 const char *start, *end;
2356 if (!parser.Find([name UTF8String], start, end))
2357 return (NSString *) [NSNull null];
2359 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2363 if (parsed_ != NULL)
2365 @synchronized (database_) {
2366 if ([database_ era] != era_ || file_.end())
2369 ParsedPackage *parsed(new ParsedPackage);
2372 _profile(Package$parse)
2373 pkgRecords::Parser *parser;
2375 _profile(Package$parse$Lookup)
2376 parser = &[database_ records]->Lookup(file_);
2381 _profile(Package$parse$Find)
2386 {"icon", &parsed->icon_},
2387 {"depiction", &parsed->depiction_},
2388 {"homepage", &parsed->homepage_},
2389 {"website", &website},
2390 {"bugs", &parsed->bugs_},
2391 {"support", &parsed->support_},
2392 {"sponsor", &parsed->sponsor_},
2393 {"author", &parsed->author_},
2396 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2397 const char *start, *end;
2399 if (parser->Find(names[i].name_, start, end)) {
2400 CYString &value(*names[i].value_);
2401 _profile(Package$parse$Value)
2402 value.set(pool_, start, end - start);
2408 _profile(Package$parse$Tagline)
2409 const char *start, *end;
2410 if (parser->ShortDesc(start, end)) {
2411 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2414 while (stop != start && stop[-1] == '\r')
2416 parsed->tagline_.set(pool_, start, stop - start);
2420 _profile(Package$parse$Retain)
2421 if (parsed->homepage_.empty())
2422 parsed->homepage_ = website;
2423 if (parsed->homepage_ == parsed->depiction_)
2424 parsed->homepage_.clear();
2429 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2430 if ((self = [super init]) != nil) {
2431 _profile(Package$initWithVersion)
2434 database_ = database;
2435 era_ = [database era];
2439 pkgCache::PkgIterator iterator(version.ParentPkg());
2440 iterator_ = iterator;
2442 _profile(Package$initWithVersion$Version)
2443 if (!version_.end())
2444 file_ = version_.FileList();
2446 pkgCache &cache([database_ cache]);
2447 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2451 _profile(Package$initWithVersion$Cache)
2452 name_.set(NULL, iterator.Display());
2454 latest_.set(NULL, StripVersion_(version_.VerStr()));
2456 pkgCache::VerIterator current(iterator.CurrentVer());
2458 installed_.set(NULL, StripVersion_(current.VerStr()));
2461 _profile(Package$initWithVersion$Tags)
2462 pkgCache::TagIterator tag(iterator.TagList());
2464 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2466 const char *name(tag.Name());
2467 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2469 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2470 if (strcmp(name + 6, "enduser") == 0)
2472 else if (strcmp(name + 6, "hacker") == 0)
2474 else if (strcmp(name + 6, "developer") == 0)
2476 else if (strcmp(name + 6, "cydia") == 0)
2482 if (strncmp(name, "cydia::", 7) == 0) {
2483 if (strcmp(name + 7, "essential") == 0)
2485 else if (strcmp(name + 7, "obsolete") == 0)
2490 } while (!tag.end());
2494 _profile(Package$initWithVersion$Metadata)
2495 const char *mixed(iterator.Name());
2496 size_t size(strlen(mixed));
2497 char lower[size + 1];
2499 for (size_t i(0); i != size; ++i)
2500 lower[i] = mixed[i] | 0x20;
2503 PackageValue *metadata(PackageFind(lower, size));
2504 metadata_ = metadata;
2506 id_.set(NULL, metadata->name_, size);
2508 const char *latest(version_.VerStr());
2509 size_t length(strlen(latest));
2511 uint16_t vhash(hashlittle(latest, length));
2513 size_t capped(std::min<size_t>(8, length));
2514 latest = latest + length - capped;
2516 if (metadata->first_ == 0)
2517 metadata->first_ = now_;
2519 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2520 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2521 metadata->vhash_ = vhash;
2522 metadata->last_ = now_;
2523 } else if (metadata->last_ == 0)
2524 metadata->last_ = metadata->first_;
2527 _profile(Package$initWithVersion$Section)
2528 section_ = iterator.Section();
2531 _profile(Package$initWithVersion$Flags)
2532 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2533 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2538 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2539 pkgCache::VerIterator version;
2541 _profile(Package$packageWithIterator$GetCandidateVer)
2542 version = [database policy]->GetCandidateVer(iterator);
2550 _profile(Package$packageWithIterator$Allocate)
2551 package = [Package allocWithZone:zone];
2554 _profile(Package$packageWithIterator$Initialize)
2556 initWithVersion:version
2563 _profile(Package$packageWithIterator$Autorelease)
2564 package = [package autorelease];
2570 - (pkgCache::PkgIterator) iterator {
2574 - (NSString *) section {
2575 if (section$_ == nil) {
2576 if (section_ == NULL)
2579 _profile(Package$section$mappedSectionForPointer)
2580 section$_ = [database_ mappedSectionForPointer:section_];
2585 - (NSString *) simpleSection {
2586 if (NSString *section = [self section])
2587 return Simplify(section);
2592 - (NSString *) longSection {
2593 return LocalizeSection([self section]);
2596 - (NSString *) shortSection {
2597 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2600 - (NSString *) uri {
2603 pkgIndexFile *index;
2604 pkgCache::PkgFileIterator file(file_.File());
2605 if (![database_ list].FindIndex(file, index))
2607 return [NSString stringWithUTF8String:iterator_->Path];
2608 //return [NSString stringWithUTF8String:file.Site()];
2609 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2613 - (Address *) maintainer {
2614 @synchronized (database_) {
2615 if ([database_ era] != era_ || file_.end())
2618 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2619 const std::string &maintainer(parser->Maintainer());
2620 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2624 @synchronized (database_) {
2625 if ([database_ era] != era_ || version_.end())
2628 return version_->InstalledSize;
2631 - (NSString *) longDescription {
2632 @synchronized (database_) {
2633 if ([database_ era] != era_ || file_.end())
2636 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2637 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2639 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2640 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2641 if ([lines count] < 2)
2644 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2645 for (size_t i(1), e([lines count]); i != e; ++i) {
2646 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2647 [trimmed addObject:trim];
2650 return [trimmed componentsJoinedByString:@"\n"];
2653 - (NSString *) shortDescription {
2654 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2658 _profile(Package$index)
2659 CFStringRef name((CFStringRef) [self name]);
2660 if (CFStringGetLength(name) == 0)
2662 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2663 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2665 return toupper(character);
2669 - (PackageValue *) metadata {
2674 PackageValue *metadata([self metadata]);
2675 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2678 - (bool) subscribed {
2679 return [self metadata]->subscribed_;
2682 - (bool) setSubscribed:(bool)subscribed {
2683 PackageValue *metadata([self metadata]);
2684 if (metadata->subscribed_ == subscribed)
2686 metadata->subscribed_ = subscribed;
2694 - (NSString *) latest {
2698 - (NSString *) installed {
2702 - (BOOL) uninstalled {
2703 return installed_.empty();
2707 return !version_.end();
2710 - (BOOL) upgradableAndEssential:(BOOL)essential {
2711 _profile(Package$upgradableAndEssential)
2712 pkgCache::VerIterator current(iterator_.CurrentVer());
2714 return essential && essential_;
2716 return !version_.end() && version_ != current;
2720 - (BOOL) essential {
2725 return [database_ cache][iterator_].InstBroken();
2728 - (BOOL) unfiltered {
2729 _profile(Package$unfiltered$obsolete)
2730 if (_unlikely(obsolete_))
2734 _profile(Package$unfiltered$hasSupportingRole)
2735 if (_unlikely(![self hasSupportingRole]))
2743 if (![self unfiltered])
2748 _profile(Package$visible$section)
2749 section = [self section];
2752 _profile(Package$visible$isSectionVisible)
2753 if (!isSectionVisible(section))
2761 unsigned char current(iterator_->CurrentState);
2762 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2765 - (BOOL) halfConfigured {
2766 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2769 - (BOOL) halfInstalled {
2770 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2774 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2775 return state.Mode != pkgDepCache::ModeKeep;
2778 - (NSString *) mode {
2779 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2781 switch (state.Mode) {
2782 case pkgDepCache::ModeDelete:
2783 if ((state.iFlags & pkgDepCache::Purge) != 0)
2787 case pkgDepCache::ModeKeep:
2788 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2789 return @"REINSTALL";
2790 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2794 case pkgDepCache::ModeInstall:
2795 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2796 return @"REINSTALL";
2797 else*/ switch (state.Status) {
2799 return @"DOWNGRADE";
2805 return @"NEW_INSTALL";
2816 - (NSString *) name {
2817 return name_.empty() ? id_ : name_;
2820 - (UIImage *) icon {
2821 NSString *section = [self simpleSection];
2824 if (parsed_ != NULL)
2825 if (NSString *href = parsed_->icon_)
2826 if ([href hasPrefix:@"file:///"])
2827 // XXX: correct escaping
2828 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2829 if (icon == nil) if (section != nil)
2830 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2831 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2832 if ([dicon hasPrefix:@"file:///"])
2833 // XXX: correct escaping
2834 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2836 icon = [UIImage applicationImageNamed:@"unknown.png"];
2840 - (NSString *) homepage {
2841 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2844 - (NSString *) depiction {
2845 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2848 - (Address *) sponsor {
2849 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2852 - (Address *) author {
2853 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2856 - (NSString *) support {
2857 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2860 - (NSArray *) files {
2861 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2862 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2865 fin.open([path UTF8String]);
2870 while (std::getline(fin, line))
2871 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2876 - (NSArray *) warnings {
2877 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2878 const char *name(iterator_.Name());
2880 size_t length(strlen(name));
2881 if (length < 2) invalid:
2882 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2883 else for (size_t i(0); i != length; ++i)
2885 /* XXX: technically this is not allowed */
2886 (name[i] < 'A' || name[i] > 'Z') &&
2887 (name[i] < 'a' || name[i] > 'z') &&
2888 (name[i] < '0' || name[i] > '9') &&
2889 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2892 if (strcmp(name, "cydia") != 0) {
2895 bool _private = false;
2898 bool repository = [[self section] isEqualToString:@"Repositories"];
2900 if (NSArray *files = [self files])
2901 for (NSString *file in files)
2902 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2904 else if (!user && [file isEqualToString:@"/User"])
2906 else if (!_private && [file isEqualToString:@"/private"])
2908 else if (!stash && [file isEqualToString:@"/var/stash"])
2911 /* XXX: this is not sensitive enough. only some folders are valid. */
2912 if (cydia && !repository)
2913 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2915 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2917 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2919 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2922 return [warnings count] == 0 ? nil : warnings;
2925 - (NSArray *) applications {
2926 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2928 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2930 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2931 if (NSArray *files = [self files])
2932 for (NSString *file in files)
2933 if (application_r(file)) {
2934 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2935 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2936 if ([id isEqualToString:me])
2939 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2941 display = application_r[1];
2943 NSString *bundle([file stringByDeletingLastPathComponent]);
2944 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2945 if (icon == nil || [icon length] == 0)
2947 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2949 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2950 [applications addObject:application];
2952 [application addObject:id];
2953 [application addObject:display];
2954 [application addObject:url];
2957 return [applications count] == 0 ? nil : applications;
2960 - (Source *) source {
2961 if (source_ == nil) {
2962 @synchronized (database_) {
2963 if ([database_ era] != era_ || file_.end())
2964 source_ = (Source *) [NSNull null];
2966 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2970 return source_ == (Source *) [NSNull null] ? nil : source_;
2973 - (BOOL) matches:(NSString *)text {
2979 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2980 if (range.location != NSNotFound)
2983 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2984 if (range.location != NSNotFound)
2989 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2990 if (range.location != NSNotFound)
2996 - (bool) hasSupportingRole {
3001 if ([Role_ isEqualToString:@"User"])
3005 if ([Role_ isEqualToString:@"Hacker"])
3009 if ([Role_ isEqualToString:@"Developer"])
3014 - (BOOL) hasTag:(NSString *)tag {
3015 return tags_ == nil ? NO : [tags_ containsObject:tag];
3018 - (NSString *) primaryPurpose {
3019 for (NSString *tag in tags_)
3020 if ([tag hasPrefix:@"purpose::"])
3021 return [tag substringFromIndex:9];
3025 - (NSArray *) purposes {
3026 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3027 for (NSString *tag in tags_)
3028 if ([tag hasPrefix:@"purpose::"])
3029 [purposes addObject:[tag substringFromIndex:9]];
3030 return [purposes count] == 0 ? nil : purposes;
3033 - (bool) isCommercial {
3034 return [self hasTag:@"cydia::commercial"];
3037 - (void) setIndex:(size_t)index {
3038 if (metadata_->index_ != index)
3039 metadata_->index_ = index;
3042 - (CYString &) cyname {
3043 return name_.empty() ? id_ : name_;
3046 - (uint32_t) compareBySection:(NSArray *)sections {
3047 NSString *section([self section]);
3048 for (size_t i(0), e([sections count]); i != e; ++i) {
3049 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3053 return _not(uint32_t);
3057 @synchronized (database_) {
3058 pkgProblemResolver *resolver = [database_ resolver];
3059 resolver->Clear(iterator_);
3061 pkgCacheFile &cache([database_ cache]);
3062 cache->SetReInstall(iterator_, false);
3063 cache->MarkKeep(iterator_, false);
3067 @synchronized (database_) {
3068 pkgProblemResolver *resolver = [database_ resolver];
3069 resolver->Clear(iterator_);
3070 resolver->Protect(iterator_);
3072 pkgCacheFile &cache([database_ cache]);
3073 cache->SetReInstall(iterator_, false);
3074 cache->MarkInstall(iterator_, false);
3076 pkgDepCache::StateCache &state((*cache)[iterator_]);
3077 if (!state.Install())
3078 cache->SetReInstall(iterator_, true);
3082 @synchronized (database_) {
3083 pkgProblemResolver *resolver = [database_ resolver];
3084 resolver->Clear(iterator_);
3085 resolver->Remove(iterator_);
3086 resolver->Protect(iterator_);
3088 pkgCacheFile &cache([database_ cache]);
3089 cache->SetReInstall(iterator_, false);
3090 cache->MarkDelete(iterator_, true);
3093 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3094 _profile(Package$isUnfilteredAndSearchedForBy)
3097 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3098 value &= [self unfiltered];
3101 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3102 value &= [self matches:search];
3109 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3110 if ([search length] == 0)
3113 _profile(Package$isUnfilteredAndSelectedForBy)
3116 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3117 value &= [self unfiltered];
3120 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3121 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3128 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3129 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3132 - (bool) isVisibleInSection:(NSString *)name {
3133 NSString *section([self section]);
3137 section == nil && [name length] == 0 ||
3138 [name isEqualToString:section]
3139 ) && [self visible];
3142 - (bool) isVisibleInSource:(Source *)source {
3143 return [self source] == source && [self visible];
3148 /* Section Class {{{ */
3149 @interface Section : NSObject {
3154 NSString *localized_;
3157 - (NSComparisonResult) compareByLocalized:(Section *)section;
3158 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3159 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3160 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3161 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3162 - (NSString *) name;
3169 - (void) addToCount;
3171 - (void) setCount:(size_t)count;
3172 - (NSString *) localized;
3176 @implementation Section
3180 if (localized_ != nil)
3181 [localized_ release];
3185 - (NSComparisonResult) compareByLocalized:(Section *)section {
3186 NSString *lhs(localized_);
3187 NSString *rhs([section localized]);
3189 /*if ([lhs length] != 0 && [rhs length] != 0) {
3190 unichar lhc = [lhs characterAtIndex:0];
3191 unichar rhc = [rhs characterAtIndex:0];
3193 if (isalpha(lhc) && !isalpha(rhc))
3194 return NSOrderedAscending;
3195 else if (!isalpha(lhc) && isalpha(rhc))
3196 return NSOrderedDescending;
3199 return [lhs compare:rhs options:LaxCompareOptions_];
3202 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3203 if ((self = [self initWithName:name localize:NO]) != nil) {
3204 if (localized != nil)
3205 localized_ = [localized retain];
3209 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3210 return [self initWithName:name row:0 localize:localize];
3213 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3214 if ((self = [super init]) != nil) {
3215 name_ = [name retain];
3219 localized_ = [LocalizeSection(name_) retain];
3223 /* XXX: localize the index thingees */
3224 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3225 if ((self = [super init]) != nil) {
3226 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3232 - (NSString *) name {
3252 - (void) addToCount {
3256 - (void) setCount:(size_t)count {
3260 - (NSString *) localized {
3267 static NSString *Colon_;
3268 static NSString *Elision_;
3269 static NSString *Error_;
3270 static NSString *Warning_;
3272 /* Database Implementation {{{ */
3273 @implementation Database
3275 + (Database *) sharedInstance {
3276 static Database *instance;
3277 if (instance == nil)
3278 instance = [[Database alloc] init];
3286 - (void) releasePackages {
3287 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3288 CFArrayRemoveAllValues(packages_);
3292 // XXX: actually implement this thing
3294 [sourceList_ release];
3295 [self releasePackages];
3296 apr_pool_destroy(pool_);
3297 NSRecycleZone(zone_);
3301 - (void) _readCydia:(NSNumber *)fd { _pooled
3302 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3303 std::istream is(&ib);
3306 static Pcre finish_r("^finish:([^:]*)$");
3308 while (std::getline(is, line)) {
3309 const char *data(line.c_str());
3310 size_t size = line.size();
3311 lprintf("C:%s\n", data);
3313 if (finish_r(data, size)) {
3314 NSString *finish = finish_r[1];
3315 int index = [Finishes_ indexOfObject:finish];
3316 if (index != INT_MAX && index > Finish_)
3324 - (void) _readStatus:(NSNumber *)fd { _pooled
3325 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3326 std::istream is(&ib);
3329 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3330 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3332 while (std::getline(is, line)) {
3333 const char *data(line.c_str());
3334 size_t size(line.size());
3335 lprintf("S:%s\n", data);
3337 if (conffile_r(data, size))
3338 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3339 else if (strncmp(data, "status: ", 8) == 0) {
3340 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:@"STATUS"]);
3341 [progress_ performSelectorOnMainThread:@selector(addProgressEvent) withObject:event waitUntilDone:YES];
3342 } else if (pmstatus_r(data, size)) {
3343 std::string type([pmstatus_r[1] UTF8String]);
3344 NSString *package = pmstatus_r[2];
3346 float percent([pmstatus_r[3] floatValue]);
3347 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3349 NSString *string = pmstatus_r[4];
3351 if (type == "pmerror") {
3352 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"ERROR" forPackage:package]);
3353 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3354 } else if (type == "pmstatus") {
3355 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"STATUS" forPackage:package]);
3356 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3357 } else if (type == "pmconffile")
3358 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3360 lprintf("E:unknown pmstatus\n");
3362 lprintf("E:unknown status\n");
3368 - (void) _readOutput:(NSNumber *)fd { _pooled
3369 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3370 std::istream is(&ib);
3373 while (std::getline(is, line)) {
3374 lprintf("O:%s\n", line.c_str());
3376 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:@"INFORMATION"]);
3377 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3387 - (Package *) packageWithName:(NSString *)name {
3388 @synchronized (self) {
3389 if (static_cast<pkgDepCache *>(cache_) == NULL)
3391 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3392 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3396 if ((self = [super init]) != nil) {
3403 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3404 apr_pool_create(&pool_, NULL);
3406 size_t capacity(MetaFile_->active_);
3412 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3413 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3417 _assert(pipe(fds) != -1);
3420 _config->Set("APT::Keep-Fds::", cydiafd_);
3421 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3424 detachNewThreadSelector:@selector(_readCydia:)
3426 withObject:[NSNumber numberWithInt:fds[0]]
3429 _assert(pipe(fds) != -1);
3433 detachNewThreadSelector:@selector(_readStatus:)
3435 withObject:[NSNumber numberWithInt:fds[0]]
3438 _assert(pipe(fds) != -1);
3439 _assert(dup2(fds[0], 0) != -1);
3440 _assert(close(fds[0]) != -1);
3442 input_ = fdopen(fds[1], "a");
3444 _assert(pipe(fds) != -1);
3445 _assert(dup2(fds[1], 1) != -1);
3446 _assert(close(fds[1]) != -1);
3449 detachNewThreadSelector:@selector(_readOutput:)
3451 withObject:[NSNumber numberWithInt:fds[0]]
3456 - (pkgCacheFile &) cache {
3460 - (pkgDepCache::Policy *) policy {
3464 - (pkgRecords *) records {
3468 - (pkgProblemResolver *) resolver {
3472 - (pkgAcquire &) fetcher {
3476 - (pkgSourceList &) list {
3480 - (NSArray *) packages {
3481 return (NSArray *) packages_;
3484 - (NSArray *) sources {
3488 - (Source *) sourceWithKey:(NSString *)key {
3489 for (Source *source in [self sources]) {
3490 if ([[source key] isEqualToString:key])
3495 - (bool) popErrorWithTitle:(NSString *)title {
3498 while (!_error->empty()) {
3500 bool warning(!_error->PopMessage(error));
3505 size_t size(error.size());
3506 if (size == 0 || error[size - 1] != '\n')
3508 error.resize(size - 1);
3511 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3513 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3519 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3520 return [self popErrorWithTitle:title] || !success;
3523 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3524 @synchronized (self) {
3527 [self releasePackages];
3530 [sourceList_ removeAllObjects];
3550 apr_pool_clear(pool_);
3552 NSRecycleZone(zone_);
3553 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3555 int chk(creat("/tmp/cydia.chk", 0644));
3559 if (invocation != nil)
3560 [invocation invoke];
3562 NSString *title(UCLocalize("DATABASE"));
3565 OpProgress progress;
3566 while (!cache_.Open(progress, true)) { pop:
3568 bool warning(!_error->PopMessage(error));
3569 lprintf("cache_.Open():[%s]\n", error.c_str());
3571 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3572 [delegate_ repairWithSelector:@selector(configure)];
3573 else if (error == "The package lists or status file could not be parsed or opened.")
3574 [delegate_ repairWithSelector:@selector(update)];
3575 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3576 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3577 // else if (error == "The list of sources could not be read.")
3579 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3589 unlink("/tmp/cydia.chk");
3591 now_ = [[NSDate date] timeIntervalSince1970];
3593 policy_ = new pkgDepCache::Policy();
3594 records_ = new pkgRecords(cache_);
3595 resolver_ = new pkgProblemResolver(cache_);
3596 fetcher_ = new pkgAcquire(&status_);
3599 list_ = new pkgSourceList();
3600 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3603 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3604 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:@"ERROR"] forTask:title];
3608 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3611 if (cache_->BrokenCount() != 0) {
3612 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3615 if (cache_->BrokenCount() != 0) {
3616 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:@"ERROR"] forTask:title];
3620 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3624 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3625 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3626 [sourceList_ addObject:object];
3628 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3629 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3630 // XXX: this could be more intelligent
3631 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3632 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3634 sourceMap_[cached->ID] = object;
3639 /*std::vector<Package *> packages;
3640 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3641 [packages_ release];
3646 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3647 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3648 //packages.push_back(package);
3649 CFArrayAppendValue(packages_, [package retain]);
3653 /*if (packages.empty())
3654 packages_ = [[NSArray alloc] init];
3656 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3659 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3660 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3661 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3669 /*if (!packages.empty())
3670 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3671 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3673 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3675 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3677 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3681 size_t count(CFArrayGetCount(packages_));
3682 MetaFile_->active_ = count;
3684 for (size_t index(0); index != count; ++index)
3685 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3689 } } CYPoolEnd() _trace(); }
3692 @synchronized (self) {
3694 resolver_ = new pkgProblemResolver(cache_);
3696 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3697 if (!cache_[iterator].Keep())
3698 cache_->MarkKeep(iterator, false);
3699 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3700 cache_->SetReInstall(iterator, false);
3703 - (void) configure {
3704 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3706 system([dpkg UTF8String]);
3711 // XXX: I don't remember this condition
3716 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3718 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3720 if ([self popErrorWithTitle:title])
3724 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3727 public pkgArchiveCleaner
3730 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3735 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3742 fetcher_->Shutdown();
3744 pkgRecords records(cache_);
3746 lock_ = new FileFd();
3747 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3749 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3751 if ([self popErrorWithTitle:title])
3755 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3758 manager_ = (_system->CreatePM(cache_));
3759 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3766 bool substrate(RestartSubstrate_);
3767 RestartSubstrate_ = false;
3769 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3771 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3773 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3775 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3776 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3779 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3781 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3783 [self popErrorWithTitle:title];
3787 bool failed = false;
3788 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3789 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3791 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3797 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3805 RestartSubstrate_ = true;
3808 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3810 if (_error->PendingError()) {
3815 if (result == pkgPackageManager::Failed) {
3820 if (result != pkgPackageManager::Completed) {
3825 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3827 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3829 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3830 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3833 if (![before isEqualToArray:after])
3838 NSString *title(UCLocalize("UPGRADE"));
3839 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3845 [self updateWithStatus:status_];
3848 - (void) updateWithStatus:(Status &)status {
3849 NSString *title(UCLocalize("REFRESHING_DATA"));
3852 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3856 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3857 if ([self popErrorWithTitle:title])
3860 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3862 bool success(ListUpdate(status, list, PulseInterval_));
3863 if (status.WasCancelled())
3866 [self popErrorWithTitle:title forOperation:success];
3868 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3870 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3874 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3875 delegate_ = delegate;
3878 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3879 progress_ = delegate;
3880 status_.setDelegate(delegate);
3883 - (NSObject<ProgressDelegate> *) progressDelegate {
3887 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3888 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3889 return i == sourceMap_.end() ? nil : i->second;
3892 - (NSString *) mappedSectionForPointer:(const char *)section {
3893 _H<NSString> *mapped;
3895 _profile(Database$mappedSectionForPointer$Cache)
3896 mapped = §ions_[section];
3899 if (*mapped == NULL) {
3900 size_t length(strlen(section));
3901 char spaced[length + 1];
3903 _profile(Database$mappedSectionForPointer$Replace)
3904 for (size_t index(0); index != length; ++index)
3905 spaced[index] = section[index] == '_' ? ' ' : section[index];
3906 spaced[length] = '\0';
3911 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3912 string = [NSString stringWithUTF8String:spaced];
3915 _profile(Database$mappedSectionForPointer$Map)
3916 string = [SectionMap_ objectForKey:string] ?: string;
3926 /* Web Scripting {{{ */
3927 @interface CydiaObject : NSObject {
3929 _transient id delegate_;
3932 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3936 @implementation CydiaObject
3939 [indirect_ release];
3943 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3944 if ((self = [super init]) != nil) {
3945 indirect_ = [indirect retain];
3949 - (void) setDelegate:(id)delegate {
3950 delegate_ = delegate;
3953 + (NSArray *) _attributeKeys {
3954 return [NSArray arrayWithObjects:
3967 - (NSArray *) attributeKeys {
3968 return [[self class] _attributeKeys];
3971 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3972 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3975 - (NSString *) device {
3976 return [[UIDevice currentDevice] uniqueIdentifier];
3979 - (NSString *) firmware {
3980 return [[UIDevice currentDevice] systemVersion];
3983 - (NSString *) hostname {
3984 return [[UIDevice currentDevice] name];
3987 - (NSString *) idiom {
3988 UIDevice *device([UIDevice currentDevice]);
3989 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
3992 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
3993 if (idiom == UIUserInterfaceIdiomPhone)
3995 else if (idiom == UIUserInterfaceIdiomPad)
4001 - (NSString *) plmn {
4002 return (id) PLMN_ ?: [NSNull null];
4005 - (NSString *) ecid {
4006 return (id) ChipID_ ?: [NSNull null];
4009 - (NSString *) serial {
4010 return SerialNumber_;
4013 - (NSString *) role {
4014 return (id) Role_ ?: [NSNull null];
4017 - (NSString *) model {
4018 return [NSString stringWithUTF8String:Machine_];
4021 + (NSString *) webScriptNameForSelector:(SEL)selector {
4023 else if (selector == @selector(addTrivialSource:))
4024 return @"addTrivialSource";
4025 else if (selector == @selector(close))
4027 else if (selector == @selector(du:))
4029 else if (selector == @selector(stringWithFormat:arguments:))
4031 else if (selector == @selector(getAllSources))
4032 return @"getAllSourcs";
4033 else if (selector == @selector(getKernelNumber:))
4034 return @"getKernelNumber";
4035 else if (selector == @selector(getKernelString:))
4036 return @"getKernelString";
4037 else if (selector == @selector(getInstalledPackages))
4038 return @"getInstalledPackages";
4039 else if (selector == @selector(getPackageById:))
4040 return @"getPackageById";
4041 else if (selector == @selector(installPackages:))
4042 return @"installPackages";
4043 else if (selector == @selector(localizedStringForKey:value:table:))
4045 else if (selector == @selector(refreshSources))
4046 return @"refreshSources";
4047 else if (selector == @selector(removeButton))
4048 return @"removeButton";
4049 else if (selector == @selector(scrollToBottom:))
4050 return @"scrollToBottom";
4051 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4052 return @"setButtonImage";
4053 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4054 return @"setButtonTitle";
4055 else if (selector == @selector(setPopupHook:))
4056 return @"setPopupHook";
4057 else if (selector == @selector(setToken:))
4059 else if (selector == @selector(setViewportWidth:))
4060 return @"setViewportWidth";
4061 else if (selector == @selector(statfs:))
4063 else if (selector == @selector(supports:))
4069 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4070 return [self webScriptNameForSelector:selector] == nil;
4073 - (BOOL) supports:(NSString *)feature {
4074 return [feature isEqualToString:@"window.open"];
4077 - (NSNumber *) getKernelNumber:(NSString *)name {
4078 const char *string([name UTF8String]);
4081 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4082 return (id) [NSNull null];
4084 if (size != sizeof(int))
4085 return (id) [NSNull null];
4088 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4089 return (id) [NSNull null];
4091 return [NSNumber numberWithInt:value];
4094 - (NSString *) getKernelString:(NSString *)name {
4095 const char *string([name UTF8String]);
4098 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4099 return (id) [NSNull null];
4101 char value[size + 1];
4102 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4103 return (id) [NSNull null];
4105 // XXX: just in case you request something ludicrous
4108 return [NSString stringWithCString:value];
4111 - (void) addTrivialSource:(NSString *)href {
4112 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4115 - (void) refreshSources {
4116 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4119 - (NSArray *) getAllSources {
4120 return [[Database sharedInstance] sources];
4123 - (NSArray *) getInstalledPackages {
4124 Database *database([Database sharedInstance]);
4125 @synchronized (database) {
4126 NSArray *packages([database packages]);
4127 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4128 for (Package *package in packages)
4129 if (![package uninstalled])
4130 [installed addObject:package];
4134 - (Package *) getPackageById:(NSString *)id {
4135 Package *package([[Database sharedInstance] packageWithName:id]);
4140 - (NSArray *) statfs:(NSString *)path {
4143 if (path == nil || statfs([path UTF8String], &stat) == -1)
4146 return [NSArray arrayWithObjects:
4147 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4148 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4149 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4153 - (NSNumber *) du:(NSString *)path {
4154 NSNumber *value(nil);
4157 _assert(pipe(fds) != -1);
4159 pid_t pid(ExecFork());
4161 _assert(dup2(fds[1], 1) != -1);
4162 _assert(close(fds[0]) != -1);
4163 _assert(close(fds[1]) != -1);
4164 /* XXX: this should probably not use du */
4165 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4170 _assert(close(fds[1]) != -1);
4172 if (FILE *du = fdopen(fds[0], "r")) {
4174 while (fgets(line, sizeof(line), du) != NULL) {
4175 size_t length(strlen(line));
4176 while (length != 0 && line[length - 1] == '\n')
4177 line[--length] = '\0';
4178 if (char *tab = strchr(line, '\t')) {
4180 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4185 } else _assert(close(fds[0]));
4189 if (waitpid(pid, &status, 0) == -1)
4192 else _assert(false);
4198 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4201 - (void) installPackages:(NSArray *)packages {
4202 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4205 - (void) removeButton {
4206 [indirect_ removeButton];
4209 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4210 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4213 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4214 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4217 - (void) _setToken:(NSString *)token {
4220 Token_ = [token retain];
4222 [Metadata_ setObject:Token_ forKey:@"Token"];
4226 - (void) setToken:(NSString *)token {
4227 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4230 - (void) setPopupHook:(id)function {
4231 [indirect_ setPopupHook:function];
4234 - (void) scrollToBottom:(NSNumber *)animated {
4235 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4238 - (void) setViewportWidth:(float)width {
4239 [indirect_ setViewportWidthOnMainThread:width];
4242 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4243 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4244 unsigned count([arguments count]);
4246 for (unsigned i(0); i != count; ++i)
4247 values[i] = [arguments objectAtIndex:i];
4248 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4251 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4252 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4254 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4256 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4262 /* @ Loading... Indicator {{{ */
4263 @interface CYLoadingIndicator : UIView {
4264 _H<UIActivityIndicatorView> spinner_;
4266 _H<UIView> container_;
4269 @property (readonly, nonatomic) UILabel *label;
4270 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4274 @implementation CYLoadingIndicator
4276 - (id) initWithFrame:(CGRect)frame {
4277 if ((self = [super initWithFrame:frame]) != nil) {
4278 container_ = [[[UIView alloc] init] autorelease];
4279 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4281 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4282 [spinner_ startAnimating];
4283 [container_ addSubview:spinner_];
4285 label_ = [[[UILabel alloc] init] autorelease];
4286 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4287 [label_ setBackgroundColor:[UIColor clearColor]];
4288 [label_ setTextColor:[UIColor blackColor]];
4289 [label_ setShadowColor:[UIColor whiteColor]];
4290 [label_ setShadowOffset:CGSizeMake(0, 1)];
4291 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4292 [container_ addSubview:label_];
4294 CGSize viewsize = frame.size;
4295 CGSize spinnersize = [spinner_ bounds].size;
4296 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4297 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4299 CGRect containrect = {
4300 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4301 CGSizeMake(bothwidth, spinnersize.height)
4304 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4312 [container_ setFrame:containrect];
4313 [spinner_ setFrame:spinrect];
4314 [label_ setFrame:textrect];
4315 [self addSubview:container_];
4319 - (UILabel *) label {
4323 - (UIActivityIndicatorView *) activityIndicatorView {
4329 /* Emulated Loading Controller {{{ */
4330 @interface CYEmulatedLoadingController : CYViewController {
4331 _transient Database *database_;
4332 _H<CYLoadingIndicator> indicator_;
4333 _H<UITabBar> tabbar_;
4334 _H<UINavigationBar> navbar_;
4339 @implementation CYEmulatedLoadingController
4341 - (id) initWithDatabase:(Database *)database {
4342 if ((self = [super init]) != nil) {
4343 database_ = database;
4348 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4349 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4351 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4352 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4353 [[self view] addSubview:indicator_];
4355 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4356 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4357 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4358 [[self view] addSubview:tabbar_];
4360 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4361 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4362 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4363 [[self view] addSubview:navbar_];
4366 - (void) releaseSubviews {
4375 /* Cydia Browser Controller {{{ */
4376 @interface CYBrowserController : BrowserController {
4377 CydiaObject *cydia_;
4382 @implementation CYBrowserController
4389 - (NSURL *) navigationURL {
4390 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4393 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4396 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4397 [super webView:view didClearWindowObject:window forFrame:frame];
4399 WebDataSource *source([frame dataSource]);
4400 NSURLResponse *response([source response]);
4402 NSURL *url([response URL]);
4403 NSString *scheme([url scheme]);
4404 NSString *host([url host]);
4406 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4407 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4408 NSDictionary *headers([http allHeaderFields]);
4409 [self setHeaders:headers forHost:host];
4413 [host isEqualToString:@"cydia.saurik.com"] ||
4414 [host hasSuffix:@".cydia.saurik.com"] ||
4415 [scheme isEqualToString:@"file"]
4417 [window setValue:cydia_ forKey:@"cydia"];
4420 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4421 if (System_ != NULL)
4422 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4423 if (Machine_ != NULL)
4424 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4426 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4428 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4431 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4432 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4433 [self _setMoreHeaders:copy];
4437 - (void) setDelegate:(id)delegate {
4438 [super setDelegate:delegate];
4439 [cydia_ setDelegate:delegate];
4443 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4444 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4446 WebView *webview([[webview_ _documentView] webView]);
4448 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4450 NSString *application = package == nil ? @"Cydia" : [NSString
4451 stringWithFormat:@"Cydia/%@",
4456 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4458 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4459 if (Product_ != nil)
4460 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4462 [webview setApplicationNameForUserAgent:application];
4470 @interface NSObject (CydiaScript)
4471 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4474 @implementation NSObject (CydiaScript)
4476 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4482 @implementation NSArray (CydiaScript)
4484 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4485 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4486 for (size_t i(0), e([self count]); i != e; ++i)
4487 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4493 @implementation NSDictionary (CydiaScript)
4495 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4496 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4498 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4505 /* Confirmation Controller {{{ */
4506 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4507 if (!iterator.end())
4508 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4509 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4511 pkgCache::PkgIterator package(dep.TargetPkg());
4514 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4521 @protocol ConfirmationControllerDelegate
4522 - (void) cancelAndClear:(bool)clear;
4523 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4527 @interface ConfirmationController : CYBrowserController {
4528 _transient Database *database_;
4530 UIAlertView *essential_;
4532 NSDictionary *changes_;
4533 NSMutableArray *issues_;
4534 NSDictionary *sizes_;
4539 - (id) initWithDatabase:(Database *)database;
4543 @implementation ConfirmationController
4550 if (essential_ != nil)
4551 [essential_ release];
4558 RestartSubstrate_ = true;
4559 [delegate_ confirmWithNavigationController:[self navigationController]];
4562 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4563 NSString *context([alert context]);
4565 if ([context isEqualToString:@"remove"]) {
4566 if (button == [alert cancelButtonIndex])
4567 [self dismissModalViewControllerAnimated:YES];
4568 else if (button == [alert firstOtherButtonIndex]) {
4572 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4573 } else if ([context isEqualToString:@"unable"]) {
4574 [self dismissModalViewControllerAnimated:YES];
4575 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4577 [super alertView:alert clickedButtonAtIndex:button];
4581 - (void) _doContinue {
4582 [self dismissModalViewControllerAnimated:YES];
4583 [delegate_ cancelAndClear:NO];
4586 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4587 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4591 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4592 [super webView:view didClearWindowObject:window forFrame:frame];
4594 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4595 changes_, @"changes",
4599 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4602 - (id) initWithDatabase:(Database *)database {
4603 if ((self = [super init]) != nil) {
4604 database_ = database;
4606 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4607 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4608 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4609 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4610 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4614 pkgCacheFile &cache([database_ cache]);
4615 NSArray *packages([database_ packages]);
4616 pkgDepCache::Policy *policy([database_ policy]);
4618 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4620 for (Package *package in packages) {
4621 pkgCache::PkgIterator iterator([package iterator]);
4622 NSString *name([package id]);
4624 if ([package broken]) {
4625 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4627 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4629 reasons, @"reasons",
4632 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4636 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4637 pkgCache::DepIterator start;
4638 pkgCache::DepIterator end;
4639 dep.GlobOr(start, end); // ++dep
4641 if (!cache->IsImportantDep(end))
4643 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4646 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4648 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4649 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4650 clauses, @"clauses",
4654 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4656 pkgCache::PkgIterator target(start.TargetPkg());
4657 if (target->ProvidesList != 0)
4658 reason = @"missing";
4660 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4662 reason = @"installed";
4663 installed = [NSString stringWithUTF8String:ver.VerStr()];
4664 } else if (!cache[target].CandidateVerIter(cache).end())
4665 reason = @"uninstalled";
4666 else if (target->ProvidesList == 0)
4667 reason = @"uninstallable";
4669 reason = @"virtual";
4672 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4673 [NSString stringWithUTF8String:start.CompType()], @"operator",
4674 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4677 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4678 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4679 version, @"version",
4681 installed, @"installed",
4684 // yes, seriously. (wtf?)
4692 pkgDepCache::StateCache &state(cache[iterator]);
4694 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4696 if (state.NewInstall())
4697 [installs addObject:name];
4698 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4699 [reinstalls addObject:name];
4700 else if (state.Upgrade())
4701 [upgrades addObject:name];
4702 else if (state.Downgrade())
4703 [downgrades addObject:name];
4704 else if (!state.Delete())
4706 else if (special_r(name))
4707 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4708 [NSNull null], @"package",
4709 [NSArray arrayWithObjects:
4710 [NSDictionary dictionaryWithObjectsAndKeys:
4711 @"Conflicts", @"relationship",
4712 [NSArray arrayWithObjects:
4713 [NSDictionary dictionaryWithObjectsAndKeys:
4715 [NSNull null], @"version",
4716 @"installed", @"reason",
4723 if ([package essential])
4725 [removes addObject:name];
4728 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4729 substrate_ |= DepSubstrate(iterator.CurrentVer());
4734 else if (Advanced_) {
4735 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4737 essential_ = [[UIAlertView alloc]
4738 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4739 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4741 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4743 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4747 [essential_ setContext:@"remove"];
4749 essential_ = [[UIAlertView alloc]
4750 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4751 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4753 cancelButtonTitle:UCLocalize("OKAY")
4754 otherButtonTitles:nil
4757 [essential_ setContext:@"unable"];
4760 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4761 installs, @"installs",
4762 reinstalls, @"reinstalls",
4763 upgrades, @"upgrades",
4764 downgrades, @"downgrades",
4765 removes, @"removes",
4768 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4769 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4770 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4773 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4775 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4776 initWithTitle:UCLocalize("CANCEL")
4777 style:UIBarButtonItemStylePlain
4779 action:@selector(cancelButtonClicked)
4785 - (void) applyRightButton {
4786 if ([issues_ count] == 0 && ![self isLoading])
4787 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4788 initWithTitle:UCLocalize("CONFIRM")
4789 style:UIBarButtonItemStyleDone
4791 action:@selector(confirmButtonClicked)
4794 [[self navigationItem] setRightBarButtonItem:nil];
4798 - (void) cancelButtonClicked {
4799 [self dismissModalViewControllerAnimated:YES];
4800 [delegate_ cancelAndClear:YES];
4804 - (void) confirmButtonClicked {
4805 if (essential_ != nil)
4815 /* Progress Data {{{ */
4816 @interface CydiaProgressData : NSObject {
4817 _transient id delegate_;
4822 _H<NSMutableArray> events_;
4823 _H<NSString> title_;
4825 _H<NSString> status_;
4826 _H<NSString> finish_;
4831 @implementation CydiaProgressData
4833 + (NSArray *) _attributeKeys {
4834 return [NSArray arrayWithObjects:
4843 - (NSArray *) attributeKeys {
4844 return [[self class] _attributeKeys];
4847 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4848 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4852 if ((self = [super init]) != nil) {
4853 events_ = [NSMutableArray arrayWithCapacity:32];
4857 - (void) setDelegate:(id)delegate {
4858 delegate_ = delegate;
4861 - (void) setProgress:(float)value {
4865 - (NSNumber *) progress {
4866 return [NSNumber numberWithFloat:progress_];
4869 - (NSArray *) events {
4873 - (void) removeAllEvents {
4874 [events_ removeAllObjects];
4877 - (void) addEvent:(CydiaProgressEvent *)event {
4878 [events_ addObject:event];
4881 - (void) setTitle:(NSString *)text {
4885 - (NSString *) title {
4889 - (void) setFinish:(NSString *)text {
4893 - (NSString *) finish {
4894 return (id) finish_ ?: [NSNull null];
4897 - (void) setRunning:(bool)running {
4901 - (NSNumber *) running {
4902 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4907 /* Progress Controller {{{ */
4908 @interface ProgressController : CYBrowserController <
4911 _transient Database *database_;
4912 _H<CydiaProgressData> progress_;
4916 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4918 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4920 - (void) setTitle:(NSString *)title;
4921 - (void) setCancellable:(bool)cancellable;
4925 @implementation ProgressController
4928 [database_ setProgressDelegate:nil];
4929 [progress_ setDelegate:nil];
4933 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4934 if ((self = [super init]) != nil) {
4935 database_ = database;
4936 delegate_ = delegate;
4938 [database_ setProgressDelegate:self];
4940 progress_ = [[[CydiaProgressData alloc] init] autorelease];
4941 [progress_ setDelegate:self];
4945 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4946 [super webView:view didClearWindowObject:window forFrame:frame];
4947 [window setValue:progress_ forKey:@"cydiaProgress"];
4950 - (void) updateProgress {
4951 [self dispatchEvent:@"CydiaProgressUpdate"];
4954 - (void) updateCancel {
4955 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
4956 initWithTitle:UCLocalize("CANCEL")
4957 style:UIBarButtonItemStylePlain
4959 action:@selector(cancel)
4960 ] autorelease] : nil)];
4963 - (void) viewWillAppear:(BOOL)animated {
4964 if (![self hasLoaded]) {
4965 [scroller_ setBackgroundColor:[UIColor blackColor]];
4966 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/progress/", UI_]]];
4969 [super viewDidAppear:animated];
4971 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4973 [[self navigationItem] setHidesBackButton:YES];
4975 [self updateCancel];
4979 UpdateExternalStatus(0);
4986 [delegate_ terminateWithSuccess];
4987 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4988 [delegate_ suspendWithAnimation:YES];
4990 [delegate_ suspend];*/
5002 system("/usr/bin/sbreload");
5008 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5009 SBReboot(SBSSpringBoardServerPort());
5011 reboot2(RB_AUTOBOOT);
5018 - (void) setTitle:(NSString *)title {
5019 [progress_ setTitle:title];
5020 [self updateProgress];
5023 - (UIBarButtonItem *) rightButton {
5024 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5025 initWithTitle:UCLocalize("CLOSE")
5026 style:UIBarButtonItemStylePlain
5028 action:@selector(close)
5032 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5033 UpdateExternalStatus(1);
5035 [progress_ setRunning:true];
5036 [self setTitle:title];
5037 // implicit updateProgress
5039 SHA1SumValue notifyconf; {
5041 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5044 MMap mmap(file, MMap::ReadOnly);
5046 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5047 notifyconf = sha1.Result();
5051 SHA1SumValue springlist; {
5053 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5056 MMap mmap(file, MMap::ReadOnly);
5058 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5059 springlist = sha1.Result();
5063 if (invocation != nil) {
5064 [invocation yieldToSelector:@selector(invoke)];
5065 [self setTitle:@"COMPLETE"];
5070 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5073 MMap mmap(file, MMap::ReadOnly);
5075 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5076 if (!(notifyconf == sha1.Result()))
5083 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5086 MMap mmap(file, MMap::ReadOnly);
5088 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5089 if (!(springlist == sha1.Result()))
5095 if (RestartSubstrate_)
5099 RestartSubstrate_ = false;
5102 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5103 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5104 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5105 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5106 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5110 system("su -c /usr/bin/uicache mobile");
5113 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5115 [progress_ setRunning:false];
5116 [self updateProgress];
5118 [self applyRightButton];
5121 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5122 [progress_ addEvent:event];
5123 [self updateProgress];
5126 - (bool) isProgressCancelled {
5127 return cancel_ == 2;
5132 [self updateCancel];
5135 - (void) setCancellable:(bool)cancellable {
5136 unsigned cancel(cancel_);
5140 else if (cancel_ == 0)
5143 if (cancel != cancel_)
5144 [self updateCancel];
5147 - (void) setProgressCancellable:(NSNumber *)cancellable {
5148 [self setCancellable:[cancellable boolValue]];
5151 - (void) setProgressPercent:(NSNumber *)percent {
5152 [progress_ setProgress:[percent floatValue]];
5153 [self updateProgress];
5159 /* Cell Content View {{{ */
5160 @protocol ContentDelegate
5161 - (void) drawContentRect:(CGRect)rect;
5164 @interface ContentView : UIView {
5165 _transient id<ContentDelegate> delegate_;
5170 @implementation ContentView
5172 - (id) initWithFrame:(CGRect)frame {
5173 if ((self = [super initWithFrame:frame]) != nil) {
5174 [self setNeedsDisplayOnBoundsChange:YES];
5178 - (void) setDelegate:(id<ContentDelegate>)delegate {
5179 delegate_ = delegate;
5182 - (void) drawRect:(CGRect)rect {
5183 [super drawRect:rect];
5184 [delegate_ drawContentRect:rect];
5189 /* Cydia TableView Cell {{{ */
5190 @interface CYTableViewCell : UITableViewCell {
5191 ContentView *content_;
5197 @implementation CYTableViewCell
5204 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5205 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5207 if (view == content_) {
5208 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5209 highlighted_ = highlighted;
5212 [super _updateHighlightColorsForView:view highlighted:highlighted];
5215 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5216 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5217 highlighted_ = selected;
5219 [super setSelected:selected animated:animated];
5220 [content_ setNeedsDisplay];
5226 /* Package Cell {{{ */
5227 @interface PackageCell : CYTableViewCell <
5232 NSString *description_;
5240 - (PackageCell *) init;
5241 - (void) setPackage:(Package *)package;
5243 - (void) drawContentRect:(CGRect)rect;
5247 @implementation PackageCell
5249 - (void) clearPackage {
5260 if (description_ != nil) {
5261 [description_ release];
5265 if (source_ != nil) {
5270 if (badge_ != nil) {
5275 if (placard_ != nil) {
5285 [self clearPackage];
5289 - (PackageCell *) init {
5290 CGRect frame(CGRectMake(0, 0, 320, 74));
5291 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5292 UIView *content([self contentView]);
5293 CGRect bounds([content bounds]);
5295 content_ = [[ContentView alloc] initWithFrame:bounds];
5296 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5297 [content addSubview:content_];
5299 [content_ setDelegate:self];
5300 [content_ setOpaque:YES];
5304 - (NSString *) accessibilityLabel {
5305 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5308 - (void) setPackage:(Package *)package {
5309 [self clearPackage];
5312 Source *source = [package source];
5314 icon_ = [[package icon] retain];
5315 name_ = [[package name] retain];
5318 description_ = [package longDescription];
5319 if (description_ == nil)
5320 description_ = [package shortDescription];
5321 if (description_ != nil)
5322 description_ = [description_ retain];
5324 commercial_ = [package isCommercial];
5326 package_ = [package retain];
5328 NSString *label = nil;
5329 bool trusted = false;
5331 if (source != nil) {
5332 label = [source label];
5333 trusted = [source trusted];
5334 } else if ([[package id] isEqualToString:@"firmware"])
5335 label = UCLocalize("APPLE");
5337 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5339 NSString *from(label);
5341 NSString *section = [package simpleSection];
5342 if (section != nil && ![section isEqualToString:label]) {
5343 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5344 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5347 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5348 source_ = [from retain];
5350 if (NSString *purpose = [package primaryPurpose])
5351 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5352 badge_ = [badge_ retain];
5357 if (NSString *mode = [package_ mode]) {
5358 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5359 color = RemovingColor_;
5360 //placard = @"removing";
5362 color = InstallingColor_;
5363 //placard = @"installing";
5366 // XXX: the removing/installing placards are not @2x
5369 color = [UIColor whiteColor];
5371 if ([package installed] != nil)
5372 placard = @"installed";
5377 [content_ setBackgroundColor:color];
5380 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5381 placard_ = [placard_ retain];
5383 [self setNeedsDisplay];
5384 [content_ setNeedsDisplay];
5387 - (void) drawContentRect:(CGRect)rect {
5388 bool highlighted(highlighted_);
5389 float width([self bounds].size.width);
5392 CGContextRef context(UIGraphicsGetCurrentContext());
5393 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5394 CGContextFillRect(context, rect);
5399 rect.size = [icon_ size];
5401 rect.size.width /= 2;
5402 rect.size.height /= 2;
5404 rect.origin.x = 25 - rect.size.width / 2;
5405 rect.origin.y = 25 - rect.size.height / 2;
5407 [icon_ drawInRect:rect];
5410 if (badge_ != nil) {
5412 rect.size = [badge_ size];
5414 rect.size.width /= 2;
5415 rect.size.height /= 2;
5417 rect.origin.x = 36 - rect.size.width / 2;
5418 rect.origin.y = 36 - rect.size.height / 2;
5420 [badge_ drawInRect:rect];
5427 UISetColor(commercial_ ? Purple_ : Black_);
5428 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5429 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5432 UISetColor(commercial_ ? Purplish_ : Gray_);
5433 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5435 if (placard_ != nil)
5436 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5441 /* Section Cell {{{ */
5442 @interface SectionCell : CYTableViewCell <
5454 - (void) setSection:(Section *)section editing:(BOOL)editing;
5458 @implementation SectionCell
5460 - (void) clearSection {
5461 if (basic_ != nil) {
5466 if (section_ != nil) {
5476 if (count_ != nil) {
5483 [self clearSection];
5489 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5490 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5491 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5492 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5493 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5495 UIView *content([self contentView]);
5496 CGRect bounds([content bounds]);
5498 content_ = [[ContentView alloc] initWithFrame:bounds];
5499 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5500 [content addSubview:content_];
5501 [content_ setBackgroundColor:[UIColor whiteColor]];
5503 [content_ setDelegate:self];
5507 - (void) onSwitch:(id)sender {
5508 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5509 if (metadata == nil) {
5510 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5511 [Sections_ setObject:metadata forKey:basic_];
5514 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5518 - (void) setSection:(Section *)section editing:(BOOL)editing {
5519 if (editing != editing_) {
5521 [switch_ removeFromSuperview];
5523 [self addSubview:switch_];
5527 [self clearSection];
5529 if (section == nil) {
5530 name_ = [UCLocalize("ALL_PACKAGES") retain];
5533 basic_ = [section name];
5535 basic_ = [basic_ retain];
5537 section_ = [section localized];
5538 if (section_ != nil)
5539 section_ = [section_ retain];
5541 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5542 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5545 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5548 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5549 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5551 [content_ setNeedsDisplay];
5554 - (void) setFrame:(CGRect)frame {
5555 [super setFrame:frame];
5557 CGRect rect([switch_ frame]);
5558 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5561 - (NSString *) accessibilityLabel {
5565 - (void) drawContentRect:(CGRect)rect {
5566 bool highlighted(highlighted_ && !editing_);
5568 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5573 float width(rect.size.width);
5579 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5581 CGSize size = [count_ sizeWithFont:Font14_];
5585 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5591 /* File Table {{{ */
5592 @interface FileTable : CYViewController <
5593 UITableViewDataSource,
5596 _transient Database *database_;
5599 NSMutableArray *files_;
5603 - (id) initWithDatabase:(Database *)database;
5604 - (void) setPackage:(Package *)package;
5608 @implementation FileTable
5611 [self releaseSubviews];
5620 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5621 return files_ == nil ? 0 : [files_ count];
5624 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5628 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5629 static NSString *reuseIdentifier = @"Cell";
5631 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5633 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5634 [cell setFont:[UIFont systemFontOfSize:16]];
5636 [cell setText:[files_ objectAtIndex:indexPath.row]];
5637 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5642 - (NSURL *) navigationURL {
5643 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5647 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5649 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5650 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5651 [list_ setRowHeight:24.0f];
5652 [list_ setDataSource:self];
5653 [list_ setDelegate:self];
5654 [[self view] addSubview:list_];
5657 - (void) viewDidLoad {
5658 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5661 - (void) releaseSubviews {
5666 - (id) initWithDatabase:(Database *)database {
5667 if ((self = [super init]) != nil) {
5668 database_ = database;
5670 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5674 - (void) setPackage:(Package *)package {
5675 if (package_ != nil) {
5676 [package_ autorelease];
5685 [files_ removeAllObjects];
5687 if (package != nil) {
5688 package_ = [package retain];
5689 name_ = [[package id] retain];
5691 if (NSArray *files = [package files])
5692 [files_ addObjectsFromArray:files];
5694 if ([files_ count] != 0) {
5695 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5696 [files_ removeObjectAtIndex:0];
5697 [files_ sortUsingSelector:@selector(compareByPath:)];
5699 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5700 [stack addObject:@"/"];
5702 for (int i(0), e([files_ count]); i != e; ++i) {
5703 NSString *file = [files_ objectAtIndex:i];
5704 while (![file hasPrefix:[stack lastObject]])
5705 [stack removeLastObject];
5706 NSString *directory = [stack lastObject];
5707 [stack addObject:[file stringByAppendingString:@"/"]];
5708 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5709 ([stack count] - 2) * 3, "",
5710 [file substringFromIndex:[directory length]]
5719 - (void) reloadData {
5722 [self setPackage:[database_ packageWithName:name_]];
5727 /* Package Controller {{{ */
5728 @interface CYPackageController : CYBrowserController <
5729 UIActionSheetDelegate
5731 _transient Database *database_;
5735 NSMutableArray *buttons_;
5736 UIBarButtonItem *button_;
5739 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5743 @implementation CYPackageController
5746 if (package_ != nil)
5759 - (NSURL *) navigationURL {
5760 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5763 /* XXX: this is not safe at all... localization of /fail/ */
5764 - (void) _clickButtonWithName:(NSString *)name {
5765 if ([name isEqualToString:UCLocalize("CLEAR")])
5766 [delegate_ clearPackage:package_];
5767 else if ([name isEqualToString:UCLocalize("INSTALL")])
5768 [delegate_ installPackage:package_];
5769 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5770 [delegate_ installPackage:package_];
5771 else if ([name isEqualToString:UCLocalize("REMOVE")])
5772 [delegate_ removePackage:package_];
5773 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5774 [delegate_ installPackage:package_];
5775 else _assert(false);
5778 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5779 NSString *context([sheet context]);
5781 if ([context isEqualToString:@"modify"]) {
5782 if (button != [sheet cancelButtonIndex]) {
5783 NSString *buttonName = [buttons_ objectAtIndex:button];
5784 [self _clickButtonWithName:buttonName];
5787 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5791 - (bool) _allowJavaScriptPanel {
5796 - (void) _customButtonClicked {
5797 int count([buttons_ count]);
5802 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5804 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5805 [buttons addObjectsFromArray:buttons_];
5807 UIActionSheet *sheet = [[[UIActionSheet alloc]
5810 cancelButtonTitle:nil
5811 destructiveButtonTitle:nil
5812 otherButtonTitles:nil
5815 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5817 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5818 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5820 [sheet setContext:@"modify"];
5822 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5826 // We don't want to allow non-commercial packages to do custom things to the install button,
5827 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5828 - (void) customButtonClicked {
5830 [super customButtonClicked];
5832 [self _customButtonClicked];
5835 - (void) reloadButtonClicked {
5836 // Don't reload a commerical package by tapping the loading button,
5837 // but if it's not an Install button, we should forward it on.
5838 if (![package_ uninstalled])
5839 [self _customButtonClicked];
5842 - (void) applyLoadingTitle {
5843 // Don't show "Loading" as the title. Ever.
5846 - (UIBarButtonItem *) rightButton {
5851 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5852 if ((self = [super init]) != nil) {
5853 database_ = database;
5854 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5855 name_ = [[NSString alloc] initWithString:name];
5856 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5860 - (void) reloadData {
5861 if (package_ != nil)
5862 [package_ autorelease];
5863 package_ = [database_ packageWithName:name_];
5865 [buttons_ removeAllObjects];
5867 if (package_ != nil) {
5870 package_ = [package_ retain];
5871 commercial_ = [package_ isCommercial];
5873 if ([package_ mode] != nil)
5874 [buttons_ addObject:UCLocalize("CLEAR")];
5875 if ([package_ source] == nil);
5876 else if ([package_ upgradableAndEssential:NO])
5877 [buttons_ addObject:UCLocalize("UPGRADE")];
5878 else if ([package_ uninstalled])
5879 [buttons_ addObject:UCLocalize("INSTALL")];
5881 [buttons_ addObject:UCLocalize("REINSTALL")];
5882 if (![package_ uninstalled])
5883 [buttons_ addObject:UCLocalize("REMOVE")];
5890 switch ([buttons_ count]) {
5891 case 0: title = nil; break;
5892 case 1: title = [buttons_ objectAtIndex:0]; break;
5893 default: title = UCLocalize("MODIFY"); break;
5896 button_ = [[UIBarButtonItem alloc]
5898 style:UIBarButtonItemStylePlain
5900 action:@selector(customButtonClicked)
5906 - (bool) isLoading {
5907 return commercial_ ? [super isLoading] : false;
5913 /* Package List Controller {{{ */
5914 @interface PackageListController : CYViewController <
5915 UITableViewDataSource,
5918 _transient Database *database_;
5920 NSMutableArray *packages_;
5921 NSMutableArray *sections_;
5923 NSMutableArray *index_;
5924 NSMutableDictionary *indices_;
5928 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5929 - (void) setDelegate:(id)delegate;
5930 - (void) resetCursor;
5934 @implementation PackageListController
5937 [packages_ release];
5938 [sections_ release];
5947 - (void) deselectWithAnimation:(BOOL)animated {
5948 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5951 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5952 CGRect base = [[self view] bounds];
5953 base.size.height -= bounds.size.height;
5954 base.origin = [list_ frame].origin;
5956 [UIView beginAnimations:nil context:NULL];
5957 [UIView setAnimationBeginsFromCurrentState:YES];
5958 [UIView setAnimationCurve:curve];
5959 [UIView setAnimationDuration:duration];
5960 [list_ setFrame:base];
5961 [UIView commitAnimations];
5964 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5965 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5968 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5969 [self resizeForKeyboardBounds:bounds duration:0];
5972 - (void) keyboardWillShow:(NSNotification *)notification {
5975 NSTimeInterval duration;
5976 UIViewAnimationCurve curve;
5977 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5978 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5979 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5980 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5982 CGRect kbframe = CGRectMake(round(center.x - bounds.size.width / 2.0), round(center.y - bounds.size.height / 2.0), bounds.size.width, bounds.size.height);
5983 UIViewController *base = self;
5984 while ([base parentViewController] != nil)
5985 base = [base parentViewController];
5986 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5987 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5989 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5992 - (void) keyboardWillHide:(NSNotification *)notification {
5993 NSTimeInterval duration;
5994 UIViewAnimationCurve curve;
5995 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5996 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5998 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6001 - (void) viewWillAppear:(BOOL)animated {
6002 [super viewWillAppear:animated];
6004 [self resizeForKeyboardBounds:CGRectZero];
6005 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6006 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6009 - (void) viewWillDisappear:(BOOL)animated {
6010 [super viewWillDisappear:animated];
6012 [self resizeForKeyboardBounds:CGRectZero];
6013 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6014 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6017 - (void) viewDidAppear:(BOOL)animated {
6018 [super viewDidAppear:animated];
6019 [self deselectWithAnimation:animated];
6022 - (void) didSelectPackage:(Package *)package {
6023 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6024 [view setDelegate:delegate_];
6025 [[self navigationController] pushViewController:view animated:YES];
6028 #if TryIndexedCollation
6029 + (BOOL) hasIndexedCollation {
6030 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6034 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6035 NSInteger count([sections_ count]);
6036 return count == 0 ? 1 : count;
6039 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6040 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6042 return [[sections_ objectAtIndex:section] name];
6045 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6046 if ([sections_ count] == 0)
6048 return [[sections_ objectAtIndex:section] count];
6051 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6052 @synchronized (database_) {
6053 if ([database_ era] != era_)
6056 Section *section([sections_ objectAtIndex:[path section]]);
6057 NSInteger row([path row]);
6058 Package *package([packages_ objectAtIndex:([section row] + row)]);
6059 return [[package retain] autorelease];
6062 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6063 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6065 cell = [[[PackageCell alloc] init] autorelease];
6066 [cell setPackage:[self packageAtIndexPath:path]];
6070 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6071 Package *package([self packageAtIndexPath:path]);
6072 package = [database_ packageWithName:[package id]];
6073 [self didSelectPackage:package];
6076 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6077 // XXX: is 20 the most optimal number here?
6078 return [packages_ count] > 20 ? index_ : nil;
6081 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6082 #if TryIndexedCollation
6083 if ([[self class] hasIndexedCollation]) {
6084 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6091 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6092 if ((self = [super init]) != nil) {
6093 database_ = database;
6094 title_ = [title copy];
6095 [[self navigationItem] setTitle:title_];
6097 #if TryIndexedCollation
6098 if ([[self class] hasIndexedCollation])
6099 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6102 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6104 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6106 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6107 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6109 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6110 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6111 [list_ setRowHeight:73];
6112 [[self view] addSubview:list_];
6114 [list_ setDataSource:self];
6115 [list_ setDelegate:self];
6119 - (void) setDelegate:(id)delegate {
6120 delegate_ = delegate;
6123 - (bool) hasPackage:(Package *)package {
6127 - (void) reloadData {
6130 era_ = [database_ era];
6131 NSArray *packages = [database_ packages];
6133 [packages_ removeAllObjects];
6134 [sections_ removeAllObjects];
6136 _profile(PackageTable$reloadData$Filter)
6137 for (Package *package in packages)
6138 if ([self hasPackage:package])
6139 [packages_ addObject:package];
6142 [indices_ removeAllObjects];
6144 Section *section = nil;
6146 #if TryIndexedCollation
6147 if ([[self class] hasIndexedCollation]) {
6148 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6149 NSArray *titles = [collation sectionIndexTitles];
6152 _profile(PackageTable$reloadData$Section)
6153 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6157 _profile(PackageTable$reloadData$Section$Package)
6158 package = [packages_ objectAtIndex:offset];
6159 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6162 while (secidx < index) {
6165 _profile(PackageTable$reloadData$Section$Allocate)
6166 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6169 _profile(PackageTable$reloadData$Section$Add)
6170 [sections_ addObject:section];
6174 [section addToCount];
6180 [index_ removeAllObjects];
6182 _profile(PackageTable$reloadData$Section)
6183 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6187 _profile(PackageTable$reloadData$Section$Package)
6188 package = [packages_ objectAtIndex:offset];
6189 index = [package index];
6192 if (section == nil || [section index] != index) {
6193 _profile(PackageTable$reloadData$Section$Allocate)
6194 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6197 [index_ addObject:[section name]];
6198 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6200 _profile(PackageTable$reloadData$Section$Add)
6201 [sections_ addObject:section];
6205 [section addToCount];
6210 _profile(PackageTable$reloadData$List)
6215 - (void) resetCursor {
6216 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6221 /* Filtered Package List Controller {{{ */
6222 @interface FilteredPackageListController : PackageListController {
6228 - (void) setObject:(id)object;
6229 - (void) setObject:(id)object forFilter:(SEL)filter;
6231 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6235 @implementation FilteredPackageListController
6243 - (void) setFilter:(SEL)filter {
6246 /* XXX: this is an unsafe optimization of doomy hell */
6247 Method method(class_getInstanceMethod([Package class], filter));
6248 _assert(method != NULL);
6249 imp_ = method_getImplementation(method);
6250 _assert(imp_ != NULL);
6253 - (void) setObject:(id)object {
6259 object_ = [object retain];
6262 - (void) setObject:(id)object forFilter:(SEL)filter {
6263 [self setFilter:filter];
6264 [self setObject:object];
6267 - (bool) hasPackage:(Package *)package {
6268 _profile(FilteredPackageTable$hasPackage)
6269 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6273 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6274 if ((self = [super initWithDatabase:database title:title]) != nil) {
6275 [self setFilter:filter];
6276 [self setObject:object];
6283 /* Home Controller {{{ */
6284 @interface HomeController : CYBrowserController {
6289 @implementation HomeController
6291 + (BOOL) shouldHideNavigationBar {
6295 - (NSURL *) navigationURL {
6296 return [NSURL URLWithString:@"cydia://home"];
6299 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6300 [super _setMoreHeaders:request];
6303 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6304 if (UniqueID_ != nil)
6305 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6307 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6310 - (void) aboutButtonClicked {
6311 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6313 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6314 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6315 [alert setCancelButtonIndex:0];
6318 @"Copyright (C) 2008-2011\n"
6319 "Jay Freeman (saurik)\n"
6320 "saurik@saurik.com\n"
6321 "http://www.saurik.com/"
6327 - (void) viewWillDisappear:(BOOL)animated {
6328 [super viewWillDisappear:animated];
6330 if ([[self class] shouldHideNavigationBar])
6331 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6334 - (void) viewWillAppear:(BOOL)animated {
6335 if (![self hasLoaded])
6336 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6338 [super viewWillAppear:animated];
6340 if ([[self class] shouldHideNavigationBar])
6341 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6344 - (void) viewDidLoad {
6345 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6346 initWithTitle:UCLocalize("ABOUT")
6347 style:UIBarButtonItemStylePlain
6349 action:@selector(aboutButtonClicked)
6355 /* Manage Controller {{{ */
6356 @interface ManageController : CYBrowserController {
6359 - (void) queueStatusDidChange;
6363 @implementation ManageController
6365 - (NSURL *) navigationURL {
6366 return [NSURL URLWithString:@"cydia://manage"];
6369 - (void) viewWillAppear:(BOOL)animated {
6370 if (![self hasLoaded])
6371 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6373 [super viewWillAppear:animated];
6376 - (void) viewDidLoad {
6377 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6378 initWithTitle:UCLocalize("SETTINGS")
6379 style:UIBarButtonItemStylePlain
6381 action:@selector(settingsButtonClicked)
6384 [self queueStatusDidChange];
6387 - (void) settingsButtonClicked {
6388 [delegate_ showSettings];
6392 - (void) queueButtonClicked {
6396 - (void) applyLoadingTitle {
6397 // Disable "Loading" title.
6400 - (void) applyRightButton {
6401 // Disable right button.
6405 - (void) queueStatusDidChange {
6407 if (!IsWildcat_ && Queuing_) {
6408 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6409 initWithTitle:UCLocalize("QUEUE")
6410 style:UIBarButtonItemStyleDone
6412 action:@selector(queueButtonClicked)
6415 [[self navigationItem] setRightBarButtonItem:nil];
6420 - (bool) isLoading {
6421 // Never show as loading.
6428 /* Refresh Bar {{{ */
6429 @interface RefreshBar : UINavigationBar {
6430 UIProgressIndicator *indicator_;
6431 UITextLabel *prompt_;
6432 UIProgressBar *progress_;
6433 UINavigationButton *cancel_;
6438 @implementation RefreshBar
6441 [indicator_ release];
6443 [progress_ release];
6448 - (void) positionViews {
6449 CGRect frame = [cancel_ frame];
6450 frame.size = [cancel_ sizeThatFits:frame.size];
6451 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6452 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6453 [cancel_ setFrame:frame];
6455 CGSize prgsize = {75, 100};
6457 [self frame].size.width - prgsize.width - 10,
6458 ([self frame].size.height - prgsize.height) / 2
6460 [progress_ setFrame:prgrect];
6462 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6463 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6464 CGRect indrect = {{indoffset, indoffset}, indsize};
6465 [indicator_ setFrame:indrect];
6467 CGSize prmsize = {215, indsize.height + 4};
6469 indoffset * 2 + indsize.width,
6470 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6472 [prompt_ setFrame:prmrect];
6475 - (void) setFrame:(CGRect)frame {
6476 [super setFrame:frame];
6477 [self positionViews];
6480 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6481 if ((self = [super initWithFrame:frame]) != nil) {
6482 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6484 [self setBarStyle:UIBarStyleBlack];
6486 UIBarStyle barstyle([self _barStyle:NO]);
6487 bool ugly(barstyle == UIBarStyleDefault);
6489 UIProgressIndicatorStyle style = ugly ?
6490 UIProgressIndicatorStyleMediumBrown :
6491 UIProgressIndicatorStyleMediumWhite;
6493 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6494 [indicator_ setStyle:style];
6495 [indicator_ startAnimation];
6496 [self addSubview:indicator_];
6498 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6499 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6500 [prompt_ setBackgroundColor:[UIColor clearColor]];
6501 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6502 [self addSubview:prompt_];
6504 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6505 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6506 [progress_ setStyle:0];
6507 [self addSubview:progress_];
6509 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6510 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6511 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6512 [cancel_ setBarStyle:barstyle];
6514 [self positionViews];
6518 - (void) setCancellable:(bool)cancellable {
6520 [self addSubview:cancel_];
6522 [cancel_ removeFromSuperview];
6526 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6527 [progress_ setProgress:0];
6531 [self setCancellable:NO];
6534 - (void) setPrompt:(NSString *)prompt {
6535 [prompt_ setText:prompt];
6538 - (void) setProgress:(float)progress {
6539 [progress_ setProgress:progress];
6545 @class CYNavigationController;
6547 /* Cydia Tab Bar Controller {{{ */
6548 @interface CYTabBarController : UITabBarController <
6549 UITabBarControllerDelegate,
6552 _transient Database *database_;
6553 RefreshBar *refreshbar_;
6557 // XXX: ok, "updatedelegate_"?...
6558 _transient NSObject<CydiaDelegate> *updatedelegate_;
6561 UIViewController *remembered_;
6562 _transient UIViewController *transient_;
6565 - (NSArray *) navigationURLCollection;
6566 - (void) dropBar:(BOOL)animated;
6567 - (void) beginUpdate;
6568 - (void) raiseBar:(BOOL)animated;
6573 @implementation CYTabBarController
6575 - (void) setUnselectedViewController:(UIViewController *)transient {
6576 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6577 if (transient != nil) {
6578 if (transient_ == nil)
6579 remembered_ = [[controllers objectAtIndex:0] retain];
6580 transient_ = transient;
6581 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6582 [controllers replaceObjectAtIndex:0 withObject:transient_];
6583 [self setSelectedIndex:0];
6584 [self setViewControllers:controllers];
6585 [self concealTabBarSelection];
6586 } else if (remembered_ != nil) {
6587 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6588 transient_ = transient;
6589 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6590 [remembered_ release];
6592 [self setViewControllers:controllers];
6593 [self revealTabBarSelection];
6597 - (UIViewController *) unselectedViewController {
6601 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6602 if ([self unselectedViewController])
6603 [self setUnselectedViewController:nil];
6606 - (NSArray *) navigationURLCollection {
6607 NSMutableArray *items([NSMutableArray array]);
6609 // XXX: Should this deal with transient view controllers?
6610 for (id navigation in [self viewControllers]) {
6611 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6613 [items addObject:stack];
6619 - (void) reloadData {
6620 for (CYViewController *controller in [self viewControllers])
6621 [controller reloadData];
6623 [(CYNavigationController *)[self unselectedViewController] reloadData];
6627 [refreshbar_ release];
6628 [[NSNotificationCenter defaultCenter] removeObserver:self];
6633 - (id) initWithDatabase:(Database *)database {
6634 if ((self = [super init]) != nil) {
6635 database_ = database;
6636 [self setDelegate:self];
6638 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6639 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6641 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6645 - (void) setUpdate:(NSDate *)date {
6649 - (void) beginUpdate {
6650 [refreshbar_ start];
6653 [updatedelegate_ retainNetworkActivityIndicator];
6657 detachNewThreadSelector:@selector(performUpdate)
6663 - (void) performUpdate { _pooled
6665 status.setDelegate(self);
6666 [database_ updateWithStatus:status];
6669 performSelectorOnMainThread:@selector(completeUpdate)
6675 - (void) stopUpdateWithSelector:(SEL)selector {
6677 [updatedelegate_ releaseNetworkActivityIndicator];
6679 [self raiseBar:YES];
6682 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6685 - (void) completeUpdate {
6688 [self stopUpdateWithSelector:@selector(reloadData)];
6691 - (void) cancelUpdate {
6692 [self stopUpdateWithSelector:@selector(updateData)];
6695 - (void) cancelPressed {
6696 [self cancelUpdate];
6703 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6704 [refreshbar_ setPrompt:[event compoundMessage]];
6707 - (bool) isProgressCancelled {
6711 - (void) setProgressCancellable:(NSNumber *)cancellable {
6712 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6715 - (void) setProgressPercent:(NSNumber *)percent {
6716 [refreshbar_ setProgress:[percent floatValue]];
6719 - (void) setUpdateDelegate:(id)delegate {
6720 updatedelegate_ = delegate;
6723 - (CGFloat) statusBarHeight {
6724 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6725 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6727 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6731 - (UIView *) transitionView {
6732 if ([self respondsToSelector:@selector(_transitionView)])
6733 return [self _transitionView];
6735 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6738 - (void) dropBar:(BOOL)animated {
6743 UIView *transition([self transitionView]);
6744 [[self view] addSubview:refreshbar_];
6746 CGRect barframe([refreshbar_ frame]);
6748 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6749 barframe.origin.y = [self statusBarHeight];
6751 barframe.origin.y = 0;
6753 [refreshbar_ setFrame:barframe];
6756 [UIView beginAnimations:nil context:NULL];
6758 CGRect viewframe = [transition frame];
6759 viewframe.origin.y += barframe.size.height;
6760 viewframe.size.height -= barframe.size.height;
6761 [transition setFrame:viewframe];
6764 [UIView commitAnimations];
6766 // Ensure bar has the proper width for our view, it might have changed
6767 barframe.size.width = viewframe.size.width;
6768 [refreshbar_ setFrame:barframe];
6770 // XXX: fix Apple's layout bug
6771 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6774 - (void) raiseBar:(BOOL)animated {
6779 UIView *transition([self transitionView]);
6780 [refreshbar_ removeFromSuperview];
6782 CGRect barframe([refreshbar_ frame]);
6785 [UIView beginAnimations:nil context:NULL];
6787 CGRect viewframe = [transition frame];
6788 viewframe.origin.y -= barframe.size.height;
6789 viewframe.size.height += barframe.size.height;
6790 [transition setFrame:viewframe];
6793 [UIView commitAnimations];
6795 // XXX: fix Apple's layout bug
6796 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6800 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6801 // XXX: fix Apple's layout bug
6802 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6806 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6807 bool dropped(dropped_);
6812 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6817 // XXX: fix Apple's layout bug
6818 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6821 - (void) statusBarFrameChanged:(NSNotification *)notification {
6830 /* Cydia Navigation Controller {{{ */
6831 @interface CYNavigationController : UINavigationController {
6832 _transient Database *database_;
6833 _transient id<UINavigationControllerDelegate> delegate_;
6836 - (NSArray *) navigationURLCollection;
6837 - (id) initWithDatabase:(Database *)database;
6838 - (void) reloadData;
6843 @implementation CYNavigationController
6845 - (NSArray *) navigationURLCollection {
6846 NSMutableArray *stack([NSMutableArray array]);
6848 for (CYViewController *controller in [self viewControllers]) {
6849 NSString *url = [[controller navigationURL] absoluteString];
6851 [stack addObject:url];
6857 - (void) reloadData {
6858 for (CYViewController *page in [self viewControllers]) {
6859 // Only reload controllers that have already loaded.
6860 // This prevents a page from accidentally loading too
6861 // early if it hasn't been shown on the screen yet.
6862 if ([page hasLoaded])
6867 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6868 delegate_ = delegate;
6871 - (id) initWithDatabase:(Database *)database {
6872 if ((self = [super init]) != nil) {
6873 database_ = database;
6880 /* Cydia:// Protocol {{{ */
6881 @interface CydiaURLProtocol : NSURLProtocol {
6886 @implementation CydiaURLProtocol
6888 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6889 NSURL *url([request URL]);
6892 NSString *scheme([[url scheme] lowercaseString]);
6893 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6898 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6902 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6903 id<NSURLProtocolClient> client([self client]);
6905 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6907 NSData *data(UIImagePNGRepresentation(icon));
6909 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6910 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6911 [client URLProtocol:self didLoadData:data];
6912 [client URLProtocolDidFinishLoading:self];
6916 - (void) startLoading {
6917 id<NSURLProtocolClient> client([self client]);
6918 NSURLRequest *request([self request]);
6920 NSURL *url([request URL]);
6921 NSString *href([url absoluteString]);
6923 NSString *path([href substringFromIndex:8]);
6924 NSRange slash([path rangeOfString:@"/"]);
6927 if (slash.location == NSNotFound) {
6931 command = [path substringToIndex:slash.location];
6932 path = [path substringFromIndex:(slash.location + 1)];
6935 Database *database([Database sharedInstance]);
6937 if ([command isEqualToString:@"package-icon"]) {
6940 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6941 Package *package([database packageWithName:path]);
6944 UIImage *icon([package icon]);
6945 [self _returnPNGWithImage:icon forRequest:request];
6946 } else if ([command isEqualToString:@"source-icon"]) {
6949 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6950 NSString *source(Simplify(path));
6951 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6953 icon = [UIImage applicationImageNamed:@"unknown.png"];
6954 [self _returnPNGWithImage:icon forRequest:request];
6955 } else if ([command isEqualToString:@"uikit-image"]) {
6958 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6959 UIImage *icon(_UIImageWithName(path));
6960 [self _returnPNGWithImage:icon forRequest:request];
6961 } else if ([command isEqualToString:@"section-icon"]) {
6964 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6965 NSString *section(Simplify(path));
6966 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6968 icon = [UIImage applicationImageNamed:@"unknown.png"];
6969 [self _returnPNGWithImage:icon forRequest:request];
6971 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6975 - (void) stopLoading {
6981 /* Section Controller {{{ */
6982 @interface SectionController : FilteredPackageListController {
6986 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6990 @implementation SectionController
6992 - (NSURL *) navigationURL {
6993 NSString *name = section_;
6997 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7000 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7003 title = UCLocalize("ALL_PACKAGES");
7004 else if (![name isEqual:@""])
7005 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7007 title = UCLocalize("NO_SECTION");
7009 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7016 /* Sections Controller {{{ */
7017 @interface SectionsController : CYViewController <
7018 UITableViewDataSource,
7021 _transient Database *database_;
7022 NSMutableArray *sections_;
7023 NSMutableArray *filtered_;
7028 - (id) initWithDatabase:(Database *)database;
7029 - (void) editButtonClicked;
7033 @implementation SectionsController
7036 [self releaseSubviews];
7037 [sections_ release];
7038 [filtered_ release];
7043 - (NSURL *) navigationURL {
7044 return [NSURL URLWithString:@"cydia://sections"];
7047 - (void) updateNavigationItem {
7048 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7049 if ([sections_ count] == 0) {
7050 [[self navigationItem] setRightBarButtonItem:nil];
7052 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7053 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7055 action:@selector(editButtonClicked)
7056 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7060 - (BOOL) isEditing {
7064 - (void) setEditing:(BOOL)editing {
7065 if ((editing_ = editing))
7068 [delegate_ updateData];
7070 [self updateNavigationItem];
7073 - (void) viewDidAppear:(BOOL)animated {
7074 [super viewDidAppear:animated];
7075 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7078 - (void) viewWillDisappear:(BOOL)animated {
7079 [super viewWillDisappear:animated];
7080 if (editing_) [self setEditing:NO];
7083 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7084 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7088 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7089 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7092 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7096 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7097 static NSString *reuseIdentifier = @"SectionCell";
7099 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7101 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7103 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7108 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7112 Section *section = [self sectionAtIndexPath:indexPath];
7114 SectionController *controller = [[[SectionController alloc]
7115 initWithDatabase:database_
7116 section:[section name]
7118 [controller setDelegate:delegate_];
7120 [[self navigationController] pushViewController:controller animated:YES];
7124 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7126 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7127 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7128 [list_ setRowHeight:45.0f];
7129 [list_ setDataSource:self];
7130 [list_ setDelegate:self];
7131 [[self view] addSubview:list_];
7134 - (void) viewDidLoad {
7135 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7138 - (void) releaseSubviews {
7143 - (id) initWithDatabase:(Database *)database {
7144 if ((self = [super init]) != nil) {
7145 database_ = database;
7147 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7148 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7152 - (void) reloadData {
7155 NSArray *packages = [database_ packages];
7157 [sections_ removeAllObjects];
7158 [filtered_ removeAllObjects];
7160 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7163 for (Package *package in packages) {
7164 NSString *name([package section]);
7165 NSString *key(name == nil ? @"" : name);
7169 _profile(SectionsView$reloadData$Section)
7170 section = [sections objectForKey:key];
7171 if (section == nil) {
7172 _profile(SectionsView$reloadData$Section$Allocate)
7173 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7174 [sections setObject:section forKey:key];
7179 [section addToCount];
7181 _profile(SectionsView$reloadData$Filter)
7182 if (![package valid] || ![package visible])
7190 [sections_ addObjectsFromArray:[sections allValues]];
7192 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7194 for (Section *section in sections_) {
7195 size_t count([section row]);
7199 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7200 [section setCount:count];
7201 [filtered_ addObject:section];
7204 [self updateNavigationItem];
7209 - (void) editButtonClicked {
7210 [self setEditing:(!editing_)];
7216 /* Changes Controller {{{ */
7217 @interface ChangesController : CYViewController <
7218 UITableViewDataSource,
7221 _transient Database *database_;
7223 CFMutableArrayRef packages_;
7224 NSMutableArray *sections_;
7227 BOOL hasSentFirstLoad_;
7230 - (id) initWithDatabase:(Database *)database;
7234 @implementation ChangesController
7237 [self releaseSubviews];
7238 CFRelease(packages_);
7239 [sections_ release];
7244 - (NSURL *) navigationURL {
7245 return [NSURL URLWithString:@"cydia://changes"];
7248 - (void) viewWillAppear:(BOOL)animated {
7249 // Loads after it appears, so don't load beforehand.
7251 [super viewWillAppear:animated];
7254 - (void) viewDidAppear:(BOOL)animated {
7255 [super viewDidAppear:animated];
7257 if (!hasSentFirstLoad_) {
7258 hasSentFirstLoad_ = YES;
7259 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7261 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7265 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7266 NSInteger count([sections_ count]);
7267 return count == 0 ? 1 : count;
7270 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7271 if ([sections_ count] == 0)
7273 return [[sections_ objectAtIndex:section] name];
7276 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7277 if ([sections_ count] == 0)
7279 return [[sections_ objectAtIndex:section] count];
7282 - (Package *) packageAtIndex:(NSUInteger)index {
7283 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7286 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7287 @synchronized (database_) {
7288 if ([database_ era] != era_)
7291 NSUInteger sectionIndex([path section]);
7292 if (sectionIndex >= [sections_ count])
7294 Section *section([sections_ objectAtIndex:sectionIndex]);
7295 NSInteger row([path row]);
7296 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7299 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7300 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7302 cell = [[[PackageCell alloc] init] autorelease];
7303 [cell setPackage:[self packageAtIndexPath:path]];
7307 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7308 Package *package([self packageAtIndexPath:path]);
7309 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7310 [view setDelegate:delegate_];
7311 [[self navigationController] pushViewController:view animated:YES];
7315 - (void) refreshButtonClicked {
7316 [delegate_ beginUpdate];
7317 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7320 - (void) upgradeButtonClicked {
7321 [delegate_ distUpgrade];
7325 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7327 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7328 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7329 [list_ setRowHeight:73];
7330 [list_ setDataSource:self];
7331 [list_ setDelegate:self];
7332 [[self view] addSubview:list_];
7335 - (void) viewDidLoad {
7336 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7339 - (void) releaseSubviews {
7344 - (id) initWithDatabase:(Database *)database {
7345 if ((self = [super init]) != nil) {
7346 database_ = database;
7348 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7349 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7353 // this mostly works because reloadData (below) is @synchronized (database_)
7354 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7355 - (void) _reloadPackages:(NSArray *)packages {
7356 CFRelease(packages_);
7357 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7360 _profile(ChangesController$_reloadPackages$Filter)
7361 for (Package *package in packages)
7362 if ([package upgradableAndEssential:YES] || [package visible])
7363 CFArrayAppendValue(packages_, package);
7366 _profile(ChangesController$_reloadPackages$radixSort)
7367 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7372 - (void) reloadData {
7373 @synchronized (database_) {
7374 era_ = [database_ era];
7375 NSArray *packages = [database_ packages];
7377 [sections_ removeAllObjects];
7380 UIProgressHUD *hud([delegate_ addProgressHUD]);
7381 [hud setText:UCLocalize("LOADING")];
7382 //NSLog(@"HUD:%@::%@", delegate_, hud);
7383 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7384 [delegate_ removeProgressHUD:hud];
7386 [self _reloadPackages:packages];
7389 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7390 Section *ignored = nil;
7391 Section *section = nil;
7395 bool unseens = false;
7397 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7399 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7400 Package *package = [self packageAtIndex:offset];
7402 BOOL uae = [package upgradableAndEssential:YES];
7406 time_t seen([package seen]);
7408 if (section == nil || last != seen) {
7412 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7415 _profile(ChangesController$reloadData$Allocate)
7416 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7417 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7418 [sections_ addObject:section];
7422 [section addToCount];
7423 } else if ([package ignored]) {
7424 if (ignored == nil) {
7425 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7427 [ignored addToCount];
7430 [upgradable addToCount];
7435 CFRelease(formatter);
7438 Section *last = [sections_ lastObject];
7439 size_t count = [last count];
7440 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7441 [sections_ removeLastObject];
7444 if ([ignored count] != 0)
7445 [sections_ insertObject:ignored atIndex:0];
7447 [sections_ insertObject:upgradable atIndex:0];
7452 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7453 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7454 style:UIBarButtonItemStylePlain
7456 action:@selector(upgradeButtonClicked)
7459 if (![delegate_ updating])
7460 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7461 initWithTitle:UCLocalize("REFRESH")
7462 style:UIBarButtonItemStylePlain
7464 action:@selector(refreshButtonClicked)
7472 /* Search Controller {{{ */
7473 @interface SearchController : FilteredPackageListController <
7476 UISearchBar *search_;
7480 - (id) initWithDatabase:(Database *)database;
7481 - (void) setSearchTerm:(NSString *)term;
7482 - (void) reloadData;
7486 @implementation SearchController
7493 - (NSURL *) navigationURL {
7494 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7495 return [NSURL URLWithString:@"cydia://search"];
7497 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7500 - (void) setSearchTerm:(NSString *)searchTerm {
7501 [search_ setText:searchTerm];
7505 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7506 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7507 [search_ resignFirstResponder];
7511 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7512 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7516 - (id) initWithDatabase:(Database *)database {
7517 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7518 search_ = [[UISearchBar alloc] init];
7522 - (void) viewDidAppear:(BOOL)animated {
7523 [super viewDidAppear:animated];
7525 if (!searchloaded_) {
7526 searchloaded_ = YES;
7527 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7528 [search_ layoutSubviews];
7529 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7531 UITextField *textField;
7532 if ([search_ respondsToSelector:@selector(searchField)])
7533 textField = [search_ searchField];
7535 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7537 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7538 [search_ setDelegate:self];
7539 [textField setEnablesReturnKeyAutomatically:NO];
7540 [[self navigationItem] setTitleView:textField];
7544 - (void) reloadData {
7545 [self setObject:[search_ text]];
7550 - (void) didSelectPackage:(Package *)package {
7551 [search_ resignFirstResponder];
7552 [super didSelectPackage:package];
7557 /* Package Settings Controller {{{ */
7558 @interface PackageSettingsController : CYViewController <
7559 UITableViewDataSource,
7562 _transient Database *database_;
7565 UITableView *table_;
7566 UISwitch *subscribedSwitch_;
7567 UISwitch *ignoredSwitch_;
7568 UITableViewCell *subscribedCell_;
7569 UITableViewCell *ignoredCell_;
7572 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7576 @implementation PackageSettingsController
7579 [self releaseSubviews];
7586 - (NSURL *) navigationURL {
7587 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7590 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7591 if (package_ == nil)
7594 if ([package_ installed] == nil)
7600 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7601 if (package_ == nil)
7604 // both sections contain just one item right now.
7608 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7612 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7614 return UCLocalize("SHOW_ALL_CHANGES_EX");
7616 return UCLocalize("IGNORE_UPGRADES_EX");
7619 - (void) onSubscribed:(id)control {
7620 bool value([control isOn]);
7621 if (package_ == nil)
7623 if ([package_ setSubscribed:value])
7624 [delegate_ updateData];
7627 - (void) _updateIgnored {
7628 const char *package([name_ UTF8String]);
7629 bool on([ignoredSwitch_ isOn]);
7631 pid_t pid(ExecFork());
7633 FILE *dpkg(popen("dpkg --set-selections", "w"));
7634 fwrite(package, strlen(package), 1, dpkg);
7637 fwrite(" hold\n", 6, 1, dpkg);
7639 fwrite(" install\n", 9, 1, dpkg);
7649 int result(waitpid(pid, &status, 0));
7652 _assert(result == pid);
7658 - (void) onIgnored:(id)control {
7659 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7660 [invocation setTarget:self];
7661 [invocation setSelector:@selector(_updateIgnored)];
7663 [delegate_ reloadDataWithInvocation:invocation];
7666 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7667 if (package_ == nil)
7670 switch ([indexPath section]) {
7671 case 0: return subscribedCell_;
7672 case 1: return ignoredCell_;
7681 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7683 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7684 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7685 [table_ setDataSource:self];
7686 [table_ setDelegate:self];
7687 [[self view] addSubview:table_];
7689 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7690 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7691 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7693 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7694 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7695 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7697 subscribedCell_ = [[UITableViewCell alloc] init];
7698 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7699 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7700 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7702 ignoredCell_ = [[UITableViewCell alloc] init];
7703 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7704 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7705 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7708 - (void) viewDidLoad {
7709 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7712 - (void) releaseSubviews {
7713 [ignoredCell_ release];
7716 [subscribedCell_ release];
7717 subscribedCell_ = nil;
7722 [ignoredSwitch_ release];
7723 ignoredSwitch_ = nil;
7725 [subscribedSwitch_ release];
7726 subscribedSwitch_ = nil;
7729 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7730 if ((self = [super init]) != nil) {
7731 database_ = database;
7732 name_ = [package retain];
7736 - (void) reloadData {
7739 if (package_ != nil)
7740 [package_ autorelease];
7741 package_ = [database_ packageWithName:name_];
7743 if (package_ != nil) {
7744 package_ = [package_ retain];
7745 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7746 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7747 } // XXX: what now, G?
7749 [table_ reloadData];
7755 /* Installed Controller {{{ */
7756 @interface InstalledController : FilteredPackageListController {
7760 - (id) initWithDatabase:(Database *)database;
7762 - (void) updateRoleButton;
7763 - (void) queueStatusDidChange;
7767 @implementation InstalledController
7773 - (NSURL *) navigationURL {
7774 return [NSURL URLWithString:@"cydia://installed"];
7777 - (id) initWithDatabase:(Database *)database {
7778 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7779 [self updateRoleButton];
7780 [self queueStatusDidChange];
7785 - (void) queueButtonClicked {
7790 - (void) queueStatusDidChange {
7794 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7795 initWithTitle:UCLocalize("QUEUE")
7796 style:UIBarButtonItemStyleDone
7798 action:@selector(queueButtonClicked)
7801 [[self navigationItem] setLeftBarButtonItem:nil];
7807 - (void) updateRoleButton {
7808 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7809 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7810 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7811 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7813 action:@selector(roleButtonClicked)
7817 - (void) roleButtonClicked {
7818 [self setObject:[NSNumber numberWithBool:expert_]];
7822 [self updateRoleButton];
7828 /* Source Cell {{{ */
7829 @interface SourceCell : CYTableViewCell <
7837 - (void) setSource:(Source *)source;
7841 @implementation SourceCell
7843 - (void) clearSource {
7853 - (void) setSource:(Source *)source {
7857 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7859 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7860 icon_ = [icon_ retain];
7862 origin_ = [[source name] retain];
7863 label_ = [[source uri] retain];
7865 [content_ setNeedsDisplay];
7873 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7874 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7875 UIView *content([self contentView]);
7876 CGRect bounds([content bounds]);
7878 content_ = [[ContentView alloc] initWithFrame:bounds];
7879 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7880 [content_ setBackgroundColor:[UIColor whiteColor]];
7881 [content addSubview:content_];
7883 [content_ setDelegate:self];
7884 [content_ setOpaque:YES];
7888 - (NSString *) accessibilityLabel {
7892 - (void) drawContentRect:(CGRect)rect {
7893 bool highlighted(highlighted_);
7894 float width(rect.size.width);
7897 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7904 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7908 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7913 /* Source Controller {{{ */
7914 @interface SourceController : FilteredPackageListController {
7915 _transient Source *source_;
7919 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7923 @implementation SourceController
7925 - (NSURL *) navigationURL {
7926 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7929 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7930 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7932 key_ = [[source key] retain];
7936 - (void) reloadData {
7937 source_ = [database_ sourceWithKey:key_];
7939 key_ = [[source_ key] retain];
7940 [self setObject:source_];
7941 [[self navigationItem] setTitle:[source_ label]];
7948 /* Sources Controller {{{ */
7949 @interface SourcesController : CYViewController <
7950 UITableViewDataSource,
7953 _transient Database *database_;
7955 NSMutableArray *sources_;
7959 UIProgressHUD *hud_;
7962 //NSURLConnection *installer_;
7963 NSURLConnection *trivial_;
7964 NSURLConnection *trivial_bz2_;
7965 NSURLConnection *trivial_gz_;
7966 //NSURLConnection *automatic_;
7971 - (id) initWithDatabase:(Database *)database;
7972 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7976 @implementation SourcesController
7978 - (void) _releaseConnection:(NSURLConnection *)connection {
7979 if (connection != nil) {
7980 [connection cancel];
7981 //[connection setDelegate:nil];
7982 [connection release];
7987 [self releaseSubviews];
7993 //[self _releaseConnection:installer_];
7994 [self _releaseConnection:trivial_];
7995 [self _releaseConnection:trivial_gz_];
7996 [self _releaseConnection:trivial_bz2_];
7997 //[self _releaseConnection:automatic_];
8003 - (NSURL *) navigationURL {
8004 return [NSURL URLWithString:@"cydia://sources"];
8007 - (void) viewDidAppear:(BOOL)animated {
8008 [super viewDidAppear:animated];
8009 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8012 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8013 return offset_ == 0 ? 1 : 2;
8016 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8017 switch (section + (offset_ == 0 ? 1 : 0)) {
8018 case 0: return UCLocalize("ENTERED_BY_USER");
8019 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8025 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8026 int count = [sources_ count];
8028 case 0: return (offset_ == 0 ? count : offset_);
8029 case 1: return count - offset_;
8035 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8037 switch (indexPath.section) {
8038 case 0: idx = indexPath.row; break;
8039 case 1: idx = indexPath.row + offset_; break;
8043 return [sources_ objectAtIndex:idx];
8046 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8047 static NSString *cellIdentifier = @"SourceCell";
8049 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8050 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8051 [cell setSource:[self sourceAtIndexPath:indexPath]];
8052 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8057 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8058 Source *source = [self sourceAtIndexPath:indexPath];
8060 SourceController *controller = [[[SourceController alloc]
8061 initWithDatabase:database_
8065 [controller setDelegate:delegate_];
8067 [[self navigationController] pushViewController:controller animated:YES];
8070 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8071 Source *source = [self sourceAtIndexPath:indexPath];
8072 return [source record] != nil;
8075 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8076 Source *source = [self sourceAtIndexPath:indexPath];
8077 [Sources_ removeObjectForKey:[source key]];
8078 [delegate_ syncData];
8082 [delegate_ addTrivialSource:href_];
8083 [delegate_ syncData];
8086 - (NSString *) getWarning {
8087 NSString *href(href_);
8088 NSRange colon([href rangeOfString:@"://"]);
8089 if (colon.location != NSNotFound)
8090 href = [href substringFromIndex:(colon.location + 3)];
8091 href = [href stringByAddingPercentEscapes];
8092 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8093 href = [href stringByCachingURLWithCurrentCDN];
8095 NSURL *url([NSURL URLWithString:href]);
8097 NSStringEncoding encoding;
8098 NSError *error(nil);
8100 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8101 return [warning length] == 0 ? nil : warning;
8105 - (void) _endConnection:(NSURLConnection *)connection {
8106 // XXX: the memory management in this method is horribly awkward
8108 NSURLConnection **field = NULL;
8109 if (connection == trivial_)
8111 else if (connection == trivial_bz2_)
8112 field = &trivial_bz2_;
8113 else if (connection == trivial_gz_)
8114 field = &trivial_gz_;
8115 _assert(field != NULL);
8116 [connection release];
8121 trivial_bz2_ == nil &&
8127 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8130 UIAlertView *alert = [[[UIAlertView alloc]
8131 initWithTitle:UCLocalize("SOURCE_WARNING")
8134 cancelButtonTitle:UCLocalize("CANCEL")
8136 UCLocalize("ADD_ANYWAY"),
8140 [alert setContext:@"warning"];
8141 [alert setNumberOfRows:1];
8145 } else if (error_ != nil) {
8146 UIAlertView *alert = [[[UIAlertView alloc]
8147 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8148 message:[error_ localizedDescription]
8150 cancelButtonTitle:UCLocalize("OK")
8151 otherButtonTitles:nil
8154 [alert setContext:@"urlerror"];
8157 UIAlertView *alert = [[[UIAlertView alloc]
8158 initWithTitle:UCLocalize("NOT_REPOSITORY")
8159 message:UCLocalize("NOT_REPOSITORY_EX")
8161 cancelButtonTitle:UCLocalize("OK")
8162 otherButtonTitles:nil
8165 [alert setContext:@"trivial"];
8169 [delegate_ releaseNetworkActivityIndicator];
8171 [delegate_ removeProgressHUD:hud_];
8180 if (error_ != nil) {
8187 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8188 switch ([response statusCode]) {
8194 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8195 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8197 error_ = [error retain];
8198 [self _endConnection:connection];
8201 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8202 [self _endConnection:connection];
8205 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8206 NSMutableURLRequest *request = [NSMutableURLRequest
8207 requestWithURL:[NSURL URLWithString:href]
8208 cachePolicy:NSURLRequestUseProtocolCachePolicy
8209 timeoutInterval:120.0
8212 [request setHTTPMethod:method];
8214 if (Machine_ != NULL)
8215 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8216 if (UniqueID_ != nil)
8217 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8219 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8221 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8224 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8225 NSString *context([alert context]);
8227 if ([context isEqualToString:@"source"]) {
8230 NSString *href = [[alert textField] text];
8232 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8234 if (![href hasSuffix:@"/"])
8235 href_ = [href stringByAppendingString:@"/"];
8238 href_ = [href_ retain];
8240 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8241 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8242 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8243 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8247 // XXX: this is stupid
8248 hud_ = [[delegate_ addProgressHUD] retain];
8249 [hud_ setText:UCLocalize("VERIFYING_URL")];
8250 [delegate_ retainNetworkActivityIndicator];
8259 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8260 } else if ([context isEqualToString:@"trivial"])
8261 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8262 else if ([context isEqualToString:@"urlerror"])
8263 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8264 else if ([context isEqualToString:@"warning"]) {
8279 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8284 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8286 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8287 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8288 [list_ setRowHeight:56];
8289 [list_ setDataSource:self];
8290 [list_ setDelegate:self];
8291 [[self view] addSubview:list_];
8294 - (void) viewDidLoad {
8295 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8296 [self updateButtonsForEditingStatus:NO animated:NO];
8299 - (void) releaseSubviews {
8304 - (id) initWithDatabase:(Database *)database {
8305 if ((self = [super init]) != nil) {
8306 database_ = database;
8307 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8311 - (void) reloadData {
8315 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8318 [sources_ removeAllObjects];
8319 [sources_ addObjectsFromArray:[database_ sources]];
8321 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8324 int count([sources_ count]);
8326 for (int i = 0; i != count; i++) {
8327 if ([[sources_ objectAtIndex:i] record] == nil)
8332 [list_ setEditing:NO];
8333 [self updateButtonsForEditingStatus:NO animated:NO];
8337 - (void) showAddSourcePrompt {
8338 UIAlertView *alert = [[[UIAlertView alloc]
8339 initWithTitle:UCLocalize("ENTER_APT_URL")
8342 cancelButtonTitle:UCLocalize("CANCEL")
8344 UCLocalize("ADD_SOURCE"),
8348 [alert setContext:@"source"];
8349 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8351 [alert setNumberOfRows:1];
8352 [alert addTextFieldWithValue:@"http://" label:@""];
8354 UITextInputTraits *traits = [[alert textField] textInputTraits];
8355 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8356 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8357 [traits setKeyboardType:UIKeyboardTypeURL];
8358 // XXX: UIReturnKeyDone
8359 [traits setReturnKeyType:UIReturnKeyNext];
8364 - (void) addButtonClicked {
8365 [self showAddSourcePrompt];
8368 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8369 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8370 initWithTitle:UCLocalize("ADD")
8371 style:UIBarButtonItemStylePlain
8373 action:@selector(addButtonClicked)
8374 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8376 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8377 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8378 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8380 action:@selector(editButtonClicked)
8381 ] autorelease] animated:animated];
8383 if (IsWildcat_ && !editing)
8384 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8385 initWithTitle:UCLocalize("SETTINGS")
8386 style:UIBarButtonItemStylePlain
8388 action:@selector(settingsButtonClicked)
8392 - (void) settingsButtonClicked {
8393 [delegate_ showSettings];
8396 - (void) editButtonClicked {
8397 [list_ setEditing:![list_ isEditing] animated:YES];
8399 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8405 /* Settings Controller {{{ */
8406 @interface SettingsController : CYViewController <
8407 UITableViewDataSource,
8410 _transient Database *database_;
8411 // XXX: ok, "roledelegate_"?...
8412 _transient id roledelegate_;
8413 UITableView *table_;
8414 UISegmentedControl *segment_;
8418 - (void) showDoneButton;
8419 - (void) resizeSegmentedControl;
8423 @implementation SettingsController
8426 [self releaseSubviews];
8432 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8434 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8435 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8436 [table_ setDelegate:self];
8437 [table_ setDataSource:self];
8438 [[self view] addSubview:table_];
8440 NSArray *items = [NSArray arrayWithObjects:
8442 UCLocalize("HACKER"),
8443 UCLocalize("DEVELOPER"),
8445 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8446 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8447 [container_ addSubview:segment_];
8450 - (void) viewDidLoad {
8451 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8454 if ([Role_ isEqualToString:@"User"]) index = 0;
8455 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8456 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8458 [segment_ setSelectedSegmentIndex:index];
8459 [self showDoneButton];
8462 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8463 [self resizeSegmentedControl];
8466 - (void) releaseSubviews {
8473 [container_ release];
8477 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8478 if ((self = [super init]) != nil) {
8479 database_ = database;
8480 roledelegate_ = delegate;
8484 - (void) resizeSegmentedControl {
8485 CGFloat width = [[self view] frame].size.width;
8486 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8489 - (void) viewWillAppear:(BOOL)animated {
8490 [super viewWillAppear:animated];
8492 [self resizeSegmentedControl];
8495 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8496 [self resizeSegmentedControl];
8499 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8500 [self resizeSegmentedControl];
8504 NSString *role(nil);
8506 switch ([segment_ selectedSegmentIndex]) {
8507 case 0: role = @"User"; break;
8508 case 1: role = @"Hacker"; break;
8509 case 2: role = @"Developer"; break;
8514 if (![role isEqualToString:Role_]) {
8515 bool rolling(Role_ == nil);
8518 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8522 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8526 [roledelegate_ loadData];
8528 [roledelegate_ updateData];
8532 - (void) segmentChanged:(UISegmentedControl *)control {
8533 [self showDoneButton];
8536 - (void) saveAndClose {
8539 [[self navigationItem] setRightBarButtonItem:nil];
8540 [[self navigationController] dismissModalViewControllerAnimated:YES];
8543 - (void) doneButtonClicked {
8544 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8545 [spinner startAnimating];
8546 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8547 [[self navigationItem] setRightBarButtonItem:spinItem];
8549 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8552 - (void) showDoneButton {
8553 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8554 initWithTitle:UCLocalize("DONE")
8555 style:UIBarButtonItemStyleDone
8557 action:@selector(doneButtonClicked)
8558 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8561 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8562 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8566 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8570 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8571 return nil; // This method is required by the protocol.
8574 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8576 return UCLocalize("ROLE_EX");
8578 return [NSString stringWithFormat:
8579 @"%@: %@\n%@: %@\n%@: %@",
8580 UCLocalize("USER"), UCLocalize("USER_EX"),
8581 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8582 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8587 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8588 return section == 3 ? 44.0f : 0;
8591 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8592 return section == 3 ? container_ : nil;
8595 - (void) reloadData {
8597 [table_ reloadData];
8602 /* Stash Controller {{{ */
8603 @interface StashController : CYViewController {
8604 UIActivityIndicatorView *spinner_;
8611 @implementation StashController
8614 [self releaseSubviews];
8620 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8621 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8623 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8624 CGRect spinrect = [spinner_ frame];
8625 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8626 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8627 [spinner_ setFrame:spinrect];
8628 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8629 [[self view] addSubview:spinner_];
8630 [spinner_ startAnimating];
8633 captrect.size.width = [[self view] frame].size.width;
8634 captrect.size.height = 40.0f;
8635 captrect.origin.x = 0;
8636 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8637 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8638 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8639 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8640 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8641 [caption_ setTextColor:[UIColor whiteColor]];
8642 [caption_ setBackgroundColor:[UIColor clearColor]];
8643 [caption_ setShadowColor:[UIColor blackColor]];
8644 [caption_ setTextAlignment:UITextAlignmentCenter];
8645 [[self view] addSubview:caption_];
8648 statusrect.size.width = [[self view] frame].size.width;
8649 statusrect.size.height = 30.0f;
8650 statusrect.origin.x = 0;
8651 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8652 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8653 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8654 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8655 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8656 [status_ setTextColor:[UIColor whiteColor]];
8657 [status_ setBackgroundColor:[UIColor clearColor]];
8658 [status_ setShadowColor:[UIColor blackColor]];
8659 [status_ setTextAlignment:UITextAlignmentCenter];
8660 [[self view] addSubview:status_];
8663 - (void) releaseSubviews {
8677 @interface Cydia : UIApplication <
8678 ConfirmationControllerDelegate,
8681 UINavigationControllerDelegate,
8682 UITabBarControllerDelegate
8684 // XXX: evaluate all fields for _transient
8687 CYTabBarController *tabbar_;
8688 CYEmulatedLoadingController *emulated_;
8690 NSMutableArray *essential_;
8691 NSMutableArray *broken_;
8693 Database *database_;
8700 StashController *stash_;
8709 @implementation Cydia
8711 - (void) beginUpdate {
8712 [tabbar_ beginUpdate];
8716 return [tabbar_ updating];
8720 if ([broken_ count] != 0) {
8721 int count = [broken_ count];
8723 UIAlertView *alert = [[[UIAlertView alloc]
8724 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8725 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8727 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8729 UCLocalize("TEMPORARY_IGNORE"),
8733 [alert setContext:@"fixhalf"];
8735 } else if (!Ignored_ && [essential_ count] != 0) {
8736 int count = [essential_ count];
8738 UIAlertView *alert = [[[UIAlertView alloc]
8739 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8740 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8742 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8744 UCLocalize("UPGRADE_ESSENTIAL"),
8745 UCLocalize("COMPLETE_UPGRADE"),
8749 [alert setContext:@"upgrade"];
8754 - (void) _saveConfig {
8760 NSString *error(nil);
8762 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8764 NSError *error(nil);
8765 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8766 NSLog(@"failure to save metadata data: %@", error);
8771 NSLog(@"failure to serialize metadata: %@", error);
8776 // Navigation controller for the queuing badge.
8777 - (CYNavigationController *) queueNavigationController {
8778 NSArray *controllers = [tabbar_ viewControllers];
8779 return [controllers objectAtIndex:3];
8782 - (void) _updateData {
8785 [tabbar_ reloadData];
8787 CYNavigationController *navigation = [self queueNavigationController];
8789 id queuedelegate = nil;
8790 if ([[navigation viewControllers] count] > 0)
8791 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8793 [queuedelegate queueStatusDidChange];
8794 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8797 - (void) _refreshIfPossible:(NSDate *)update {
8798 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8800 bool recently = false;
8801 if (update != nil) {
8802 NSTimeInterval interval([update timeIntervalSinceNow]);
8803 if (interval <= 0 && interval > -(15*60))
8807 // Don't automatic refresh if:
8808 // - We already refreshed recently.
8809 // - We already auto-refreshed this launch.
8810 // - Auto-refresh is disabled.
8811 if (recently || loaded_ || ManualRefresh) {
8812 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8814 // If we are cancelling, we need to make sure it knows it's already loaded.
8818 // We are going to load, so remember that.
8822 SCNetworkReachabilityFlags flags; {
8823 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8824 SCNetworkReachabilityGetFlags(reachability, &flags);
8825 CFRelease(reachability);
8828 // XXX: this elaborate mess is what Apple is using to determine this? :(
8829 // XXX: do we care if the user has to intervene? maybe that's ok?
8831 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8832 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8833 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8834 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8835 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8836 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8840 // If we can reach the server, auto-refresh!
8842 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8847 - (void) refreshIfPossible {
8848 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8851 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8852 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8853 [hud setText:UCLocalize("RELOADING_DATA")];
8855 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8858 [self removeProgressHUD:hud];
8862 [essential_ removeAllObjects];
8863 [broken_ removeAllObjects];
8865 NSArray *packages([database_ packages]);
8866 for (Package *package in packages) {
8868 [broken_ addObject:package];
8869 if ([package upgradableAndEssential:NO]) {
8870 if ([package essential])
8871 [essential_ addObject:package];
8876 NSLog(@"changes:#%u", changes);
8878 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8881 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8882 [changesItem setBadgeValue:badge];
8883 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8884 [self setApplicationIconBadgeNumber:changes];
8887 [changesItem setBadgeValue:nil];
8888 [changesItem setAnimatedBadge:NO];
8889 [self setApplicationIconBadgeNumber:0];
8894 [self refreshIfPossible];
8897 - (void) updateData {
8906 @synchronized (self) {
8907 [self _reloadDataWithInvocation:nil];
8911 - (void) presentModalViewController:(UIViewController *)controller {
8912 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
8914 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8915 [((UIViewController *) emulated_ ?: tabbar_) presentModalViewController:navigation animated:YES];
8918 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8919 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8921 if (navigation != nil)
8922 [navigation pushViewController:progress animated:YES];
8924 [self presentModalViewController:progress];
8926 [progress invoke:invocation withTitle:title];
8930 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8931 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8934 - (void) repairWithInvocation:(NSInvocation *)invocation {
8936 [self invokeNewProgress:invocation forController:nil withTitle:UCLocalize("REPAIRING")];
8940 - (void) repairWithSelector:(SEL)selector {
8941 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8947 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8948 _assert(file != NULL);
8950 for (NSString *key in [Sources_ allKeys]) {
8951 NSDictionary *source([Sources_ objectForKey:key]);
8953 fprintf(file, "%s %s %s\n",
8954 [[source objectForKey:@"Type"] UTF8String],
8955 [[source objectForKey:@"URI"] UTF8String],
8956 [[source objectForKey:@"Distribution"] UTF8String]
8962 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:UCLocalize("UPDATING_SOURCES")];
8967 - (void) addTrivialSource:(NSString *)href {
8968 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8971 @"./", @"Distribution",
8972 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8977 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8978 @synchronized (self) {
8979 [self _reloadDataWithInvocation:invocation];
8983 - (void) reloadData {
8984 [self reloadDataWithInvocation:nil];
8988 pkgProblemResolver *resolver = [database_ resolver];
8990 resolver->InstallProtect();
8991 if (!resolver->Resolve(true))
8996 // XXX: this is a really crappy way of doing this.
8997 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8998 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8999 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9000 if ([tabbar_ updating])
9001 [tabbar_ cancelUpdate];
9003 if (![database_ prepare])
9006 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9007 [page setDelegate:self];
9008 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9009 [confirm_ setDelegate:self];
9012 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9013 [tabbar_ presentModalViewController:confirm_ animated:YES];
9019 @synchronized (self) {
9024 - (void) clearPackage:(Package *)package {
9025 @synchronized (self) {
9032 - (void) installPackages:(NSArray *)packages {
9033 @synchronized (self) {
9034 for (Package *package in packages)
9041 - (void) installPackage:(Package *)package {
9042 @synchronized (self) {
9049 - (void) removePackage:(Package *)package {
9050 @synchronized (self) {
9057 - (void) distUpgrade {
9058 @synchronized (self) {
9059 if (![database_ upgrade])
9065 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9068 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:UCLocalize("RUNNING")];
9073 - (void) showSettings {
9074 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9075 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9077 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9078 [tabbar_ presentModalViewController:nav animated:YES];
9081 - (void) retainNetworkActivityIndicator {
9082 if (activity_++ == 0)
9083 [self setNetworkActivityIndicatorVisible:YES];
9086 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9090 - (void) releaseNetworkActivityIndicator {
9091 if (--activity_ == 0)
9092 [self setNetworkActivityIndicatorVisible:NO];
9095 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9100 - (void) cancelAndClear:(bool)clear {
9101 @synchronized (self) {
9113 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9114 NSString *context([alert context]);
9116 if ([context isEqualToString:@"conffile"]) {
9117 FILE *input = [database_ input];
9118 if (button == [alert cancelButtonIndex])
9119 fprintf(input, "N\n");
9120 else if (button == [alert firstOtherButtonIndex])
9121 fprintf(input, "Y\n");
9124 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9125 } else if ([context isEqualToString:@"fixhalf"]) {
9126 if (button == [alert cancelButtonIndex]) {
9127 @synchronized (self) {
9128 for (Package *broken in broken_) {
9131 NSString *id = [broken id];
9132 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9133 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9134 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9135 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9141 } else if (button == [alert firstOtherButtonIndex]) {
9142 [broken_ removeAllObjects];
9146 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9147 } else if ([context isEqualToString:@"upgrade"]) {
9148 if (button == [alert firstOtherButtonIndex]) {
9149 @synchronized (self) {
9150 for (Package *essential in essential_)
9151 [essential install];
9156 } else if (button == [alert firstOtherButtonIndex] + 1) {
9158 } else if (button == [alert cancelButtonIndex]) {
9162 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9166 - (void) system:(NSString *)command { _pooled
9168 system([command UTF8String]);
9172 - (void) applicationWillSuspend {
9174 [super applicationWillSuspend];
9177 - (BOOL) isSafeToSuspend {
9178 // Use external process status API internally.
9179 // This is probably a really bad idea.
9180 // XXX: what is the point of this? does this solve anything at all?
9181 uint64_t status = 0;
9183 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9184 notify_get_state(notify_token, &status);
9185 notify_cancel(notify_token);
9188 return locked_ == 0 && status == 0;
9191 - (void) applicationSuspend:(__GSEvent *)event {
9192 if ([self isSafeToSuspend])
9193 [super applicationSuspend:event];
9196 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9197 if ([self isSafeToSuspend])
9198 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9201 - (void) _setSuspended:(BOOL)value {
9202 if ([self isSafeToSuspend])
9203 [super _setSuspended:value];
9206 - (UIProgressHUD *) addProgressHUD {
9207 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9208 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9210 [window_ setUserInteractionEnabled:NO];
9213 UIViewController *target = tabbar_;
9214 while ([target modalViewController] != nil) target = [target modalViewController];
9215 [[target view] addSubview:hud];
9221 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9223 [hud removeFromSuperview];
9224 [window_ setUserInteractionEnabled:YES];
9228 - (CYViewController *) pageForPackage:(NSString *)name {
9229 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9232 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9233 NSString *scheme([[url scheme] lowercaseString]);
9234 if ([[url absoluteString] length] <= [scheme length] + 3)
9236 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9237 NSArray *components([path pathComponents]);
9239 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9240 return [self pageForPackage:[components objectAtIndex:1]];
9242 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9245 NSString *base([components objectAtIndex:0]);
9247 CYViewController *controller = nil;
9249 if ([base isEqualToString:@"url"]) {
9250 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9251 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9252 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9253 } else if (!external && [components count] == 1) {
9254 if ([base isEqualToString:@"manage"]) {
9255 controller = [[[ManageController alloc] init] autorelease];
9258 if ([base isEqualToString:@"sources"]) {
9259 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9262 if ([base isEqualToString:@"home"]) {
9263 controller = [[[HomeController alloc] init] autorelease];
9266 if ([base isEqualToString:@"sections"]) {
9267 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9270 if ([base isEqualToString:@"search"]) {
9271 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9274 if ([base isEqualToString:@"changes"]) {
9275 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9278 if ([base isEqualToString:@"installed"]) {
9279 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9281 } else if ([components count] == 2) {
9282 NSString *argument = [components objectAtIndex:1];
9284 if ([base isEqualToString:@"package"]) {
9285 controller = [self pageForPackage:argument];
9288 if (!external && [base isEqualToString:@"search"]) {
9289 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9290 [(SearchController *)controller setSearchTerm:argument];
9293 if (!external && [base isEqualToString:@"sections"]) {
9294 if ([argument isEqualToString:@"all"])
9296 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9299 if (!external && [base isEqualToString:@"sources"]) {
9300 if ([argument isEqualToString:@"add"]) {
9301 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9302 [(SourcesController *)controller showAddSourcePrompt];
9304 Source *source = [database_ sourceWithKey:argument];
9305 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9309 if (!external && [base isEqualToString:@"launch"]) {
9310 [self launchApplicationWithIdentifier:argument suspended:NO];
9313 } else if (!external && [components count] == 3) {
9314 NSString *arg1 = [components objectAtIndex:1];
9315 NSString *arg2 = [components objectAtIndex:2];
9317 if ([base isEqualToString:@"package"]) {
9318 if ([arg2 isEqualToString:@"settings"]) {
9319 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9320 } else if ([arg2 isEqualToString:@"files"]) {
9321 if (Package *package = [database_ packageWithName:arg1]) {
9322 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9323 [(FileTable *)controller setPackage:package];
9329 [controller setDelegate:self];
9333 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9334 CYViewController *page([self pageForURL:url forExternal:external]);
9337 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9338 [nav setViewControllers:[NSArray arrayWithObject:page]];
9339 [tabbar_ setUnselectedViewController:nav];
9345 - (void) applicationOpenURL:(NSURL *)url {
9346 [super applicationOpenURL:url];
9348 if (!loaded_) starturl_ = [url retain];
9349 else [self openCydiaURL:url forExternal:YES];
9352 - (void) applicationWillResignActive:(UIApplication *)application {
9353 // Stop refreshing if you get a phone call or lock the device.
9354 if ([tabbar_ updating])
9355 [tabbar_ cancelUpdate];
9357 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9358 [super applicationWillResignActive:application];
9361 - (void) applicationWillTerminate:(UIApplication *)application {
9363 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9364 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9365 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9370 - (void) setConfigurationData:(NSString *)data {
9371 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9373 if (!conffile_r(data)) {
9374 lprintf("E:invalid conffile\n");
9378 NSString *ofile = conffile_r[1];
9379 //NSString *nfile = conffile_r[2];
9381 UIAlertView *alert = [[[UIAlertView alloc]
9382 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9383 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9385 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9387 UCLocalize("ACCEPT_NEW_COPY"),
9388 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9392 [alert setContext:@"conffile"];
9396 - (void) addStashController {
9398 stash_ = [[StashController alloc] init];
9399 [window_ addSubview:[stash_ view]];
9402 - (void) removeStashController {
9403 [[stash_ view] removeFromSuperview];
9409 [self setIdleTimerDisabled:YES];
9411 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9412 UpdateExternalStatus(1);
9413 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9414 UpdateExternalStatus(0);
9416 [self removeStashController];
9418 if (ExecFork() == 0) {
9419 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9420 perror("launchctl stop");
9424 - (void) setupViewControllers {
9425 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9427 NSMutableArray *items([NSMutableArray arrayWithObjects:
9428 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9429 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9430 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9431 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9435 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9436 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9438 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9441 NSMutableArray *controllers([NSMutableArray array]);
9442 for (UITabBarItem *item in items) {
9443 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9444 [controller setTabBarItem:item];
9445 [controllers addObject:controller];
9447 [tabbar_ setViewControllers:controllers];
9449 [tabbar_ setUpdateDelegate:self];
9452 - (void) applicationDidFinishLaunching:(id)unused {
9454 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9455 [self setApplicationSupportsShakeToEdit:NO];
9457 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9458 initWithMemoryCapacity:524288
9459 diskCapacity:10485760
9460 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9463 [CYBrowserController _initialize];
9465 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9467 Font12_ = [[UIFont systemFontOfSize:12] retain];
9468 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9469 Font14_ = [[UIFont systemFontOfSize:14] retain];
9470 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9471 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9473 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9474 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9476 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9477 [window_ orderFront:self];
9478 [window_ makeKey:self];
9479 [window_ setHidden:NO];
9482 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9483 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9484 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9485 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9486 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9487 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9488 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9489 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9490 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9493 [self addStashController];
9494 // XXX: this would be much cleaner as a yieldToSelector:
9495 // that way the removeStashController could happen right here inline
9496 // we also could no longer require the useless stash_ field anymore
9497 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9501 database_ = [Database sharedInstance];
9502 [database_ setDelegate:self];
9504 [window_ setUserInteractionEnabled:NO];
9505 [self setupViewControllers];
9507 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9508 [window_ addSubview:[emulated_ view]];
9510 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9517 [window_ setUserInteractionEnabled:YES];
9518 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease]];
9521 if ([emulated_ modalViewController] != nil)
9522 [emulated_ dismissModalViewControllerAnimated:YES];
9523 [window_ setUserInteractionEnabled:NO];
9529 [window_ addSubview:[tabbar_ view]];
9531 [[emulated_ view] removeFromSuperview];
9532 [emulated_ release];
9535 [window_ setUserInteractionEnabled:YES];
9537 int selectedIndex = 0;
9538 NSMutableArray *items = nil;
9540 bool recently = false;
9541 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9542 if (closed != nil) {
9543 NSTimeInterval interval([closed timeIntervalSinceNow]);
9544 // XXX: Is 15 minutes the optimal time here?
9545 if (interval <= 0 && interval > -(15*60))
9549 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9550 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9553 for (NSArray *entry in items)
9554 if ([entry count] <= 0)
9557 if (!recently || !items || !enough) {
9559 items = [NSMutableArray array];
9560 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9561 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9562 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9564 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9566 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9567 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9569 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9572 [tabbar_ setSelectedIndex:selectedIndex];
9573 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9574 NSArray *stack = [items objectAtIndex:tab];
9575 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9576 NSMutableArray *current = [NSMutableArray array];
9578 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9579 NSString *addr = [stack objectAtIndex:nav];
9580 NSURL *url = [NSURL URLWithString:addr];
9581 CYViewController *page = [self pageForURL:url forExternal:NO];
9583 [current addObject:page];
9586 [navigation setViewControllers:current];
9589 // (Try to) show the startup URL.
9590 if (starturl_ != nil) {
9591 [self openCydiaURL:starturl_ forExternal:NO];
9592 [starturl_ release];
9597 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9598 if (item != nil && IsWildcat_) {
9599 [sheet showFromBarButtonItem:item animated:YES];
9601 [sheet showInView:window_];
9605 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9606 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9607 [progress setTitle:task];
9608 [progress addProgressEvent:event];
9611 - (void) addProgressEventForTask:(NSArray *)data {
9612 CydiaProgressEvent *event([data objectAtIndex:0]);
9613 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9614 [self addProgressEvent:event forTask:task];
9617 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9618 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9624 id Alloc_(id self, SEL selector) {
9625 id object = alloc_(self, selector);
9626 lprintf("[%s]A-%p\n", self->isa->name, object);
9631 id Dealloc_(id self, SEL selector) {
9632 id object = dealloc_(self, selector);
9633 lprintf("[%s]D-%p\n", self->isa->name, object);
9637 Class $WebDefaultUIKitDelegate;
9639 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9640 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9641 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9642 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9645 static NSNumber *shouldPlayKeyboardSounds;
9649 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9651 case 1104: // Keyboard Button Clicked
9652 case 1105: // Keyboard Delete Repeated
9653 if (shouldPlayKeyboardSounds == nil) {
9654 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9655 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9658 if (![shouldPlayKeyboardSounds boolValue])
9662 _UIHardware$_playSystemSound$(self, _cmd, sound);
9666 Class $UIApplication;
9668 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9669 static BOOL initialized = NO;
9670 static BOOL started = NO;
9672 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9673 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9675 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9676 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9677 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9678 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9680 if (initialized && !enabled) {
9682 [bundle performSelector:@selector(_accessibilityStopServer)];
9683 } else if (enabled) {
9687 [bundle performSelector:@selector(_accessibilityStartServer)];
9693 int main(int argc, char *argv[]) { _pooled
9696 UpdateExternalStatus(0);
9698 if (Class $UIDevice = objc_getClass("UIDevice")) {
9699 UIDevice *device([$UIDevice currentDevice]);
9700 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9704 UIScreen *screen([UIScreen mainScreen]);
9705 if ([screen respondsToSelector:@selector(scale)])
9706 ScreenScale_ = [screen scale];
9710 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9711 if (ScreenScale_ > 1)
9712 [parts addObject:@"@2x"];
9713 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9714 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9716 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9718 /* Library Hacks {{{ */
9719 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9721 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9722 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9723 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9724 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9725 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9728 $UIHardware = objc_getClass("UIHardware");
9729 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9730 if (UIHardware$_playSystemSound$ != NULL) {
9731 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9732 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9735 $UIApplication = objc_getClass("UIApplication");
9736 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9737 if (UIApplication$_updateApplicationAccessibility != NULL) {
9738 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9739 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9742 /* Set Locale {{{ */
9743 Locale_ = CFLocaleCopyCurrent();
9744 Languages_ = [NSLocale preferredLanguages];
9745 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9746 //NSLog(@"%@", [Languages_ description]);
9749 if (Languages_ == nil || [Languages_ count] == 0)
9750 // XXX: consider just setting to C and then falling through?
9753 lang = [[Languages_ objectAtIndex:0] UTF8String];
9754 setenv("LANG", lang, true);
9757 //std::setlocale(LC_ALL, lang);
9758 NSLog(@"Setting Language: %s", lang);
9761 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9763 /* Parse Arguments {{{ */
9764 bool substrate(false);
9770 for (int argi(1); argi != argc; ++argi)
9771 if (strcmp(argv[argi], "--") == 0) {
9773 argv[argi] = argv[0];
9779 for (int argi(1); argi != arge; ++argi)
9780 if (strcmp(args[argi], "--substrate") == 0)
9783 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9787 App_ = [[NSBundle mainBundle] bundlePath];
9788 Home_ = NSHomeDirectory();
9794 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9795 alloc_ = alloc->method_imp;
9796 alloc->method_imp = (IMP) &Alloc_;*/
9798 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9799 dealloc_ = dealloc->method_imp;
9800 dealloc->method_imp = (IMP) &Dealloc_;*/
9802 /* System Information {{{ */
9806 size = sizeof(maxproc);
9807 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9808 perror("sysctlbyname(\"kern.maxproc\", ?)");
9809 else if (maxproc < 64) {
9811 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9812 perror("sysctlbyname(\"kern.maxproc\", #)");
9815 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9816 char *osversion = new char[size];
9817 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9818 perror("sysctlbyname(\"kern.osversion\", ?)");
9820 System_ = [NSString stringWithUTF8String:osversion];
9822 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9823 char *machine = new char[size];
9824 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9825 perror("sysctlbyname(\"hw.machine\", ?)");
9829 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9830 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9831 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9832 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9836 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9837 NSData *data((NSData *) ecid);
9838 size_t length([data length]);
9839 uint8_t bytes[length];
9840 [data getBytes:bytes];
9841 char string[length * 2 + 1];
9842 for (size_t i(0); i != length; ++i)
9843 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9844 ChipID_ = [NSString stringWithUTF8String:string];
9848 IOObjectRelease(service);
9852 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9854 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9855 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9856 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9858 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9859 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9860 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9862 if (mcc != NULL && mnc != NULL)
9863 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9870 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9871 Build_ = [system objectForKey:@"ProductBuildVersion"];
9872 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9873 Product_ = [info objectForKey:@"SafariProductVersion"];
9874 Safari_ = [info objectForKey:@"CFBundleVersion"];
9877 /* Load Database {{{ */
9879 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9881 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9883 if (Metadata_ == NULL)
9884 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9886 Settings_ = [Metadata_ objectForKey:@"Settings"];
9888 Packages_ = [Metadata_ objectForKey:@"Packages"];
9889 Sections_ = [Metadata_ objectForKey:@"Sections"];
9890 Sources_ = [Metadata_ objectForKey:@"Sources"];
9892 Token_ = [Metadata_ objectForKey:@"Token"];
9895 if (Settings_ != nil)
9896 Role_ = [Settings_ objectForKey:@"Role"];
9898 if (Sections_ == nil) {
9899 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9900 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9903 if (Sources_ == nil) {
9904 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9905 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9910 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9913 if (Packages_ != nil) {
9915 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9919 [Metadata_ removeObjectForKey:@"Packages"];
9925 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9927 #define MobileSubstrate_(name) \
9928 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) \
9929 dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL);
9931 MobileSubstrate_(Activator)
9932 MobileSubstrate_(libstatusbar)
9933 MobileSubstrate_(SimulatedKeyEvents)
9934 MobileSubstrate_(WinterBoard)
9936 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9937 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9939 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9941 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9942 unlink("/tmp/.cydia.fw");
9944 } else if (access("/User", F_OK) != 0 || version < 2) {
9947 system("/usr/libexec/cydia/firmware.sh");
9951 _assert([[NSFileManager defaultManager]
9952 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9953 withIntermediateDirectories:YES
9958 if (access("/tmp/cydia.chk", F_OK) == 0) {
9959 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9960 _assert(errno == ENOENT);
9961 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9962 _assert(errno == ENOENT);
9965 /* APT Initialization {{{ */
9966 _assert(pkgInitConfig(*_config));
9967 _assert(pkgInitSystem(*_config, _system));
9970 _config->Set("APT::Acquire::Translation", lang);
9972 // XXX: this timeout might be important :(
9973 //_config->Set("Acquire::http::Timeout", 15);
9975 _config->Set("Acquire::http::MaxParallel", 3);
9977 /* Color Choices {{{ */
9978 space_ = CGColorSpaceCreateDeviceRGB();
9980 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9981 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9982 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9983 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9984 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9985 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9986 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9987 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9988 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9990 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9991 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9993 /* UIKit Configuration {{{ */
9994 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9995 if ($GSFontSetUseLegacyFontMetrics != NULL)
9996 $GSFontSetUseLegacyFontMetrics(YES);
9998 // XXX: I have a feeling this was important
9999 //UIKeyboardDisableAutomaticAppearance();
10002 Colon_ = UCLocalize("COLON_DELIMITED");
10003 Elision_ = UCLocalize("ELISION");
10004 Error_ = UCLocalize("ERROR");
10005 Warning_ = UCLocalize("WARNING");
10008 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10010 CGColorSpaceRelease(space_);
10011 CFRelease(Locale_);