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 - (bool) isProgressCancelled;
1201 - (void) setTitle:(NSString *)title;
1204 /* Status Delegation {{{ */
1206 public pkgAcquireStatus
1209 _transient NSObject<ProgressDelegate> *delegate_;
1219 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1220 delegate_ = delegate;
1223 NSObject<ProgressDelegate> *getDelegate() const {
1227 virtual bool MediaChange(std::string media, std::string drive) {
1231 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1234 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1235 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1236 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:@"STATUS"]);
1237 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1240 virtual void Done(pkgAcquire::ItemDesc &item) {
1243 virtual void Fail(pkgAcquire::ItemDesc &item) {
1245 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1246 item.Owner->Status == pkgAcquire::Item::StatDone
1250 std::string &error(item.Owner->ErrorText);
1254 //NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1255 //NSArray *fields([description componentsSeparatedByString:@" "]);
1256 //NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1258 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:@"ERROR"]);
1259 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1262 virtual bool Pulse(pkgAcquire *Owner) {
1263 bool value = pkgAcquireStatus::Pulse(Owner);
1266 double(CurrentBytes + CurrentItems) /
1267 double(TotalBytes + TotalItems)
1270 [delegate_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:percent] waitUntilDone:YES];
1271 if (value && ![delegate_ isProgressCancelled])
1279 _finline bool WasCancelled() const {
1283 virtual void Start() {
1284 pkgAcquireStatus::Start();
1287 virtual void Stop() {
1288 pkgAcquireStatus::Stop();
1292 /* Database Interface {{{ */
1293 typedef std::map< unsigned long, _H<Source> > SourceMap;
1295 @interface Database : NSObject {
1301 pkgCacheFile cache_;
1302 pkgDepCache::Policy *policy_;
1303 pkgRecords *records_;
1304 pkgProblemResolver *resolver_;
1305 pkgAcquire *fetcher_;
1307 SPtr<pkgPackageManager> manager_;
1308 pkgSourceList *list_;
1310 SourceMap sourceMap_;
1311 NSMutableArray *sourceList_;
1313 CFMutableArrayRef packages_;
1315 _transient NSObject<DatabaseDelegate> *delegate_;
1316 _transient NSObject<ProgressDelegate> *progress_;
1324 std::map<const char *, _H<NSString> > sections_;
1327 + (Database *) sharedInstance;
1330 - (void) _readCydia:(NSNumber *)fd;
1331 - (void) _readStatus:(NSNumber *)fd;
1332 - (void) _readOutput:(NSNumber *)fd;
1336 - (Package *) packageWithName:(NSString *)name;
1338 - (pkgCacheFile &) cache;
1339 - (pkgDepCache::Policy *) policy;
1340 - (pkgRecords *) records;
1341 - (pkgProblemResolver *) resolver;
1342 - (pkgAcquire &) fetcher;
1343 - (pkgSourceList &) list;
1344 - (NSArray *) packages;
1345 - (NSArray *) sources;
1346 - (Source *) sourceWithKey:(NSString *)key;
1347 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1355 - (void) updateWithStatus:(Status &)status;
1357 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1359 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1360 - (NSObject<ProgressDelegate> *) progressDelegate;
1362 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1364 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1368 /* ProgressEvent Implementation {{{ */
1369 @implementation CydiaProgressEvent
1371 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1372 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1375 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1376 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1377 [event setPackage:package];
1381 + (NSArray *) _attributeKeys {
1382 return [NSArray arrayWithObjects:
1390 - (NSArray *) attributeKeys {
1391 return [[self class] _attributeKeys];
1394 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1395 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1398 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1399 if ((self = [super init]) != nil) {
1405 - (NSString *) message {
1409 - (NSString *) type {
1413 - (NSString *) package {
1417 - (NSString *) uri {
1421 - (void) setPackage:(NSString *)package {
1425 - (NSString *) compound:(NSString *)value {
1427 NSString *mode(nil); {
1428 NSString *type([self type]);
1429 if ([type isEqualToString:@"ERROR"])
1430 mode = UCLocalize("ERROR");
1431 else if ([type isEqualToString:@"WARNING"])
1432 mode = UCLocalize("WARNING");
1436 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1442 - (NSString *) compoundMessage {
1443 return [self compound:[self message]];
1446 - (NSString *) compoundTitle {
1449 if (package_ == nil)
1451 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1452 title = [package name];
1456 return [self compound:title];
1462 // Cytore Definitions {{{
1463 struct PackageValue :
1466 Cytore::Offset<PackageValue> next_;
1468 uint32_t index_ : 23;
1469 uint32_t subscribed_ : 1;
1486 Cytore::Offset<PackageValue> packages_[1 << 16];
1489 static Cytore::File<MetaValue> MetaFile_;
1491 // Cytore Helper Functions {{{
1492 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1493 SplitHash nhash = { hashlittle(name, length) };
1495 PackageValue *metadata;
1497 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1498 offset: if (offset->IsNull()) {
1499 *offset = MetaFile_.New<PackageValue>(length + 1);
1500 metadata = &MetaFile_.Get(*offset);
1502 if (metadata == NULL) {
1506 metadata = new PackageValue();
1507 memset(metadata, 0, sizeof(*metadata));
1510 memcpy(metadata->name_, name, length + 1);
1511 metadata->nhash_ = nhash.u16[1];
1513 metadata = &MetaFile_.Get(*offset);
1515 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1516 offset = &metadata->next_;
1524 static void PackageImport(const void *key, const void *value, void *context) {
1525 bool &fail(*reinterpret_cast<bool *>(context));
1528 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1529 NSLog(@"failed to import package %@", key);
1533 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1534 NSDictionary *package((NSDictionary *) value);
1536 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1537 if ([subscribed boolValue] && !metadata->subscribed_)
1538 metadata->subscribed_ = true;
1540 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1541 time_t time([date timeIntervalSince1970]);
1542 if (metadata->first_ > time || metadata->first_ == 0)
1543 metadata->first_ = time;
1546 NSDate *date([package objectForKey:@"LastSeen"]);
1547 NSString *version([package objectForKey:@"LastVersion"]);
1549 if (date != nil && version != nil) {
1550 time_t time([date timeIntervalSince1970]);
1551 if (metadata->last_ < time || metadata->last_ == 0)
1552 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1553 size_t length(strlen(buffer));
1554 uint16_t vhash(hashlittle(buffer, length));
1556 size_t capped(std::min<size_t>(8, length));
1557 char *latest(buffer + length - capped);
1559 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1560 metadata->vhash_ = vhash;
1562 metadata->last_ = time;
1568 /* Source Class {{{ */
1569 @interface Source : NSObject {
1570 CYString depiction_;
1571 CYString description_;
1577 CYString distribution_;
1582 NSString *authority_;
1584 CYString defaultIcon_;
1586 NSDictionary *record_;
1590 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1592 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1594 - (NSString *) depictionForPackage:(NSString *)package;
1595 - (NSString *) supportForPackage:(NSString *)package;
1597 - (NSDictionary *) record;
1601 - (NSString *) distribution;
1602 - (NSString *) type;
1604 - (NSString *) host;
1606 - (NSString *) name;
1607 - (NSString *) description;
1608 - (NSString *) label;
1609 - (NSString *) origin;
1610 - (NSString *) version;
1612 - (NSString *) defaultIcon;
1616 @implementation Source
1620 distribution_.clear();
1623 description_.clear();
1629 defaultIcon_.clear();
1631 if (record_ != nil) {
1641 if (authority_ != nil) {
1642 [authority_ release];
1648 // XXX: this is a very inefficient way to call these deconstructors
1653 + (NSArray *) _attributeKeys {
1654 return [NSArray arrayWithObjects:
1669 - (NSArray *) attributeKeys {
1670 return [[self class] _attributeKeys];
1673 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1674 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1677 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1680 trusted_ = index->IsTrusted();
1682 uri_.set(pool, index->GetURI());
1683 distribution_.set(pool, index->GetDist());
1684 type_.set(pool, index->GetType());
1686 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1687 if (dindex != NULL) {
1689 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1692 pkgTagFile tags(&fd);
1694 pkgTagSection section;
1701 {"default-icon", &defaultIcon_},
1702 {"depiction", &depiction_},
1703 {"description", &description_},
1705 {"origin", &origin_},
1706 {"support", &support_},
1707 {"version", &version_},
1710 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1711 const char *start, *end;
1713 if (section.Find(names[i].name_, start, end)) {
1714 CYString &value(*names[i].value_);
1715 value.set(pool, start, end - start);
1721 record_ = [Sources_ objectForKey:[self key]];
1723 record_ = [record_ retain];
1725 NSURL *url([NSURL URLWithString:uri_]);
1729 host_ = [[host_ lowercaseString] retain];
1734 authority_ = [url path];
1736 if (authority_ != nil)
1737 authority_ = [authority_ retain];
1740 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1741 if ((self = [super init]) != nil) {
1742 [self setMetaIndex:index inPool:pool];
1746 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1747 NSDictionary *lhr = [self record];
1748 NSDictionary *rhr = [source record];
1751 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1753 NSString *lhs = [self name];
1754 NSString *rhs = [source name];
1756 if ([lhs length] != 0 && [rhs length] != 0) {
1757 unichar lhc = [lhs characterAtIndex:0];
1758 unichar rhc = [rhs characterAtIndex:0];
1760 if (isalpha(lhc) && !isalpha(rhc))
1761 return NSOrderedAscending;
1762 else if (!isalpha(lhc) && isalpha(rhc))
1763 return NSOrderedDescending;
1766 return [lhs compare:rhs options:LaxCompareOptions_];
1769 - (NSString *) depictionForPackage:(NSString *)package {
1770 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1773 - (NSString *) supportForPackage:(NSString *)package {
1774 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1777 - (NSDictionary *) record {
1785 - (NSString *) uri {
1789 - (NSString *) distribution {
1790 return distribution_;
1793 - (NSString *) type {
1797 - (NSString *) key {
1798 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1801 - (NSString *) host {
1805 - (NSString *) name {
1806 return origin_.empty() ? authority_ : origin_;
1809 - (NSString *) description {
1810 return description_;
1813 - (NSString *) label {
1814 return label_.empty() ? authority_ : label_;
1817 - (NSString *) origin {
1821 - (NSString *) version {
1825 - (NSString *) defaultIcon {
1826 return defaultIcon_;
1831 /* CydiaOperation Class {{{ */
1832 @interface CydiaOperation : NSObject {
1833 NSString *operator_;
1837 - (NSString *) operator;
1838 - (NSString *) value;
1842 @implementation CydiaOperation
1845 [operator_ release];
1850 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1851 if ((self = [super init]) != nil) {
1852 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1853 value_ = [[NSString alloc] initWithUTF8String:value];
1857 + (NSArray *) _attributeKeys {
1858 return [NSArray arrayWithObjects:
1864 - (NSArray *) attributeKeys {
1865 return [[self class] _attributeKeys];
1868 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1869 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1872 - (NSString *) operator {
1876 - (NSString *) value {
1882 /* CydiaClause Class {{{ */
1883 @interface CydiaClause : NSObject {
1885 CydiaOperation *version_;
1888 - (NSString *) package;
1889 - (CydiaOperation *) version;
1893 @implementation CydiaClause
1901 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1902 if ((self = [super init]) != nil) {
1903 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1905 if (const char *version = dep.TargetVer())
1906 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1908 version_ = [[NSNull null] retain];
1912 + (NSArray *) _attributeKeys {
1913 return [NSArray arrayWithObjects:
1919 - (NSArray *) attributeKeys {
1920 return [[self class] _attributeKeys];
1923 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1924 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1927 - (NSString *) package {
1931 - (CydiaOperation *) version {
1937 /* CydiaRelation Class {{{ */
1938 @interface CydiaRelation : NSObject {
1939 NSString *relationship_;
1940 NSMutableArray *clauses_;
1943 - (NSString *) relationship;
1944 - (NSArray *) clauses;
1948 @implementation CydiaRelation
1951 [relationship_ release];
1956 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1957 if ((self = [super init]) != nil) {
1958 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1959 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1961 pkgCache::DepIterator start;
1962 pkgCache::DepIterator end;
1963 dep.GlobOr(start, end); // ++dep
1966 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1968 // yes, seriously. (wtf?)
1976 + (NSArray *) _attributeKeys {
1977 return [NSArray arrayWithObjects:
1983 - (NSArray *) attributeKeys {
1984 return [[self class] _attributeKeys];
1987 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1988 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1991 - (NSString *) relationship {
1992 return relationship_;
1995 - (NSArray *) clauses {
1999 - (void) addClause:(CydiaClause *)clause {
2000 [clauses_ addObject:clause];
2005 /* Package Class {{{ */
2006 struct ParsedPackage {
2011 CYString depiction_;
2021 @interface Package : NSObject {
2024 uint32_t essential_ : 1;
2025 uint32_t obsolete_ : 1;
2026 uint32_t ignored_ : 1;
2030 _transient Database *database_;
2032 pkgCache::VerIterator version_;
2033 pkgCache::PkgIterator iterator_;
2034 pkgCache::VerFileIterator file_;
2040 CYString installed_;
2042 const char *section_;
2043 _transient NSString *section$_;
2047 PackageValue *metadata_;
2048 ParsedPackage *parsed_;
2050 NSMutableArray *tags_;
2053 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2054 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2056 - (pkgCache::PkgIterator) iterator;
2059 - (NSString *) section;
2060 - (NSString *) simpleSection;
2062 - (NSString *) longSection;
2063 - (NSString *) shortSection;
2067 - (Address *) maintainer;
2069 - (NSString *) longDescription;
2070 - (NSString *) shortDescription;
2073 - (PackageValue *) metadata;
2076 - (bool) subscribed;
2077 - (bool) setSubscribed:(bool)subscribed;
2081 - (NSString *) latest;
2082 - (NSString *) installed;
2083 - (BOOL) uninstalled;
2086 - (BOOL) upgradableAndEssential:(BOOL)essential;
2089 - (BOOL) unfiltered;
2093 - (BOOL) halfConfigured;
2094 - (BOOL) halfInstalled;
2096 - (NSString *) mode;
2099 - (NSString *) name;
2101 - (NSString *) homepage;
2102 - (NSString *) depiction;
2103 - (Address *) author;
2105 - (NSString *) support;
2107 - (NSArray *) files;
2108 - (NSArray *) warnings;
2109 - (NSArray *) applications;
2111 - (Source *) source;
2113 - (BOOL) matches:(NSString *)text;
2115 - (bool) hasSupportingRole;
2116 - (BOOL) hasTag:(NSString *)tag;
2117 - (NSString *) primaryPurpose;
2118 - (NSArray *) purposes;
2119 - (bool) isCommercial;
2121 - (void) setIndex:(size_t)index;
2123 - (CYString &) cyname;
2125 - (uint32_t) compareBySection:(NSArray *)sections;
2130 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2131 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2132 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2133 - (bool) isVisibleInSection:(NSString *)section;
2134 - (bool) isVisibleInSource:(Source *)source;
2138 uint32_t PackageChangesRadix(Package *self, void *) {
2143 uint32_t timestamp : 30;
2144 uint32_t ignored : 1;
2145 uint32_t upgradable : 1;
2149 bool upgradable([self upgradableAndEssential:YES]);
2150 value.bits.upgradable = upgradable ? 1 : 0;
2153 value.bits.timestamp = 0;
2154 value.bits.ignored = [self ignored] ? 0 : 1;
2155 value.bits.upgradable = 1;
2157 value.bits.timestamp = [self seen] >> 2;
2158 value.bits.ignored = 0;
2159 value.bits.upgradable = 0;
2162 return _not(uint32_t) - value.key;
2165 uint32_t PackagePrefixRadix(Package *self, void *context) {
2166 size_t offset(reinterpret_cast<size_t>(context));
2167 CYString &name([self cyname]);
2169 size_t size(name.size());
2172 char *text(name.data());
2175 if (!isdigit(text[0]))
2179 while (size != digits && isdigit(text[digits]))
2187 if (offset == 0 && zeros != 0) {
2188 memset(data, '0', zeros);
2189 memcpy(data + zeros, text, 4 - zeros);
2191 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2192 if (size <= offset - zeros)
2195 text += offset - zeros;
2196 size -= offset - zeros;
2199 memcpy(data, text, 4);
2201 memcpy(data, text, size);
2202 memset(data + size, 0, 4 - size);
2205 for (size_t i(0); i != 4; ++i)
2206 if (isalpha(data[i]))
2214 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2216 /* XXX: ntohl may be more honest */
2217 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2220 CYString &(*PackageName)(Package *self, SEL sel);
2222 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2223 _profile(PackageNameCompare)
2224 CYString &lhi(PackageName(lhs, @selector(cyname)));
2225 CYString &rhi(PackageName(rhs, @selector(cyname)));
2226 CFStringRef lhn(lhi), rhn(rhi);
2229 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2230 else if (rhn == NULL)
2231 return NSOrderedDescending;
2233 _profile(PackageNameCompare$NumbersLast)
2234 if (!lhi.empty() && !rhi.empty()) {
2235 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2236 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2237 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2238 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2239 return lha ? NSOrderedAscending : NSOrderedDescending;
2243 CFIndex length = CFStringGetLength(lhn);
2245 _profile(PackageNameCompare$Compare)
2246 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2251 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2252 return PackageNameCompare(*lhs, *rhs, context);
2255 struct PackageNameOrdering :
2256 std::binary_function<Package *, Package *, bool>
2258 _finline bool operator ()(Package *lhs, Package *rhs) const {
2259 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2263 @implementation Package
2265 - (NSString *) description {
2266 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2270 if (parsed_ != NULL)
2279 + (NSString *) webScriptNameForSelector:(SEL)selector {
2281 else if (selector == @selector(clear))
2283 else if (selector == @selector(getField:))
2285 else if (selector == @selector(hasTag:))
2287 else if (selector == @selector(install))
2289 else if (selector == @selector(remove))
2295 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2296 return [self webScriptNameForSelector:selector] == nil;
2299 + (NSArray *) _attributeKeys {
2300 return [NSArray arrayWithObjects:
2318 @"shortDescription",
2329 - (NSArray *) attributeKeys {
2330 return [[self class] _attributeKeys];
2333 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2334 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2337 - (NSArray *) relations {
2338 @synchronized (database_) {
2339 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2340 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2341 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2345 - (NSString *) getField:(NSString *)name {
2346 @synchronized (database_) {
2347 if ([database_ era] != era_ || file_.end())
2350 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2352 const char *start, *end;
2353 if (!parser.Find([name UTF8String], start, end))
2354 return (NSString *) [NSNull null];
2356 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2360 if (parsed_ != NULL)
2362 @synchronized (database_) {
2363 if ([database_ era] != era_ || file_.end())
2366 ParsedPackage *parsed(new ParsedPackage);
2369 _profile(Package$parse)
2370 pkgRecords::Parser *parser;
2372 _profile(Package$parse$Lookup)
2373 parser = &[database_ records]->Lookup(file_);
2378 _profile(Package$parse$Find)
2383 {"icon", &parsed->icon_},
2384 {"depiction", &parsed->depiction_},
2385 {"homepage", &parsed->homepage_},
2386 {"website", &website},
2387 {"bugs", &parsed->bugs_},
2388 {"support", &parsed->support_},
2389 {"sponsor", &parsed->sponsor_},
2390 {"author", &parsed->author_},
2393 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2394 const char *start, *end;
2396 if (parser->Find(names[i].name_, start, end)) {
2397 CYString &value(*names[i].value_);
2398 _profile(Package$parse$Value)
2399 value.set(pool_, start, end - start);
2405 _profile(Package$parse$Tagline)
2406 const char *start, *end;
2407 if (parser->ShortDesc(start, end)) {
2408 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2411 while (stop != start && stop[-1] == '\r')
2413 parsed->tagline_.set(pool_, start, stop - start);
2417 _profile(Package$parse$Retain)
2418 if (parsed->homepage_.empty())
2419 parsed->homepage_ = website;
2420 if (parsed->homepage_ == parsed->depiction_)
2421 parsed->homepage_.clear();
2426 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2427 if ((self = [super init]) != nil) {
2428 _profile(Package$initWithVersion)
2431 database_ = database;
2432 era_ = [database era];
2436 pkgCache::PkgIterator iterator(version.ParentPkg());
2437 iterator_ = iterator;
2439 _profile(Package$initWithVersion$Version)
2440 if (!version_.end())
2441 file_ = version_.FileList();
2443 pkgCache &cache([database_ cache]);
2444 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2448 _profile(Package$initWithVersion$Cache)
2449 name_.set(NULL, iterator.Display());
2451 latest_.set(NULL, StripVersion_(version_.VerStr()));
2453 pkgCache::VerIterator current(iterator.CurrentVer());
2455 installed_.set(NULL, StripVersion_(current.VerStr()));
2458 _profile(Package$initWithVersion$Tags)
2459 pkgCache::TagIterator tag(iterator.TagList());
2461 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2463 const char *name(tag.Name());
2464 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2466 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2467 if (strcmp(name + 6, "enduser") == 0)
2469 else if (strcmp(name + 6, "hacker") == 0)
2471 else if (strcmp(name + 6, "developer") == 0)
2473 else if (strcmp(name + 6, "cydia") == 0)
2479 if (strncmp(name, "cydia::", 7) == 0) {
2480 if (strcmp(name + 7, "essential") == 0)
2482 else if (strcmp(name + 7, "obsolete") == 0)
2487 } while (!tag.end());
2491 _profile(Package$initWithVersion$Metadata)
2492 const char *mixed(iterator.Name());
2493 size_t size(strlen(mixed));
2494 char lower[size + 1];
2496 for (size_t i(0); i != size; ++i)
2497 lower[i] = mixed[i] | 0x20;
2500 PackageValue *metadata(PackageFind(lower, size));
2501 metadata_ = metadata;
2503 id_.set(NULL, metadata->name_, size);
2505 const char *latest(version_.VerStr());
2506 size_t length(strlen(latest));
2508 uint16_t vhash(hashlittle(latest, length));
2510 size_t capped(std::min<size_t>(8, length));
2511 latest = latest + length - capped;
2513 if (metadata->first_ == 0)
2514 metadata->first_ = now_;
2516 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2517 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2518 metadata->vhash_ = vhash;
2519 metadata->last_ = now_;
2520 } else if (metadata->last_ == 0)
2521 metadata->last_ = metadata->first_;
2524 _profile(Package$initWithVersion$Section)
2525 section_ = iterator.Section();
2528 _profile(Package$initWithVersion$Flags)
2529 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2530 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2535 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2536 pkgCache::VerIterator version;
2538 _profile(Package$packageWithIterator$GetCandidateVer)
2539 version = [database policy]->GetCandidateVer(iterator);
2547 _profile(Package$packageWithIterator$Allocate)
2548 package = [Package allocWithZone:zone];
2551 _profile(Package$packageWithIterator$Initialize)
2553 initWithVersion:version
2560 _profile(Package$packageWithIterator$Autorelease)
2561 package = [package autorelease];
2567 - (pkgCache::PkgIterator) iterator {
2571 - (NSString *) section {
2572 if (section$_ == nil) {
2573 if (section_ == NULL)
2576 _profile(Package$section$mappedSectionForPointer)
2577 section$_ = [database_ mappedSectionForPointer:section_];
2582 - (NSString *) simpleSection {
2583 if (NSString *section = [self section])
2584 return Simplify(section);
2589 - (NSString *) longSection {
2590 return LocalizeSection([self section]);
2593 - (NSString *) shortSection {
2594 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2597 - (NSString *) uri {
2600 pkgIndexFile *index;
2601 pkgCache::PkgFileIterator file(file_.File());
2602 if (![database_ list].FindIndex(file, index))
2604 return [NSString stringWithUTF8String:iterator_->Path];
2605 //return [NSString stringWithUTF8String:file.Site()];
2606 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2610 - (Address *) maintainer {
2611 @synchronized (database_) {
2612 if ([database_ era] != era_ || file_.end())
2615 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2616 const std::string &maintainer(parser->Maintainer());
2617 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2621 @synchronized (database_) {
2622 if ([database_ era] != era_ || version_.end())
2625 return version_->InstalledSize;
2628 - (NSString *) longDescription {
2629 @synchronized (database_) {
2630 if ([database_ era] != era_ || file_.end())
2633 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2634 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2636 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2637 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2638 if ([lines count] < 2)
2641 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2642 for (size_t i(1), e([lines count]); i != e; ++i) {
2643 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2644 [trimmed addObject:trim];
2647 return [trimmed componentsJoinedByString:@"\n"];
2650 - (NSString *) shortDescription {
2651 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2655 _profile(Package$index)
2656 CFStringRef name((CFStringRef) [self name]);
2657 if (CFStringGetLength(name) == 0)
2659 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2660 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2662 return toupper(character);
2666 - (PackageValue *) metadata {
2671 PackageValue *metadata([self metadata]);
2672 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2675 - (bool) subscribed {
2676 return [self metadata]->subscribed_;
2679 - (bool) setSubscribed:(bool)subscribed {
2680 PackageValue *metadata([self metadata]);
2681 if (metadata->subscribed_ == subscribed)
2683 metadata->subscribed_ = subscribed;
2691 - (NSString *) latest {
2695 - (NSString *) installed {
2699 - (BOOL) uninstalled {
2700 return installed_.empty();
2704 return !version_.end();
2707 - (BOOL) upgradableAndEssential:(BOOL)essential {
2708 _profile(Package$upgradableAndEssential)
2709 pkgCache::VerIterator current(iterator_.CurrentVer());
2711 return essential && essential_;
2713 return !version_.end() && version_ != current;
2717 - (BOOL) essential {
2722 return [database_ cache][iterator_].InstBroken();
2725 - (BOOL) unfiltered {
2726 _profile(Package$unfiltered$obsolete)
2727 if (_unlikely(obsolete_))
2731 _profile(Package$unfiltered$hasSupportingRole)
2732 if (_unlikely(![self hasSupportingRole]))
2740 if (![self unfiltered])
2745 _profile(Package$visible$section)
2746 section = [self section];
2749 _profile(Package$visible$isSectionVisible)
2750 if (!isSectionVisible(section))
2758 unsigned char current(iterator_->CurrentState);
2759 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2762 - (BOOL) halfConfigured {
2763 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2766 - (BOOL) halfInstalled {
2767 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2771 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2772 return state.Mode != pkgDepCache::ModeKeep;
2775 - (NSString *) mode {
2776 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2778 switch (state.Mode) {
2779 case pkgDepCache::ModeDelete:
2780 if ((state.iFlags & pkgDepCache::Purge) != 0)
2784 case pkgDepCache::ModeKeep:
2785 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2786 return @"REINSTALL";
2787 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2791 case pkgDepCache::ModeInstall:
2792 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2793 return @"REINSTALL";
2794 else*/ switch (state.Status) {
2796 return @"DOWNGRADE";
2802 return @"NEW_INSTALL";
2813 - (NSString *) name {
2814 return name_.empty() ? id_ : name_;
2817 - (UIImage *) icon {
2818 NSString *section = [self simpleSection];
2821 if (parsed_ != NULL)
2822 if (NSString *href = parsed_->icon_)
2823 if ([href hasPrefix:@"file:///"])
2824 // XXX: correct escaping
2825 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2826 if (icon == nil) if (section != nil)
2827 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2828 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2829 if ([dicon hasPrefix:@"file:///"])
2830 // XXX: correct escaping
2831 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2833 icon = [UIImage applicationImageNamed:@"unknown.png"];
2837 - (NSString *) homepage {
2838 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2841 - (NSString *) depiction {
2842 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2845 - (Address *) sponsor {
2846 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2849 - (Address *) author {
2850 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2853 - (NSString *) support {
2854 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2857 - (NSArray *) files {
2858 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2859 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2862 fin.open([path UTF8String]);
2867 while (std::getline(fin, line))
2868 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2873 - (NSArray *) warnings {
2874 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2875 const char *name(iterator_.Name());
2877 size_t length(strlen(name));
2878 if (length < 2) invalid:
2879 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2880 else for (size_t i(0); i != length; ++i)
2882 /* XXX: technically this is not allowed */
2883 (name[i] < 'A' || name[i] > 'Z') &&
2884 (name[i] < 'a' || name[i] > 'z') &&
2885 (name[i] < '0' || name[i] > '9') &&
2886 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2889 if (strcmp(name, "cydia") != 0) {
2892 bool _private = false;
2895 bool repository = [[self section] isEqualToString:@"Repositories"];
2897 if (NSArray *files = [self files])
2898 for (NSString *file in files)
2899 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2901 else if (!user && [file isEqualToString:@"/User"])
2903 else if (!_private && [file isEqualToString:@"/private"])
2905 else if (!stash && [file isEqualToString:@"/var/stash"])
2908 /* XXX: this is not sensitive enough. only some folders are valid. */
2909 if (cydia && !repository)
2910 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2912 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2914 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2916 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2919 return [warnings count] == 0 ? nil : warnings;
2922 - (NSArray *) applications {
2923 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2925 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2927 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2928 if (NSArray *files = [self files])
2929 for (NSString *file in files)
2930 if (application_r(file)) {
2931 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2932 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2933 if ([id isEqualToString:me])
2936 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2938 display = application_r[1];
2940 NSString *bundle([file stringByDeletingLastPathComponent]);
2941 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2942 if (icon == nil || [icon length] == 0)
2944 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2946 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2947 [applications addObject:application];
2949 [application addObject:id];
2950 [application addObject:display];
2951 [application addObject:url];
2954 return [applications count] == 0 ? nil : applications;
2957 - (Source *) source {
2958 if (source_ == nil) {
2959 @synchronized (database_) {
2960 if ([database_ era] != era_ || file_.end())
2961 source_ = (Source *) [NSNull null];
2963 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2967 return source_ == (Source *) [NSNull null] ? nil : source_;
2970 - (BOOL) matches:(NSString *)text {
2976 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2977 if (range.location != NSNotFound)
2980 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2981 if (range.location != NSNotFound)
2986 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2987 if (range.location != NSNotFound)
2993 - (bool) hasSupportingRole {
2998 if ([Role_ isEqualToString:@"User"])
3002 if ([Role_ isEqualToString:@"Hacker"])
3006 if ([Role_ isEqualToString:@"Developer"])
3011 - (BOOL) hasTag:(NSString *)tag {
3012 return tags_ == nil ? NO : [tags_ containsObject:tag];
3015 - (NSString *) primaryPurpose {
3016 for (NSString *tag in tags_)
3017 if ([tag hasPrefix:@"purpose::"])
3018 return [tag substringFromIndex:9];
3022 - (NSArray *) purposes {
3023 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3024 for (NSString *tag in tags_)
3025 if ([tag hasPrefix:@"purpose::"])
3026 [purposes addObject:[tag substringFromIndex:9]];
3027 return [purposes count] == 0 ? nil : purposes;
3030 - (bool) isCommercial {
3031 return [self hasTag:@"cydia::commercial"];
3034 - (void) setIndex:(size_t)index {
3035 if (metadata_->index_ != index)
3036 metadata_->index_ = index;
3039 - (CYString &) cyname {
3040 return name_.empty() ? id_ : name_;
3043 - (uint32_t) compareBySection:(NSArray *)sections {
3044 NSString *section([self section]);
3045 for (size_t i(0), e([sections count]); i != e; ++i) {
3046 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3050 return _not(uint32_t);
3054 @synchronized (database_) {
3055 pkgProblemResolver *resolver = [database_ resolver];
3056 resolver->Clear(iterator_);
3058 pkgCacheFile &cache([database_ cache]);
3059 cache->SetReInstall(iterator_, false);
3060 cache->MarkKeep(iterator_, false);
3064 @synchronized (database_) {
3065 pkgProblemResolver *resolver = [database_ resolver];
3066 resolver->Clear(iterator_);
3067 resolver->Protect(iterator_);
3069 pkgCacheFile &cache([database_ cache]);
3070 cache->SetReInstall(iterator_, false);
3071 cache->MarkInstall(iterator_, false);
3073 pkgDepCache::StateCache &state((*cache)[iterator_]);
3074 if (!state.Install())
3075 cache->SetReInstall(iterator_, true);
3079 @synchronized (database_) {
3080 pkgProblemResolver *resolver = [database_ resolver];
3081 resolver->Clear(iterator_);
3082 resolver->Remove(iterator_);
3083 resolver->Protect(iterator_);
3085 pkgCacheFile &cache([database_ cache]);
3086 cache->SetReInstall(iterator_, false);
3087 cache->MarkDelete(iterator_, true);
3090 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3091 _profile(Package$isUnfilteredAndSearchedForBy)
3094 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3095 value &= [self unfiltered];
3098 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3099 value &= [self matches:search];
3106 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3107 if ([search length] == 0)
3110 _profile(Package$isUnfilteredAndSelectedForBy)
3113 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3114 value &= [self unfiltered];
3117 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3118 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3125 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3126 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3129 - (bool) isVisibleInSection:(NSString *)name {
3130 NSString *section([self section]);
3134 section == nil && [name length] == 0 ||
3135 [name isEqualToString:section]
3136 ) && [self visible];
3139 - (bool) isVisibleInSource:(Source *)source {
3140 return [self source] == source && [self visible];
3145 /* Section Class {{{ */
3146 @interface Section : NSObject {
3151 NSString *localized_;
3154 - (NSComparisonResult) compareByLocalized:(Section *)section;
3155 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3156 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3157 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3158 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3159 - (NSString *) name;
3166 - (void) addToCount;
3168 - (void) setCount:(size_t)count;
3169 - (NSString *) localized;
3173 @implementation Section
3177 if (localized_ != nil)
3178 [localized_ release];
3182 - (NSComparisonResult) compareByLocalized:(Section *)section {
3183 NSString *lhs(localized_);
3184 NSString *rhs([section localized]);
3186 /*if ([lhs length] != 0 && [rhs length] != 0) {
3187 unichar lhc = [lhs characterAtIndex:0];
3188 unichar rhc = [rhs characterAtIndex:0];
3190 if (isalpha(lhc) && !isalpha(rhc))
3191 return NSOrderedAscending;
3192 else if (!isalpha(lhc) && isalpha(rhc))
3193 return NSOrderedDescending;
3196 return [lhs compare:rhs options:LaxCompareOptions_];
3199 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3200 if ((self = [self initWithName:name localize:NO]) != nil) {
3201 if (localized != nil)
3202 localized_ = [localized retain];
3206 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3207 return [self initWithName:name row:0 localize:localize];
3210 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3211 if ((self = [super init]) != nil) {
3212 name_ = [name retain];
3216 localized_ = [LocalizeSection(name_) retain];
3220 /* XXX: localize the index thingees */
3221 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3222 if ((self = [super init]) != nil) {
3223 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3229 - (NSString *) name {
3249 - (void) addToCount {
3253 - (void) setCount:(size_t)count {
3257 - (NSString *) localized {
3264 static NSString *Colon_;
3265 static NSString *Elision_;
3266 static NSString *Error_;
3267 static NSString *Warning_;
3269 /* Database Implementation {{{ */
3270 @implementation Database
3272 + (Database *) sharedInstance {
3273 static Database *instance;
3274 if (instance == nil)
3275 instance = [[Database alloc] init];
3283 - (void) releasePackages {
3284 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3285 CFArrayRemoveAllValues(packages_);
3289 // XXX: actually implement this thing
3291 [sourceList_ release];
3292 [self releasePackages];
3293 apr_pool_destroy(pool_);
3294 NSRecycleZone(zone_);
3298 - (void) _readCydia:(NSNumber *)fd { _pooled
3299 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3300 std::istream is(&ib);
3303 static Pcre finish_r("^finish:([^:]*)$");
3305 while (std::getline(is, line)) {
3306 const char *data(line.c_str());
3307 size_t size = line.size();
3308 lprintf("C:%s\n", data);
3310 if (finish_r(data, size)) {
3311 NSString *finish = finish_r[1];
3312 int index = [Finishes_ indexOfObject:finish];
3313 if (index != INT_MAX && index > Finish_)
3321 - (void) _readStatus:(NSNumber *)fd { _pooled
3322 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3323 std::istream is(&ib);
3326 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3327 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3329 while (std::getline(is, line)) {
3330 const char *data(line.c_str());
3331 size_t size(line.size());
3332 lprintf("S:%s\n", data);
3334 if (conffile_r(data, size))
3335 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3336 else if (strncmp(data, "status: ", 8) == 0) {
3337 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:@"STATUS"]);
3338 [progress_ performSelectorOnMainThread:@selector(addProgressEvent) withObject:event waitUntilDone:YES];
3339 } else if (pmstatus_r(data, size)) {
3340 std::string type([pmstatus_r[1] UTF8String]);
3341 NSString *package = pmstatus_r[2];
3343 float percent([pmstatus_r[3] floatValue]);
3344 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3346 NSString *string = pmstatus_r[4];
3348 if (type == "pmerror") {
3349 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"ERROR" forPackage:package]);
3350 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3351 } else if (type == "pmstatus") {
3352 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"STATUS" forPackage:package]);
3353 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3354 } else if (type == "pmconffile")
3355 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3357 lprintf("E:unknown pmstatus\n");
3359 lprintf("E:unknown status\n");
3365 - (void) _readOutput:(NSNumber *)fd { _pooled
3366 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3367 std::istream is(&ib);
3370 while (std::getline(is, line)) {
3371 lprintf("O:%s\n", line.c_str());
3373 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:@"INFORMATION"]);
3374 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3384 - (Package *) packageWithName:(NSString *)name {
3385 @synchronized (self) {
3386 if (static_cast<pkgDepCache *>(cache_) == NULL)
3388 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3389 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3393 if ((self = [super init]) != nil) {
3400 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3401 apr_pool_create(&pool_, NULL);
3403 size_t capacity(MetaFile_->active_);
3409 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3410 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3414 _assert(pipe(fds) != -1);
3417 _config->Set("APT::Keep-Fds::", cydiafd_);
3418 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3421 detachNewThreadSelector:@selector(_readCydia:)
3423 withObject:[NSNumber numberWithInt:fds[0]]
3426 _assert(pipe(fds) != -1);
3430 detachNewThreadSelector:@selector(_readStatus:)
3432 withObject:[NSNumber numberWithInt:fds[0]]
3435 _assert(pipe(fds) != -1);
3436 _assert(dup2(fds[0], 0) != -1);
3437 _assert(close(fds[0]) != -1);
3439 input_ = fdopen(fds[1], "a");
3441 _assert(pipe(fds) != -1);
3442 _assert(dup2(fds[1], 1) != -1);
3443 _assert(close(fds[1]) != -1);
3446 detachNewThreadSelector:@selector(_readOutput:)
3448 withObject:[NSNumber numberWithInt:fds[0]]
3453 - (pkgCacheFile &) cache {
3457 - (pkgDepCache::Policy *) policy {
3461 - (pkgRecords *) records {
3465 - (pkgProblemResolver *) resolver {
3469 - (pkgAcquire &) fetcher {
3473 - (pkgSourceList &) list {
3477 - (NSArray *) packages {
3478 return (NSArray *) packages_;
3481 - (NSArray *) sources {
3485 - (Source *) sourceWithKey:(NSString *)key {
3486 for (Source *source in [self sources]) {
3487 if ([[source key] isEqualToString:key])
3492 - (bool) popErrorWithTitle:(NSString *)title {
3495 while (!_error->empty()) {
3497 bool warning(!_error->PopMessage(error));
3502 size_t size(error.size());
3503 if (size == 0 || error[size - 1] != '\n')
3505 error.resize(size - 1);
3508 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3510 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3516 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3517 return [self popErrorWithTitle:title] || !success;
3520 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3521 @synchronized (self) {
3524 [self releasePackages];
3527 [sourceList_ removeAllObjects];
3547 apr_pool_clear(pool_);
3549 NSRecycleZone(zone_);
3550 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3552 int chk(creat("/tmp/cydia.chk", 0644));
3556 if (invocation != nil)
3557 [invocation invoke];
3559 NSString *title(UCLocalize("DATABASE"));
3562 OpProgress progress;
3563 while (!cache_.Open(progress, true)) { pop:
3565 bool warning(!_error->PopMessage(error));
3566 lprintf("cache_.Open():[%s]\n", error.c_str());
3568 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3569 [delegate_ repairWithSelector:@selector(configure)];
3570 else if (error == "The package lists or status file could not be parsed or opened.")
3571 [delegate_ repairWithSelector:@selector(update)];
3572 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3573 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3574 // else if (error == "The list of sources could not be read.")
3576 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3586 unlink("/tmp/cydia.chk");
3588 now_ = [[NSDate date] timeIntervalSince1970];
3590 policy_ = new pkgDepCache::Policy();
3591 records_ = new pkgRecords(cache_);
3592 resolver_ = new pkgProblemResolver(cache_);
3593 fetcher_ = new pkgAcquire(&status_);
3596 list_ = new pkgSourceList();
3597 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3600 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3601 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:@"ERROR"] forTask:title];
3605 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3608 if (cache_->BrokenCount() != 0) {
3609 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3612 if (cache_->BrokenCount() != 0) {
3613 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:@"ERROR"] forTask:title];
3617 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3621 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3622 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3623 [sourceList_ addObject:object];
3625 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3626 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3627 // XXX: this could be more intelligent
3628 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3629 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3631 sourceMap_[cached->ID] = object;
3636 /*std::vector<Package *> packages;
3637 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3638 [packages_ release];
3643 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3644 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3645 //packages.push_back(package);
3646 CFArrayAppendValue(packages_, [package retain]);
3650 /*if (packages.empty())
3651 packages_ = [[NSArray alloc] init];
3653 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3656 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3657 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3658 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3666 /*if (!packages.empty())
3667 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3668 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3670 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3672 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3674 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3678 size_t count(CFArrayGetCount(packages_));
3679 MetaFile_->active_ = count;
3681 for (size_t index(0); index != count; ++index)
3682 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3686 } } CYPoolEnd() _trace(); }
3689 @synchronized (self) {
3691 resolver_ = new pkgProblemResolver(cache_);
3693 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3694 if (!cache_[iterator].Keep())
3695 cache_->MarkKeep(iterator, false);
3696 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3697 cache_->SetReInstall(iterator, false);
3700 - (void) configure {
3701 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3703 system([dpkg UTF8String]);
3708 // XXX: I don't remember this condition
3713 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3715 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3717 if ([self popErrorWithTitle:title])
3721 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3724 public pkgArchiveCleaner
3727 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3732 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3739 fetcher_->Shutdown();
3741 pkgRecords records(cache_);
3743 lock_ = new FileFd();
3744 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3746 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3748 if ([self popErrorWithTitle:title])
3752 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3755 manager_ = (_system->CreatePM(cache_));
3756 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3763 bool substrate(RestartSubstrate_);
3764 RestartSubstrate_ = false;
3766 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3768 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3770 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3772 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3773 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3776 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3778 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3780 [self popErrorWithTitle:title];
3784 bool failed = false;
3785 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3786 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3788 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3794 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3802 RestartSubstrate_ = true;
3805 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3807 if (_error->PendingError()) {
3812 if (result == pkgPackageManager::Failed) {
3817 if (result != pkgPackageManager::Completed) {
3822 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3824 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3826 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3827 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3830 if (![before isEqualToArray:after])
3835 NSString *title(UCLocalize("UPGRADE"));
3836 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3842 [self updateWithStatus:status_];
3845 - (void) updateWithStatus:(Status &)status {
3846 NSString *title(UCLocalize("REFRESHING_DATA"));
3849 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3853 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3854 if ([self popErrorWithTitle:title])
3857 bool success(ListUpdate(status, list, PulseInterval_));
3858 if (status.WasCancelled())
3861 [self popErrorWithTitle:title forOperation:success];
3863 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3867 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3868 delegate_ = delegate;
3871 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3872 progress_ = delegate;
3873 status_.setDelegate(delegate);
3876 - (NSObject<ProgressDelegate> *) progressDelegate {
3880 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3881 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3882 return i == sourceMap_.end() ? nil : i->second;
3885 - (NSString *) mappedSectionForPointer:(const char *)section {
3886 _H<NSString> *mapped;
3888 _profile(Database$mappedSectionForPointer$Cache)
3889 mapped = §ions_[section];
3892 if (*mapped == NULL) {
3893 size_t length(strlen(section));
3894 char spaced[length + 1];
3896 _profile(Database$mappedSectionForPointer$Replace)
3897 for (size_t index(0); index != length; ++index)
3898 spaced[index] = section[index] == '_' ? ' ' : section[index];
3899 spaced[length] = '\0';
3904 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3905 string = [NSString stringWithUTF8String:spaced];
3908 _profile(Database$mappedSectionForPointer$Map)
3909 string = [SectionMap_ objectForKey:string] ?: string;
3919 /* Web Scripting {{{ */
3920 @interface CydiaObject : NSObject {
3922 _transient id delegate_;
3925 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3929 @implementation CydiaObject
3932 [indirect_ release];
3936 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3937 if ((self = [super init]) != nil) {
3938 indirect_ = [indirect retain];
3942 - (void) setDelegate:(id)delegate {
3943 delegate_ = delegate;
3946 + (NSArray *) _attributeKeys {
3947 return [NSArray arrayWithObjects:
3957 - (NSArray *) attributeKeys {
3958 return [[self class] _attributeKeys];
3961 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3962 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3965 - (NSString *) device {
3966 return [[UIDevice currentDevice] uniqueIdentifier];
3969 - (NSString *) plmn {
3973 - (NSString *) ecid {
3977 - (NSString *) serial {
3978 return SerialNumber_;
3981 - (NSString *) role {
3985 - (NSString *) model {
3986 return [NSString stringWithUTF8String:Machine_];
3989 + (NSString *) webScriptNameForSelector:(SEL)selector {
3991 else if (selector == @selector(addTrivialSource:))
3992 return @"addTrivialSource";
3993 else if (selector == @selector(close))
3995 else if (selector == @selector(du:))
3997 else if (selector == @selector(stringWithFormat:arguments:))
3999 else if (selector == @selector(getAllSources))
4000 return @"getAllSourcs";
4001 else if (selector == @selector(getKernelNumber:))
4002 return @"getKernelNumber";
4003 else if (selector == @selector(getKernelString:))
4004 return @"getKernelString";
4005 else if (selector == @selector(getInstalledPackages))
4006 return @"getInstalledPackages";
4007 else if (selector == @selector(getPackageById:))
4008 return @"getPackageById";
4009 else if (selector == @selector(installPackages:))
4010 return @"installPackages";
4011 else if (selector == @selector(localizedStringForKey:value:table:))
4013 else if (selector == @selector(refreshSources))
4014 return @"refreshSources";
4015 else if (selector == @selector(removeButton))
4016 return @"removeButton";
4017 else if (selector == @selector(scrollToBottom:))
4018 return @"scrollToBottom";
4019 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4020 return @"setButtonImage";
4021 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4022 return @"setButtonTitle";
4023 else if (selector == @selector(setPopupHook:))
4024 return @"setPopupHook";
4025 else if (selector == @selector(setToken:))
4027 else if (selector == @selector(setViewportWidth:))
4028 return @"setViewportWidth";
4029 else if (selector == @selector(statfs:))
4031 else if (selector == @selector(supports:))
4037 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4038 return [self webScriptNameForSelector:selector] == nil;
4041 - (BOOL) supports:(NSString *)feature {
4042 return [feature isEqualToString:@"window.open"];
4045 - (NSNumber *) getKernelNumber:(NSString *)name {
4046 const char *string([name UTF8String]);
4049 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4050 return (id) [NSNull null];
4052 if (size != sizeof(int))
4053 return (id) [NSNull null];
4056 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4057 return (id) [NSNull null];
4059 return [NSNumber numberWithInt:value];
4062 - (NSString *) getKernelString:(NSString *)name {
4063 const char *string([name UTF8String]);
4066 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4067 return (id) [NSNull null];
4069 char value[size + 1];
4070 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4071 return (id) [NSNull null];
4073 // XXX: just in case you request something ludicrous
4076 return [NSString stringWithCString:value];
4079 - (void) addTrivialSource:(NSString *)href {
4080 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4083 - (void) refreshSources {
4084 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4087 - (NSArray *) getAllSources {
4088 return [[Database sharedInstance] sources];
4091 - (NSArray *) getInstalledPackages {
4092 Database *database([Database sharedInstance]);
4093 @synchronized (database) {
4094 NSArray *packages([database packages]);
4095 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4096 for (Package *package in packages)
4097 if (![package uninstalled])
4098 [installed addObject:package];
4102 - (Package *) getPackageById:(NSString *)id {
4103 Package *package([[Database sharedInstance] packageWithName:id]);
4108 - (NSArray *) statfs:(NSString *)path {
4111 if (path == nil || statfs([path UTF8String], &stat) == -1)
4114 return [NSArray arrayWithObjects:
4115 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4116 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4117 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4121 - (NSNumber *) du:(NSString *)path {
4122 NSNumber *value(nil);
4125 _assert(pipe(fds) != -1);
4127 pid_t pid(ExecFork());
4129 _assert(dup2(fds[1], 1) != -1);
4130 _assert(close(fds[0]) != -1);
4131 _assert(close(fds[1]) != -1);
4132 /* XXX: this should probably not use du */
4133 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4138 _assert(close(fds[1]) != -1);
4140 if (FILE *du = fdopen(fds[0], "r")) {
4142 while (fgets(line, sizeof(line), du) != NULL) {
4143 size_t length(strlen(line));
4144 while (length != 0 && line[length - 1] == '\n')
4145 line[--length] = '\0';
4146 if (char *tab = strchr(line, '\t')) {
4148 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4153 } else _assert(close(fds[0]));
4157 if (waitpid(pid, &status, 0) == -1)
4160 else _assert(false);
4166 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4169 - (void) installPackages:(NSArray *)packages {
4170 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4173 - (void) removeButton {
4174 [indirect_ removeButton];
4177 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4178 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4181 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4182 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4185 - (void) _setToken:(NSString *)token {
4188 Token_ = [token retain];
4190 [Metadata_ setObject:Token_ forKey:@"Token"];
4194 - (void) setToken:(NSString *)token {
4195 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4198 - (void) setPopupHook:(id)function {
4199 [indirect_ setPopupHook:function];
4202 - (void) scrollToBottom:(NSNumber *)animated {
4203 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4206 - (void) setViewportWidth:(float)width {
4207 [indirect_ setViewportWidthOnMainThread:width];
4210 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4211 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4212 unsigned count([arguments count]);
4214 for (unsigned i(0); i != count; ++i)
4215 values[i] = [arguments objectAtIndex:i];
4216 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4219 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4220 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4222 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4224 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4230 /* @ Loading... Indicator {{{ */
4231 @interface CYLoadingIndicator : UIView {
4232 _H<UIActivityIndicatorView> spinner_;
4234 _H<UIView> container_;
4237 @property (readonly, nonatomic) UILabel *label;
4238 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4242 @implementation CYLoadingIndicator
4244 - (id) initWithFrame:(CGRect)frame {
4245 if ((self = [super initWithFrame:frame]) != nil) {
4246 container_ = [[[UIView alloc] init] autorelease];
4247 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4249 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4250 [spinner_ startAnimating];
4251 [container_ addSubview:spinner_];
4253 label_ = [[[UILabel alloc] init] autorelease];
4254 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4255 [label_ setBackgroundColor:[UIColor clearColor]];
4256 [label_ setTextColor:[UIColor blackColor]];
4257 [label_ setShadowColor:[UIColor whiteColor]];
4258 [label_ setShadowOffset:CGSizeMake(0, 1)];
4259 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4260 [container_ addSubview:label_];
4262 CGSize viewsize = frame.size;
4263 CGSize spinnersize = [spinner_ bounds].size;
4264 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4265 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4267 CGRect containrect = {
4268 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4269 CGSizeMake(bothwidth, spinnersize.height)
4272 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4280 [container_ setFrame:containrect];
4281 [spinner_ setFrame:spinrect];
4282 [label_ setFrame:textrect];
4283 [self addSubview:container_];
4287 - (UILabel *) label {
4291 - (UIActivityIndicatorView *) activityIndicatorView {
4297 /* Emulated Loading Controller {{{ */
4298 @interface CYEmulatedLoadingController : CYViewController {
4299 _transient Database *database_;
4300 _H<CYLoadingIndicator> indicator_;
4301 _H<UITabBar> tabbar_;
4302 _H<UINavigationBar> navbar_;
4307 @implementation CYEmulatedLoadingController
4309 - (id) initWithDatabase:(Database *)database {
4310 if ((self = [super init]) != nil) {
4311 database_ = database;
4316 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4317 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4319 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4320 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4321 [[self view] addSubview:indicator_];
4323 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4324 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4325 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4326 [[self view] addSubview:tabbar_];
4328 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4329 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4330 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4331 [[self view] addSubview:navbar_];
4334 - (void) releaseSubviews {
4343 /* Cydia Browser Controller {{{ */
4344 @interface CYBrowserController : BrowserController {
4345 CydiaObject *cydia_;
4350 @implementation CYBrowserController
4357 - (NSURL *) navigationURL {
4358 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4361 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4364 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4365 [super webView:view didClearWindowObject:window forFrame:frame];
4367 WebDataSource *source([frame dataSource]);
4368 NSURLResponse *response([source response]);
4370 NSURL *url([response URL]);
4371 NSString *scheme([url scheme]);
4372 NSString *host([url host]);
4374 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4375 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4376 NSDictionary *headers([http allHeaderFields]);
4377 [self setHeaders:headers forHost:host];
4381 [host isEqualToString:@"cydia.saurik.com"] ||
4382 [host hasSuffix:@".cydia.saurik.com"] ||
4383 [scheme isEqualToString:@"file"]
4385 [window setValue:cydia_ forKey:@"cydia"];
4388 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4389 if (System_ != NULL)
4390 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4391 if (Machine_ != NULL)
4392 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4394 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4396 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4399 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4400 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4401 [self _setMoreHeaders:copy];
4405 - (void) setDelegate:(id)delegate {
4406 [super setDelegate:delegate];
4407 [cydia_ setDelegate:delegate];
4411 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4412 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4414 WebView *webview([[webview_ _documentView] webView]);
4416 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4418 NSString *application = package == nil ? @"Cydia" : [NSString
4419 stringWithFormat:@"Cydia/%@",
4424 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4426 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4427 if (Product_ != nil)
4428 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4430 [webview setApplicationNameForUserAgent:application];
4438 @interface NSObject (CydiaScript)
4439 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4442 @implementation NSObject (CydiaScript)
4444 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4450 @implementation NSArray (CydiaScript)
4452 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4453 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4454 for (size_t i(0), e([self count]); i != e; ++i)
4455 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4461 @implementation NSDictionary (CydiaScript)
4463 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4464 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4466 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4473 /* Confirmation Controller {{{ */
4474 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4475 if (!iterator.end())
4476 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4477 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4479 pkgCache::PkgIterator package(dep.TargetPkg());
4482 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4489 @protocol ConfirmationControllerDelegate
4490 - (void) cancelAndClear:(bool)clear;
4491 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4495 @interface ConfirmationController : CYBrowserController {
4496 _transient Database *database_;
4498 UIAlertView *essential_;
4500 NSDictionary *changes_;
4501 NSMutableArray *issues_;
4502 NSDictionary *sizes_;
4507 - (id) initWithDatabase:(Database *)database;
4511 @implementation ConfirmationController
4518 if (essential_ != nil)
4519 [essential_ release];
4526 RestartSubstrate_ = true;
4527 [delegate_ confirmWithNavigationController:[self navigationController]];
4530 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4531 NSString *context([alert context]);
4533 if ([context isEqualToString:@"remove"]) {
4534 if (button == [alert cancelButtonIndex])
4535 [self dismissModalViewControllerAnimated:YES];
4536 else if (button == [alert firstOtherButtonIndex]) {
4540 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4541 } else if ([context isEqualToString:@"unable"]) {
4542 [self dismissModalViewControllerAnimated:YES];
4543 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4545 [super alertView:alert clickedButtonAtIndex:button];
4549 - (void) _doContinue {
4550 [self dismissModalViewControllerAnimated:YES];
4551 [delegate_ cancelAndClear:NO];
4554 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4555 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4559 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4560 [super webView:view didClearWindowObject:window forFrame:frame];
4562 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4563 changes_, @"changes",
4567 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4570 - (id) initWithDatabase:(Database *)database {
4571 if ((self = [super init]) != nil) {
4572 database_ = database;
4574 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4575 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4576 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4577 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4578 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4582 pkgCacheFile &cache([database_ cache]);
4583 NSArray *packages([database_ packages]);
4584 pkgDepCache::Policy *policy([database_ policy]);
4586 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4588 for (Package *package in packages) {
4589 pkgCache::PkgIterator iterator([package iterator]);
4590 NSString *name([package id]);
4592 if ([package broken]) {
4593 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4595 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4597 reasons, @"reasons",
4600 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4604 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4605 pkgCache::DepIterator start;
4606 pkgCache::DepIterator end;
4607 dep.GlobOr(start, end); // ++dep
4609 if (!cache->IsImportantDep(end))
4611 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4614 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4616 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4617 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4618 clauses, @"clauses",
4622 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4624 pkgCache::PkgIterator target(start.TargetPkg());
4625 if (target->ProvidesList != 0)
4626 reason = @"missing";
4628 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4630 reason = @"installed";
4631 installed = [NSString stringWithUTF8String:ver.VerStr()];
4632 } else if (!cache[target].CandidateVerIter(cache).end())
4633 reason = @"uninstalled";
4634 else if (target->ProvidesList == 0)
4635 reason = @"uninstallable";
4637 reason = @"virtual";
4640 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4641 [NSString stringWithUTF8String:start.CompType()], @"operator",
4642 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4645 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4646 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4647 version, @"version",
4649 installed, @"installed",
4652 // yes, seriously. (wtf?)
4660 pkgDepCache::StateCache &state(cache[iterator]);
4662 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4664 if (state.NewInstall())
4665 [installs addObject:name];
4666 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4667 [reinstalls addObject:name];
4668 else if (state.Upgrade())
4669 [upgrades addObject:name];
4670 else if (state.Downgrade())
4671 [downgrades addObject:name];
4672 else if (!state.Delete())
4674 else if (special_r(name))
4675 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4676 [NSNull null], @"package",
4677 [NSArray arrayWithObjects:
4678 [NSDictionary dictionaryWithObjectsAndKeys:
4679 @"Conflicts", @"relationship",
4680 [NSArray arrayWithObjects:
4681 [NSDictionary dictionaryWithObjectsAndKeys:
4683 [NSNull null], @"version",
4684 @"installed", @"reason",
4691 if ([package essential])
4693 [removes addObject:name];
4696 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4697 substrate_ |= DepSubstrate(iterator.CurrentVer());
4702 else if (Advanced_) {
4703 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4705 essential_ = [[UIAlertView alloc]
4706 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4707 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4709 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4711 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4715 [essential_ setContext:@"remove"];
4717 essential_ = [[UIAlertView alloc]
4718 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4719 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4721 cancelButtonTitle:UCLocalize("OKAY")
4722 otherButtonTitles:nil
4725 [essential_ setContext:@"unable"];
4728 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4729 installs, @"installs",
4730 reinstalls, @"reinstalls",
4731 upgrades, @"upgrades",
4732 downgrades, @"downgrades",
4733 removes, @"removes",
4736 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4737 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4738 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4741 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4743 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4744 initWithTitle:UCLocalize("CANCEL")
4745 style:UIBarButtonItemStylePlain
4747 action:@selector(cancelButtonClicked)
4753 - (void) applyRightButton {
4754 if ([issues_ count] == 0 && ![self isLoading])
4755 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4756 initWithTitle:UCLocalize("CONFIRM")
4757 style:UIBarButtonItemStyleDone
4759 action:@selector(confirmButtonClicked)
4762 [[self navigationItem] setRightBarButtonItem:nil];
4766 - (void) cancelButtonClicked {
4767 [self dismissModalViewControllerAnimated:YES];
4768 [delegate_ cancelAndClear:YES];
4772 - (void) confirmButtonClicked {
4773 if (essential_ != nil)
4783 /* Progress Controller {{{ */
4784 @interface ProgressController : CYViewController <
4787 _transient Database *database_;
4788 UIProgressBar *progress_;
4789 UITextView *output_;
4790 UITextLabel *status_;
4791 UIPushButton *close_;
4792 _H<NSString> title_;
4795 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4797 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4799 - (void) setTitle:(NSString *)title;
4803 @implementation ProgressController
4806 [database_ setProgressDelegate:nil];
4807 [progress_ release];
4814 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4815 if ((self = [super init]) != nil) {
4816 database_ = database;
4817 delegate_ = delegate;
4819 [database_ setProgressDelegate:self];
4821 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4823 progress_ = [[UIProgressBar alloc] init];
4824 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4825 [progress_ setStyle:0];
4827 status_ = [[UITextLabel alloc] init];
4828 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4829 [status_ setColor:[UIColor whiteColor]];
4830 [status_ setBackgroundColor:[UIColor clearColor]];
4831 [status_ setCentersHorizontally:YES];
4832 //[status_ setFont:font];
4834 output_ = [[UITextView alloc] init];
4835 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4836 //[output_ setTextFont:@"Courier New"];
4837 [output_ setFont:[[output_ font] fontWithSize:12]];
4838 [output_ setTextColor:[UIColor whiteColor]];
4839 [output_ setBackgroundColor:[UIColor clearColor]];
4840 [output_ setMarginTop:0];
4841 [output_ setAllowsRubberBanding:YES];
4842 [output_ setEditable:NO];
4843 [[self view] addSubview:output_];
4845 close_ = [[UIPushButton alloc] init];
4846 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4847 [close_ setAutosizesToFit:NO];
4848 [close_ setDrawsShadow:YES];
4849 [close_ setStretchBackground:YES];
4850 [close_ setEnabled:YES];
4851 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4852 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4853 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4854 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4858 - (void) positionViews {
4859 CGRect bounds = [[self view] bounds];
4860 CGSize prgsize = [UIProgressBar defaultSize];
4863 (bounds.size.width - prgsize.width) / 2,
4864 bounds.size.height - prgsize.height - 20
4867 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4869 [progress_ setFrame:prgrect];
4870 [status_ setFrame:CGRectMake(
4872 bounds.size.height - prgsize.height - 50,
4873 bounds.size.width - 20,
4876 [output_ setFrame:CGRectMake(
4879 bounds.size.width - 20,
4880 bounds.size.height - 96
4882 [close_ setFrame:CGRectMake(
4883 (bounds.size.width - closewidth) / 2,
4884 bounds.size.height - prgsize.height - 50,
4890 - (void) viewWillAppear:(BOOL)animated {
4891 [super viewDidAppear:animated];
4892 [[self navigationItem] setHidesBackButton:YES];
4893 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4895 [self positionViews];
4898 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4899 [self positionViews];
4902 - (void) closeButtonPushed {
4903 UpdateExternalStatus(0);
4907 [self dismissModalViewControllerAnimated:YES];
4911 [delegate_ terminateWithSuccess];
4912 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4913 [delegate_ suspendWithAnimation:YES];
4915 [delegate_ suspend];*/
4927 system("/usr/bin/sbreload");
4933 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4934 SBReboot(SBSSpringBoardServerPort());
4936 reboot2(RB_AUTOBOOT);
4941 - (void) setTitle:(NSString *)title {
4943 [[self navigationItem] setTitle:title];
4946 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
4947 UpdateExternalStatus(1);
4949 [self setTitle:title];
4951 [status_ setText:nil];
4952 [output_ setText:@""];
4953 [progress_ setProgress:0];
4955 [close_ removeFromSuperview];
4956 [[self view] addSubview:progress_];
4957 [[self view] addSubview:status_];
4959 [delegate_ retainNetworkActivityIndicator];
4961 SHA1SumValue notifyconf; {
4963 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4966 MMap mmap(file, MMap::ReadOnly);
4968 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4969 notifyconf = sha1.Result();
4973 SHA1SumValue springlist; {
4975 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4978 MMap mmap(file, MMap::ReadOnly);
4980 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4981 springlist = sha1.Result();
4985 if (invocation != nil) {
4986 [invocation yieldToSelector:@selector(invoke)];
4987 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4990 [[self view] addSubview:close_];
4991 [progress_ removeFromSuperview];
4992 [status_ removeFromSuperview];
4996 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4999 MMap mmap(file, MMap::ReadOnly);
5001 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5002 if (!(notifyconf == sha1.Result()))
5009 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5012 MMap mmap(file, MMap::ReadOnly);
5014 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5015 if (!(springlist == sha1.Result()))
5021 if (RestartSubstrate_)
5025 RestartSubstrate_ = false;
5028 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5029 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
5030 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
5031 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5032 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
5036 system("su -c /usr/bin/uicache mobile");
5039 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5041 [delegate_ releaseNetworkActivityIndicator];
5044 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5045 NSString *type([event type]);
5047 if ([type isEqualToString:@"ERROR"] || [type isEqualToString:@"WARNING"]) {
5048 CYAlertView *sheet([[[CYAlertView alloc]
5049 initWithTitle:[event compoundTitle]
5050 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
5051 defaultButtonIndex:0
5054 [sheet setMessage:[event message]];
5055 [sheet yieldToPopupAlertAnimated:YES];
5057 } else if ([type isEqualToString:@"INFORMATION"]) {
5058 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], [event message]]];
5059 CGSize size = [output_ contentSize];
5060 CGPoint offset = [output_ contentOffset];
5061 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
5062 CGRect rect = {{0, size.height-1}, {size.width, 1}};
5063 [output_ scrollRectToVisible:rect animated:YES];
5065 } else if ([type isEqualToString:@"STATUS"]) {
5066 NSMutableArray *words([[[event message] componentsSeparatedByString:@" "] mutableCopy]);
5067 for (size_t i(0), e([words count]); i != e; ++i) {
5068 NSString *word([words objectAtIndex:i]);
5069 if (Package *package = [database_ packageWithName:word])
5070 [words replaceObjectAtIndex:i withObject:[package name]];
5073 [status_ setText:[words componentsJoinedByString:@" "]];
5074 } else _assert(false);
5077 - (bool) isProgressCancelled {
5081 - (void) setProgressPercent:(NSNumber *)percent {
5082 [progress_ setProgress:[percent floatValue]];
5088 /* Cell Content View {{{ */
5089 @protocol ContentDelegate
5090 - (void) drawContentRect:(CGRect)rect;
5093 @interface ContentView : UIView {
5094 _transient id<ContentDelegate> delegate_;
5099 @implementation ContentView
5101 - (id) initWithFrame:(CGRect)frame {
5102 if ((self = [super initWithFrame:frame]) != nil) {
5103 [self setNeedsDisplayOnBoundsChange:YES];
5107 - (void) setDelegate:(id<ContentDelegate>)delegate {
5108 delegate_ = delegate;
5111 - (void) drawRect:(CGRect)rect {
5112 [super drawRect:rect];
5113 [delegate_ drawContentRect:rect];
5118 /* Cydia TableView Cell {{{ */
5119 @interface CYTableViewCell : UITableViewCell {
5120 ContentView *content_;
5126 @implementation CYTableViewCell
5133 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5134 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5136 if (view == content_) {
5137 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5138 highlighted_ = highlighted;
5141 [super _updateHighlightColorsForView:view highlighted:highlighted];
5144 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5145 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5146 highlighted_ = selected;
5148 [super setSelected:selected animated:animated];
5149 [content_ setNeedsDisplay];
5155 /* Package Cell {{{ */
5156 @interface PackageCell : CYTableViewCell <
5161 NSString *description_;
5169 - (PackageCell *) init;
5170 - (void) setPackage:(Package *)package;
5172 - (void) drawContentRect:(CGRect)rect;
5176 @implementation PackageCell
5178 - (void) clearPackage {
5189 if (description_ != nil) {
5190 [description_ release];
5194 if (source_ != nil) {
5199 if (badge_ != nil) {
5204 if (placard_ != nil) {
5214 [self clearPackage];
5218 - (PackageCell *) init {
5219 CGRect frame(CGRectMake(0, 0, 320, 74));
5220 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5221 UIView *content([self contentView]);
5222 CGRect bounds([content bounds]);
5224 content_ = [[ContentView alloc] initWithFrame:bounds];
5225 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5226 [content addSubview:content_];
5228 [content_ setDelegate:self];
5229 [content_ setOpaque:YES];
5233 - (NSString *) accessibilityLabel {
5234 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5237 - (void) setPackage:(Package *)package {
5238 [self clearPackage];
5241 Source *source = [package source];
5243 icon_ = [[package icon] retain];
5244 name_ = [[package name] retain];
5247 description_ = [package longDescription];
5248 if (description_ == nil)
5249 description_ = [package shortDescription];
5250 if (description_ != nil)
5251 description_ = [description_ retain];
5253 commercial_ = [package isCommercial];
5255 package_ = [package retain];
5257 NSString *label = nil;
5258 bool trusted = false;
5260 if (source != nil) {
5261 label = [source label];
5262 trusted = [source trusted];
5263 } else if ([[package id] isEqualToString:@"firmware"])
5264 label = UCLocalize("APPLE");
5266 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5268 NSString *from(label);
5270 NSString *section = [package simpleSection];
5271 if (section != nil && ![section isEqualToString:label]) {
5272 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5273 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5276 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5277 source_ = [from retain];
5279 if (NSString *purpose = [package primaryPurpose])
5280 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5281 badge_ = [badge_ retain];
5286 if (NSString *mode = [package_ mode]) {
5287 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5288 color = RemovingColor_;
5289 //placard = @"removing";
5291 color = InstallingColor_;
5292 //placard = @"installing";
5295 // XXX: the removing/installing placards are not @2x
5298 color = [UIColor whiteColor];
5300 if ([package installed] != nil)
5301 placard = @"installed";
5306 [content_ setBackgroundColor:color];
5309 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5310 placard_ = [placard_ retain];
5312 [self setNeedsDisplay];
5313 [content_ setNeedsDisplay];
5316 - (void) drawContentRect:(CGRect)rect {
5317 bool highlighted(highlighted_);
5318 float width([self bounds].size.width);
5321 CGContextRef context(UIGraphicsGetCurrentContext());
5322 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5323 CGContextFillRect(context, rect);
5328 rect.size = [icon_ size];
5330 rect.size.width /= 2;
5331 rect.size.height /= 2;
5333 rect.origin.x = 25 - rect.size.width / 2;
5334 rect.origin.y = 25 - rect.size.height / 2;
5336 [icon_ drawInRect:rect];
5339 if (badge_ != nil) {
5341 rect.size = [badge_ size];
5343 rect.size.width /= 2;
5344 rect.size.height /= 2;
5346 rect.origin.x = 36 - rect.size.width / 2;
5347 rect.origin.y = 36 - rect.size.height / 2;
5349 [badge_ drawInRect:rect];
5356 UISetColor(commercial_ ? Purple_ : Black_);
5357 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5358 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5361 UISetColor(commercial_ ? Purplish_ : Gray_);
5362 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5364 if (placard_ != nil)
5365 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5370 /* Section Cell {{{ */
5371 @interface SectionCell : CYTableViewCell <
5383 - (void) setSection:(Section *)section editing:(BOOL)editing;
5387 @implementation SectionCell
5389 - (void) clearSection {
5390 if (basic_ != nil) {
5395 if (section_ != nil) {
5405 if (count_ != nil) {
5412 [self clearSection];
5418 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5419 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5420 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5421 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5422 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5424 UIView *content([self contentView]);
5425 CGRect bounds([content bounds]);
5427 content_ = [[ContentView alloc] initWithFrame:bounds];
5428 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5429 [content addSubview:content_];
5430 [content_ setBackgroundColor:[UIColor whiteColor]];
5432 [content_ setDelegate:self];
5436 - (void) onSwitch:(id)sender {
5437 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5438 if (metadata == nil) {
5439 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5440 [Sections_ setObject:metadata forKey:basic_];
5443 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5447 - (void) setSection:(Section *)section editing:(BOOL)editing {
5448 if (editing != editing_) {
5450 [switch_ removeFromSuperview];
5452 [self addSubview:switch_];
5456 [self clearSection];
5458 if (section == nil) {
5459 name_ = [UCLocalize("ALL_PACKAGES") retain];
5462 basic_ = [section name];
5464 basic_ = [basic_ retain];
5466 section_ = [section localized];
5467 if (section_ != nil)
5468 section_ = [section_ retain];
5470 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5471 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5474 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5477 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5478 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5480 [content_ setNeedsDisplay];
5483 - (void) setFrame:(CGRect)frame {
5484 [super setFrame:frame];
5486 CGRect rect([switch_ frame]);
5487 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5490 - (NSString *) accessibilityLabel {
5494 - (void) drawContentRect:(CGRect)rect {
5495 bool highlighted(highlighted_ && !editing_);
5497 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5502 float width(rect.size.width);
5508 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5510 CGSize size = [count_ sizeWithFont:Font14_];
5514 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5520 /* File Table {{{ */
5521 @interface FileTable : CYViewController <
5522 UITableViewDataSource,
5525 _transient Database *database_;
5528 NSMutableArray *files_;
5532 - (id) initWithDatabase:(Database *)database;
5533 - (void) setPackage:(Package *)package;
5537 @implementation FileTable
5540 [self releaseSubviews];
5549 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5550 return files_ == nil ? 0 : [files_ count];
5553 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5557 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5558 static NSString *reuseIdentifier = @"Cell";
5560 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5562 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5563 [cell setFont:[UIFont systemFontOfSize:16]];
5565 [cell setText:[files_ objectAtIndex:indexPath.row]];
5566 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5571 - (NSURL *) navigationURL {
5572 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5576 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5578 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5579 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5580 [list_ setRowHeight:24.0f];
5581 [list_ setDataSource:self];
5582 [list_ setDelegate:self];
5583 [[self view] addSubview:list_];
5586 - (void) viewDidLoad {
5587 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5590 - (void) releaseSubviews {
5595 - (id) initWithDatabase:(Database *)database {
5596 if ((self = [super init]) != nil) {
5597 database_ = database;
5599 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5603 - (void) setPackage:(Package *)package {
5604 if (package_ != nil) {
5605 [package_ autorelease];
5614 [files_ removeAllObjects];
5616 if (package != nil) {
5617 package_ = [package retain];
5618 name_ = [[package id] retain];
5620 if (NSArray *files = [package files])
5621 [files_ addObjectsFromArray:files];
5623 if ([files_ count] != 0) {
5624 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5625 [files_ removeObjectAtIndex:0];
5626 [files_ sortUsingSelector:@selector(compareByPath:)];
5628 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5629 [stack addObject:@"/"];
5631 for (int i(0), e([files_ count]); i != e; ++i) {
5632 NSString *file = [files_ objectAtIndex:i];
5633 while (![file hasPrefix:[stack lastObject]])
5634 [stack removeLastObject];
5635 NSString *directory = [stack lastObject];
5636 [stack addObject:[file stringByAppendingString:@"/"]];
5637 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5638 ([stack count] - 2) * 3, "",
5639 [file substringFromIndex:[directory length]]
5648 - (void) reloadData {
5651 [self setPackage:[database_ packageWithName:name_]];
5656 /* Package Controller {{{ */
5657 @interface CYPackageController : CYBrowserController <
5658 UIActionSheetDelegate
5660 _transient Database *database_;
5664 NSMutableArray *buttons_;
5665 UIBarButtonItem *button_;
5668 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5672 @implementation CYPackageController
5675 if (package_ != nil)
5688 - (NSURL *) navigationURL {
5689 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5692 /* XXX: this is not safe at all... localization of /fail/ */
5693 - (void) _clickButtonWithName:(NSString *)name {
5694 if ([name isEqualToString:UCLocalize("CLEAR")])
5695 [delegate_ clearPackage:package_];
5696 else if ([name isEqualToString:UCLocalize("INSTALL")])
5697 [delegate_ installPackage:package_];
5698 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5699 [delegate_ installPackage:package_];
5700 else if ([name isEqualToString:UCLocalize("REMOVE")])
5701 [delegate_ removePackage:package_];
5702 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5703 [delegate_ installPackage:package_];
5704 else _assert(false);
5707 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5708 NSString *context([sheet context]);
5710 if ([context isEqualToString:@"modify"]) {
5711 if (button != [sheet cancelButtonIndex]) {
5712 NSString *buttonName = [buttons_ objectAtIndex:button];
5713 [self _clickButtonWithName:buttonName];
5716 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5720 - (bool) _allowJavaScriptPanel {
5725 - (void) _customButtonClicked {
5726 int count([buttons_ count]);
5731 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5733 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5734 [buttons addObjectsFromArray:buttons_];
5736 UIActionSheet *sheet = [[[UIActionSheet alloc]
5739 cancelButtonTitle:nil
5740 destructiveButtonTitle:nil
5741 otherButtonTitles:nil
5744 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5746 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5747 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5749 [sheet setContext:@"modify"];
5751 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5755 // We don't want to allow non-commercial packages to do custom things to the install button,
5756 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5757 - (void) customButtonClicked {
5759 [super customButtonClicked];
5761 [self _customButtonClicked];
5764 - (void) reloadButtonClicked {
5765 // Don't reload a commerical package by tapping the loading button,
5766 // but if it's not an Install button, we should forward it on.
5767 if (![package_ uninstalled])
5768 [self _customButtonClicked];
5771 - (void) applyLoadingTitle {
5772 // Don't show "Loading" as the title. Ever.
5775 - (UIBarButtonItem *) rightButton {
5780 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5781 if ((self = [super init]) != nil) {
5782 database_ = database;
5783 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5784 name_ = [[NSString alloc] initWithString:name];
5785 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5789 - (void) reloadData {
5790 if (package_ != nil)
5791 [package_ autorelease];
5792 package_ = [database_ packageWithName:name_];
5794 [buttons_ removeAllObjects];
5796 if (package_ != nil) {
5799 package_ = [package_ retain];
5800 commercial_ = [package_ isCommercial];
5802 if ([package_ mode] != nil)
5803 [buttons_ addObject:UCLocalize("CLEAR")];
5804 if ([package_ source] == nil);
5805 else if ([package_ upgradableAndEssential:NO])
5806 [buttons_ addObject:UCLocalize("UPGRADE")];
5807 else if ([package_ uninstalled])
5808 [buttons_ addObject:UCLocalize("INSTALL")];
5810 [buttons_ addObject:UCLocalize("REINSTALL")];
5811 if (![package_ uninstalled])
5812 [buttons_ addObject:UCLocalize("REMOVE")];
5819 switch ([buttons_ count]) {
5820 case 0: title = nil; break;
5821 case 1: title = [buttons_ objectAtIndex:0]; break;
5822 default: title = UCLocalize("MODIFY"); break;
5825 button_ = [[UIBarButtonItem alloc]
5827 style:UIBarButtonItemStylePlain
5829 action:@selector(customButtonClicked)
5835 - (bool) isLoading {
5836 return commercial_ ? [super isLoading] : false;
5842 /* Package List Controller {{{ */
5843 @interface PackageListController : CYViewController <
5844 UITableViewDataSource,
5847 _transient Database *database_;
5849 NSMutableArray *packages_;
5850 NSMutableArray *sections_;
5852 NSMutableArray *index_;
5853 NSMutableDictionary *indices_;
5857 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5858 - (void) setDelegate:(id)delegate;
5859 - (void) resetCursor;
5863 @implementation PackageListController
5866 [packages_ release];
5867 [sections_ release];
5876 - (void) deselectWithAnimation:(BOOL)animated {
5877 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5880 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5881 CGRect base = [[self view] bounds];
5882 base.size.height -= bounds.size.height;
5883 base.origin = [list_ frame].origin;
5885 [UIView beginAnimations:nil context:NULL];
5886 [UIView setAnimationBeginsFromCurrentState:YES];
5887 [UIView setAnimationCurve:curve];
5888 [UIView setAnimationDuration:duration];
5889 [list_ setFrame:base];
5890 [UIView commitAnimations];
5893 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5894 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5897 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5898 [self resizeForKeyboardBounds:bounds duration:0];
5901 - (void) keyboardWillShow:(NSNotification *)notification {
5904 NSTimeInterval duration;
5905 UIViewAnimationCurve curve;
5906 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5907 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5908 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5909 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5911 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);
5912 UIViewController *base = self;
5913 while ([base parentViewController] != nil)
5914 base = [base parentViewController];
5915 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5916 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5918 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5921 - (void) keyboardWillHide:(NSNotification *)notification {
5922 NSTimeInterval duration;
5923 UIViewAnimationCurve curve;
5924 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5925 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5927 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5930 - (void) viewWillAppear:(BOOL)animated {
5931 [super viewWillAppear:animated];
5933 [self resizeForKeyboardBounds:CGRectZero];
5934 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5935 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5938 - (void) viewWillDisappear:(BOOL)animated {
5939 [super viewWillDisappear:animated];
5941 [self resizeForKeyboardBounds:CGRectZero];
5942 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5943 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5946 - (void) viewDidAppear:(BOOL)animated {
5947 [super viewDidAppear:animated];
5948 [self deselectWithAnimation:animated];
5951 - (void) didSelectPackage:(Package *)package {
5952 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5953 [view setDelegate:delegate_];
5954 [[self navigationController] pushViewController:view animated:YES];
5957 #if TryIndexedCollation
5958 + (BOOL) hasIndexedCollation {
5959 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5963 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5964 NSInteger count([sections_ count]);
5965 return count == 0 ? 1 : count;
5968 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5969 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5971 return [[sections_ objectAtIndex:section] name];
5974 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5975 if ([sections_ count] == 0)
5977 return [[sections_ objectAtIndex:section] count];
5980 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5981 @synchronized (database_) {
5982 if ([database_ era] != era_)
5985 Section *section([sections_ objectAtIndex:[path section]]);
5986 NSInteger row([path row]);
5987 Package *package([packages_ objectAtIndex:([section row] + row)]);
5988 return [[package retain] autorelease];
5991 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5992 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5994 cell = [[[PackageCell alloc] init] autorelease];
5995 [cell setPackage:[self packageAtIndexPath:path]];
5999 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6000 Package *package([self packageAtIndexPath:path]);
6001 package = [database_ packageWithName:[package id]];
6002 [self didSelectPackage:package];
6005 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6006 // XXX: is 20 the most optimal number here?
6007 return [packages_ count] > 20 ? index_ : nil;
6010 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6011 #if TryIndexedCollation
6012 if ([[self class] hasIndexedCollation]) {
6013 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6020 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6021 if ((self = [super init]) != nil) {
6022 database_ = database;
6023 title_ = [title copy];
6024 [[self navigationItem] setTitle:title_];
6026 #if TryIndexedCollation
6027 if ([[self class] hasIndexedCollation])
6028 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6031 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6033 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6035 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6036 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6038 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6039 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6040 [list_ setRowHeight:73];
6041 [[self view] addSubview:list_];
6043 [list_ setDataSource:self];
6044 [list_ setDelegate:self];
6048 - (void) setDelegate:(id)delegate {
6049 delegate_ = delegate;
6052 - (bool) hasPackage:(Package *)package {
6056 - (void) reloadData {
6059 era_ = [database_ era];
6060 NSArray *packages = [database_ packages];
6062 [packages_ removeAllObjects];
6063 [sections_ removeAllObjects];
6065 _profile(PackageTable$reloadData$Filter)
6066 for (Package *package in packages)
6067 if ([self hasPackage:package])
6068 [packages_ addObject:package];
6071 [indices_ removeAllObjects];
6073 Section *section = nil;
6075 #if TryIndexedCollation
6076 if ([[self class] hasIndexedCollation]) {
6077 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6078 NSArray *titles = [collation sectionIndexTitles];
6081 _profile(PackageTable$reloadData$Section)
6082 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6086 _profile(PackageTable$reloadData$Section$Package)
6087 package = [packages_ objectAtIndex:offset];
6088 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6091 while (secidx < index) {
6094 _profile(PackageTable$reloadData$Section$Allocate)
6095 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6098 _profile(PackageTable$reloadData$Section$Add)
6099 [sections_ addObject:section];
6103 [section addToCount];
6109 [index_ removeAllObjects];
6111 _profile(PackageTable$reloadData$Section)
6112 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6116 _profile(PackageTable$reloadData$Section$Package)
6117 package = [packages_ objectAtIndex:offset];
6118 index = [package index];
6121 if (section == nil || [section index] != index) {
6122 _profile(PackageTable$reloadData$Section$Allocate)
6123 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6126 [index_ addObject:[section name]];
6127 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6129 _profile(PackageTable$reloadData$Section$Add)
6130 [sections_ addObject:section];
6134 [section addToCount];
6139 _profile(PackageTable$reloadData$List)
6144 - (void) resetCursor {
6145 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6150 /* Filtered Package List Controller {{{ */
6151 @interface FilteredPackageListController : PackageListController {
6157 - (void) setObject:(id)object;
6158 - (void) setObject:(id)object forFilter:(SEL)filter;
6160 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6164 @implementation FilteredPackageListController
6172 - (void) setFilter:(SEL)filter {
6175 /* XXX: this is an unsafe optimization of doomy hell */
6176 Method method(class_getInstanceMethod([Package class], filter));
6177 _assert(method != NULL);
6178 imp_ = method_getImplementation(method);
6179 _assert(imp_ != NULL);
6182 - (void) setObject:(id)object {
6188 object_ = [object retain];
6191 - (void) setObject:(id)object forFilter:(SEL)filter {
6192 [self setFilter:filter];
6193 [self setObject:object];
6196 - (bool) hasPackage:(Package *)package {
6197 _profile(FilteredPackageTable$hasPackage)
6198 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6202 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6203 if ((self = [super initWithDatabase:database title:title]) != nil) {
6204 [self setFilter:filter];
6205 [self setObject:object];
6212 /* Home Controller {{{ */
6213 @interface HomeController : CYBrowserController {
6218 @implementation HomeController
6220 + (BOOL) shouldHideNavigationBar {
6224 - (NSURL *) navigationURL {
6225 return [NSURL URLWithString:@"cydia://home"];
6228 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6229 [super _setMoreHeaders:request];
6232 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6233 if (UniqueID_ != nil)
6234 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6236 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6239 - (void) aboutButtonClicked {
6240 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6242 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6243 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6244 [alert setCancelButtonIndex:0];
6247 @"Copyright (C) 2008-2011\n"
6248 "Jay Freeman (saurik)\n"
6249 "saurik@saurik.com\n"
6250 "http://www.saurik.com/"
6256 - (void) viewWillDisappear:(BOOL)animated {
6257 [super viewWillDisappear:animated];
6259 if ([[self class] shouldHideNavigationBar])
6260 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6263 - (void) viewWillAppear:(BOOL)animated {
6264 if (![self hasLoaded])
6265 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6267 [super viewWillAppear:animated];
6269 if ([[self class] shouldHideNavigationBar])
6270 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6273 - (void) viewDidLoad {
6274 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6275 initWithTitle:UCLocalize("ABOUT")
6276 style:UIBarButtonItemStylePlain
6278 action:@selector(aboutButtonClicked)
6284 /* Manage Controller {{{ */
6285 @interface ManageController : CYBrowserController {
6288 - (void) queueStatusDidChange;
6292 @implementation ManageController
6294 - (NSURL *) navigationURL {
6295 return [NSURL URLWithString:@"cydia://manage"];
6298 - (void) viewWillAppear:(BOOL)animated {
6299 if (![self hasLoaded])
6300 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6302 [super viewWillAppear:animated];
6305 - (void) viewDidLoad {
6306 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6307 initWithTitle:UCLocalize("SETTINGS")
6308 style:UIBarButtonItemStylePlain
6310 action:@selector(settingsButtonClicked)
6313 [self queueStatusDidChange];
6316 - (void) settingsButtonClicked {
6317 [delegate_ showSettings];
6321 - (void) queueButtonClicked {
6325 - (void) applyLoadingTitle {
6326 // Disable "Loading" title.
6329 - (void) applyRightButton {
6330 // Disable right button.
6334 - (void) queueStatusDidChange {
6336 if (!IsWildcat_ && Queuing_) {
6337 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6338 initWithTitle:UCLocalize("QUEUE")
6339 style:UIBarButtonItemStyleDone
6341 action:@selector(queueButtonClicked)
6344 [[self navigationItem] setRightBarButtonItem:nil];
6349 - (bool) isLoading {
6350 // Never show as loading.
6357 /* Refresh Bar {{{ */
6358 @interface RefreshBar : UINavigationBar {
6359 UIProgressIndicator *indicator_;
6360 UITextLabel *prompt_;
6361 UIProgressBar *progress_;
6362 UINavigationButton *cancel_;
6367 @implementation RefreshBar
6370 [indicator_ release];
6372 [progress_ release];
6377 - (void) positionViews {
6378 CGRect frame = [cancel_ frame];
6379 frame.size = [cancel_ sizeThatFits:frame.size];
6380 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6381 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6382 [cancel_ setFrame:frame];
6384 CGSize prgsize = {75, 100};
6386 [self frame].size.width - prgsize.width - 10,
6387 ([self frame].size.height - prgsize.height) / 2
6389 [progress_ setFrame:prgrect];
6391 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6392 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6393 CGRect indrect = {{indoffset, indoffset}, indsize};
6394 [indicator_ setFrame:indrect];
6396 CGSize prmsize = {215, indsize.height + 4};
6398 indoffset * 2 + indsize.width,
6399 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6401 [prompt_ setFrame:prmrect];
6404 - (void) setFrame:(CGRect)frame {
6405 [super setFrame:frame];
6406 [self positionViews];
6409 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6410 if ((self = [super initWithFrame:frame]) != nil) {
6411 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6413 [self setBarStyle:UIBarStyleBlack];
6415 UIBarStyle barstyle([self _barStyle:NO]);
6416 bool ugly(barstyle == UIBarStyleDefault);
6418 UIProgressIndicatorStyle style = ugly ?
6419 UIProgressIndicatorStyleMediumBrown :
6420 UIProgressIndicatorStyleMediumWhite;
6422 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6423 [indicator_ setStyle:style];
6424 [indicator_ startAnimation];
6425 [self addSubview:indicator_];
6427 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6428 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6429 [prompt_ setBackgroundColor:[UIColor clearColor]];
6430 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6431 [self addSubview:prompt_];
6433 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6434 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6435 [progress_ setStyle:0];
6436 [self addSubview:progress_];
6438 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6439 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6440 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6441 [cancel_ setBarStyle:barstyle];
6443 [self positionViews];
6448 [cancel_ removeFromSuperview];
6452 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6453 [progress_ setProgress:0];
6454 [self addSubview:cancel_];
6458 [cancel_ removeFromSuperview];
6461 - (void) setPrompt:(NSString *)prompt {
6462 [prompt_ setText:prompt];
6465 - (void) setProgress:(float)progress {
6466 [progress_ setProgress:progress];
6472 @class CYNavigationController;
6474 /* Cydia Tab Bar Controller {{{ */
6475 @interface CYTabBarController : UITabBarController <
6476 UITabBarControllerDelegate,
6479 _transient Database *database_;
6480 RefreshBar *refreshbar_;
6484 // XXX: ok, "updatedelegate_"?...
6485 _transient NSObject<CydiaDelegate> *updatedelegate_;
6488 UIViewController *remembered_;
6489 _transient UIViewController *transient_;
6492 - (NSArray *) navigationURLCollection;
6493 - (void) dropBar:(BOOL)animated;
6494 - (void) beginUpdate;
6495 - (void) raiseBar:(BOOL)animated;
6500 @implementation CYTabBarController
6502 - (void) setUnselectedViewController:(UIViewController *)transient {
6503 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6504 if (transient != nil) {
6505 if (transient_ == nil)
6506 remembered_ = [[controllers objectAtIndex:0] retain];
6507 transient_ = transient;
6508 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6509 [controllers replaceObjectAtIndex:0 withObject:transient_];
6510 [self setSelectedIndex:0];
6511 [self setViewControllers:controllers];
6512 [self concealTabBarSelection];
6513 } else if (remembered_ != nil) {
6514 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6515 transient_ = transient;
6516 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6517 [remembered_ release];
6519 [self setViewControllers:controllers];
6520 [self revealTabBarSelection];
6524 - (UIViewController *) unselectedViewController {
6528 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6529 if ([self unselectedViewController])
6530 [self setUnselectedViewController:nil];
6533 - (NSArray *) navigationURLCollection {
6534 NSMutableArray *items([NSMutableArray array]);
6536 // XXX: Should this deal with transient view controllers?
6537 for (id navigation in [self viewControllers]) {
6538 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6540 [items addObject:stack];
6546 - (void) reloadData {
6547 for (CYViewController *controller in [self viewControllers])
6548 [controller reloadData];
6550 [(CYNavigationController *)[self unselectedViewController] reloadData];
6554 [refreshbar_ release];
6555 [[NSNotificationCenter defaultCenter] removeObserver:self];
6560 - (id) initWithDatabase:(Database *)database {
6561 if ((self = [super init]) != nil) {
6562 database_ = database;
6563 [self setDelegate:self];
6565 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6566 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6568 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6572 - (void) setUpdate:(NSDate *)date {
6576 - (void) beginUpdate {
6577 [refreshbar_ start];
6580 [updatedelegate_ retainNetworkActivityIndicator];
6584 detachNewThreadSelector:@selector(performUpdate)
6590 - (void) performUpdate { _pooled
6592 status.setDelegate(self);
6593 [database_ updateWithStatus:status];
6596 performSelectorOnMainThread:@selector(completeUpdate)
6602 - (void) stopUpdateWithSelector:(SEL)selector {
6604 [updatedelegate_ releaseNetworkActivityIndicator];
6606 [self raiseBar:YES];
6609 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6612 - (void) completeUpdate {
6615 [self stopUpdateWithSelector:@selector(reloadData)];
6618 - (void) cancelUpdate {
6619 [self stopUpdateWithSelector:@selector(updateData)];
6622 - (void) cancelPressed {
6623 [self cancelUpdate];
6630 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6631 [refreshbar_ setPrompt:[event compoundMessage]];
6634 - (bool) isProgressCancelled {
6638 - (void) setProgressPercent:(NSNumber *)percent {
6639 [refreshbar_ setProgress:[percent floatValue]];
6642 - (void) setUpdateDelegate:(id)delegate {
6643 updatedelegate_ = delegate;
6646 - (CGFloat) statusBarHeight {
6647 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6648 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6650 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6654 - (UIView *) transitionView {
6655 if ([self respondsToSelector:@selector(_transitionView)])
6656 return [self _transitionView];
6658 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6661 - (void) dropBar:(BOOL)animated {
6666 UIView *transition([self transitionView]);
6667 [[self view] addSubview:refreshbar_];
6669 CGRect barframe([refreshbar_ frame]);
6671 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6672 barframe.origin.y = [self statusBarHeight];
6674 barframe.origin.y = 0;
6676 [refreshbar_ setFrame:barframe];
6679 [UIView beginAnimations:nil context:NULL];
6681 CGRect viewframe = [transition frame];
6682 viewframe.origin.y += barframe.size.height;
6683 viewframe.size.height -= barframe.size.height;
6684 [transition setFrame:viewframe];
6687 [UIView commitAnimations];
6689 // Ensure bar has the proper width for our view, it might have changed
6690 barframe.size.width = viewframe.size.width;
6691 [refreshbar_ setFrame:barframe];
6693 // XXX: fix Apple's layout bug
6694 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6697 - (void) raiseBar:(BOOL)animated {
6702 UIView *transition([self transitionView]);
6703 [refreshbar_ removeFromSuperview];
6705 CGRect barframe([refreshbar_ frame]);
6708 [UIView beginAnimations:nil context:NULL];
6710 CGRect viewframe = [transition frame];
6711 viewframe.origin.y -= barframe.size.height;
6712 viewframe.size.height += barframe.size.height;
6713 [transition setFrame:viewframe];
6716 [UIView commitAnimations];
6718 // XXX: fix Apple's layout bug
6719 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6723 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6724 // XXX: fix Apple's layout bug
6725 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6729 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6730 bool dropped(dropped_);
6735 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6740 // XXX: fix Apple's layout bug
6741 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6744 - (void) statusBarFrameChanged:(NSNotification *)notification {
6753 /* Cydia Navigation Controller {{{ */
6754 @interface CYNavigationController : UINavigationController {
6755 _transient Database *database_;
6756 _transient id<UINavigationControllerDelegate> delegate_;
6759 - (NSArray *) navigationURLCollection;
6760 - (id) initWithDatabase:(Database *)database;
6761 - (void) reloadData;
6766 @implementation CYNavigationController
6768 - (NSArray *) navigationURLCollection {
6769 NSMutableArray *stack([NSMutableArray array]);
6771 for (CYViewController *controller in [self viewControllers]) {
6772 NSString *url = [[controller navigationURL] absoluteString];
6774 [stack addObject:url];
6780 - (void) reloadData {
6781 for (CYViewController *page in [self viewControllers]) {
6782 // Only reload controllers that have already loaded.
6783 // This prevents a page from accidentally loading too
6784 // early if it hasn't been shown on the screen yet.
6785 if ([page hasLoaded])
6790 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6791 delegate_ = delegate;
6794 - (id) initWithDatabase:(Database *)database {
6795 if ((self = [super init]) != nil) {
6796 database_ = database;
6803 /* Cydia:// Protocol {{{ */
6804 @interface CydiaURLProtocol : NSURLProtocol {
6809 @implementation CydiaURLProtocol
6811 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6812 NSURL *url([request URL]);
6815 NSString *scheme([[url scheme] lowercaseString]);
6816 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6821 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6825 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6826 id<NSURLProtocolClient> client([self client]);
6828 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6830 NSData *data(UIImagePNGRepresentation(icon));
6832 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6833 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6834 [client URLProtocol:self didLoadData:data];
6835 [client URLProtocolDidFinishLoading:self];
6839 - (void) startLoading {
6840 id<NSURLProtocolClient> client([self client]);
6841 NSURLRequest *request([self request]);
6843 NSURL *url([request URL]);
6844 NSString *href([url absoluteString]);
6846 NSString *path([href substringFromIndex:8]);
6847 NSRange slash([path rangeOfString:@"/"]);
6850 if (slash.location == NSNotFound) {
6854 command = [path substringToIndex:slash.location];
6855 path = [path substringFromIndex:(slash.location + 1)];
6858 Database *database([Database sharedInstance]);
6860 if ([command isEqualToString:@"package-icon"]) {
6863 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6864 Package *package([database packageWithName:path]);
6867 UIImage *icon([package icon]);
6868 [self _returnPNGWithImage:icon forRequest:request];
6869 } else if ([command isEqualToString:@"source-icon"]) {
6872 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6873 NSString *source(Simplify(path));
6874 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6876 icon = [UIImage applicationImageNamed:@"unknown.png"];
6877 [self _returnPNGWithImage:icon forRequest:request];
6878 } else if ([command isEqualToString:@"uikit-image"]) {
6881 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6882 UIImage *icon(_UIImageWithName(path));
6883 [self _returnPNGWithImage:icon forRequest:request];
6884 } else if ([command isEqualToString:@"section-icon"]) {
6887 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6888 NSString *section(Simplify(path));
6889 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6891 icon = [UIImage applicationImageNamed:@"unknown.png"];
6892 [self _returnPNGWithImage:icon forRequest:request];
6894 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6898 - (void) stopLoading {
6904 /* Section Controller {{{ */
6905 @interface SectionController : FilteredPackageListController {
6909 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6913 @implementation SectionController
6915 - (NSURL *) navigationURL {
6916 NSString *name = section_;
6920 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6923 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6926 title = UCLocalize("ALL_PACKAGES");
6927 else if (![name isEqual:@""])
6928 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6930 title = UCLocalize("NO_SECTION");
6932 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6939 /* Sections Controller {{{ */
6940 @interface SectionsController : CYViewController <
6941 UITableViewDataSource,
6944 _transient Database *database_;
6945 NSMutableArray *sections_;
6946 NSMutableArray *filtered_;
6951 - (id) initWithDatabase:(Database *)database;
6952 - (void) editButtonClicked;
6956 @implementation SectionsController
6959 [self releaseSubviews];
6960 [sections_ release];
6961 [filtered_ release];
6966 - (NSURL *) navigationURL {
6967 return [NSURL URLWithString:@"cydia://sections"];
6970 - (void) updateNavigationItem {
6971 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6972 if ([sections_ count] == 0) {
6973 [[self navigationItem] setRightBarButtonItem:nil];
6975 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6976 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6978 action:@selector(editButtonClicked)
6979 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6983 - (BOOL) isEditing {
6987 - (void) setEditing:(BOOL)editing {
6988 if ((editing_ = editing))
6991 [delegate_ updateData];
6993 [self updateNavigationItem];
6996 - (void) viewDidAppear:(BOOL)animated {
6997 [super viewDidAppear:animated];
6998 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7001 - (void) viewWillDisappear:(BOOL)animated {
7002 [super viewWillDisappear:animated];
7003 if (editing_) [self setEditing:NO];
7006 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7007 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7011 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7012 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7015 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7019 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7020 static NSString *reuseIdentifier = @"SectionCell";
7022 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7024 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7026 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7031 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7035 Section *section = [self sectionAtIndexPath:indexPath];
7037 SectionController *controller = [[[SectionController alloc]
7038 initWithDatabase:database_
7039 section:[section name]
7041 [controller setDelegate:delegate_];
7043 [[self navigationController] pushViewController:controller animated:YES];
7047 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7049 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7050 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7051 [list_ setRowHeight:45.0f];
7052 [list_ setDataSource:self];
7053 [list_ setDelegate:self];
7054 [[self view] addSubview:list_];
7057 - (void) viewDidLoad {
7058 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7061 - (void) releaseSubviews {
7066 - (id) initWithDatabase:(Database *)database {
7067 if ((self = [super init]) != nil) {
7068 database_ = database;
7070 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7071 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7075 - (void) reloadData {
7078 NSArray *packages = [database_ packages];
7080 [sections_ removeAllObjects];
7081 [filtered_ removeAllObjects];
7083 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7086 for (Package *package in packages) {
7087 NSString *name([package section]);
7088 NSString *key(name == nil ? @"" : name);
7092 _profile(SectionsView$reloadData$Section)
7093 section = [sections objectForKey:key];
7094 if (section == nil) {
7095 _profile(SectionsView$reloadData$Section$Allocate)
7096 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7097 [sections setObject:section forKey:key];
7102 [section addToCount];
7104 _profile(SectionsView$reloadData$Filter)
7105 if (![package valid] || ![package visible])
7113 [sections_ addObjectsFromArray:[sections allValues]];
7115 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7117 for (Section *section in sections_) {
7118 size_t count([section row]);
7122 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7123 [section setCount:count];
7124 [filtered_ addObject:section];
7127 [self updateNavigationItem];
7132 - (void) editButtonClicked {
7133 [self setEditing:(!editing_)];
7139 /* Changes Controller {{{ */
7140 @interface ChangesController : CYViewController <
7141 UITableViewDataSource,
7144 _transient Database *database_;
7146 CFMutableArrayRef packages_;
7147 NSMutableArray *sections_;
7150 BOOL hasSentFirstLoad_;
7153 - (id) initWithDatabase:(Database *)database;
7157 @implementation ChangesController
7160 [self releaseSubviews];
7161 CFRelease(packages_);
7162 [sections_ release];
7167 - (NSURL *) navigationURL {
7168 return [NSURL URLWithString:@"cydia://changes"];
7171 - (void) viewWillAppear:(BOOL)animated {
7172 // Loads after it appears, so don't load beforehand.
7174 [super viewWillAppear:animated];
7177 - (void) viewDidAppear:(BOOL)animated {
7178 [super viewDidAppear:animated];
7180 if (!hasSentFirstLoad_) {
7181 hasSentFirstLoad_ = YES;
7182 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7184 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7188 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7189 NSInteger count([sections_ count]);
7190 return count == 0 ? 1 : count;
7193 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7194 if ([sections_ count] == 0)
7196 return [[sections_ objectAtIndex:section] name];
7199 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7200 if ([sections_ count] == 0)
7202 return [[sections_ objectAtIndex:section] count];
7205 - (Package *) packageAtIndex:(NSUInteger)index {
7206 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7209 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7210 @synchronized (database_) {
7211 if ([database_ era] != era_)
7214 NSUInteger sectionIndex([path section]);
7215 if (sectionIndex >= [sections_ count])
7217 Section *section([sections_ objectAtIndex:sectionIndex]);
7218 NSInteger row([path row]);
7219 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7222 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7223 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7225 cell = [[[PackageCell alloc] init] autorelease];
7226 [cell setPackage:[self packageAtIndexPath:path]];
7230 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7231 Package *package([self packageAtIndexPath:path]);
7232 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7233 [view setDelegate:delegate_];
7234 [[self navigationController] pushViewController:view animated:YES];
7238 - (void) refreshButtonClicked {
7239 [delegate_ beginUpdate];
7240 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7243 - (void) upgradeButtonClicked {
7244 [delegate_ distUpgrade];
7248 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7250 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7251 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7252 [list_ setRowHeight:73];
7253 [list_ setDataSource:self];
7254 [list_ setDelegate:self];
7255 [[self view] addSubview:list_];
7258 - (void) viewDidLoad {
7259 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7262 - (void) releaseSubviews {
7267 - (id) initWithDatabase:(Database *)database {
7268 if ((self = [super init]) != nil) {
7269 database_ = database;
7271 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7272 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7276 // this mostly works because reloadData (below) is @synchronized (database_)
7277 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7278 - (void) _reloadPackages:(NSArray *)packages {
7279 CFRelease(packages_);
7280 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7283 _profile(ChangesController$_reloadPackages$Filter)
7284 for (Package *package in packages)
7285 if ([package upgradableAndEssential:YES] || [package visible])
7286 CFArrayAppendValue(packages_, package);
7289 _profile(ChangesController$_reloadPackages$radixSort)
7290 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7295 - (void) reloadData {
7296 @synchronized (database_) {
7297 era_ = [database_ era];
7298 NSArray *packages = [database_ packages];
7300 [sections_ removeAllObjects];
7303 UIProgressHUD *hud([delegate_ addProgressHUD]);
7304 [hud setText:UCLocalize("LOADING")];
7305 //NSLog(@"HUD:%@::%@", delegate_, hud);
7306 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7307 [delegate_ removeProgressHUD:hud];
7309 [self _reloadPackages:packages];
7312 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7313 Section *ignored = nil;
7314 Section *section = nil;
7318 bool unseens = false;
7320 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7322 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7323 Package *package = [self packageAtIndex:offset];
7325 BOOL uae = [package upgradableAndEssential:YES];
7329 time_t seen([package seen]);
7331 if (section == nil || last != seen) {
7335 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7338 _profile(ChangesController$reloadData$Allocate)
7339 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7340 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7341 [sections_ addObject:section];
7345 [section addToCount];
7346 } else if ([package ignored]) {
7347 if (ignored == nil) {
7348 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7350 [ignored addToCount];
7353 [upgradable addToCount];
7358 CFRelease(formatter);
7361 Section *last = [sections_ lastObject];
7362 size_t count = [last count];
7363 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7364 [sections_ removeLastObject];
7367 if ([ignored count] != 0)
7368 [sections_ insertObject:ignored atIndex:0];
7370 [sections_ insertObject:upgradable atIndex:0];
7375 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7376 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7377 style:UIBarButtonItemStylePlain
7379 action:@selector(upgradeButtonClicked)
7382 if (![delegate_ updating])
7383 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7384 initWithTitle:UCLocalize("REFRESH")
7385 style:UIBarButtonItemStylePlain
7387 action:@selector(refreshButtonClicked)
7395 /* Search Controller {{{ */
7396 @interface SearchController : FilteredPackageListController <
7399 UISearchBar *search_;
7403 - (id) initWithDatabase:(Database *)database;
7404 - (void) setSearchTerm:(NSString *)term;
7405 - (void) reloadData;
7409 @implementation SearchController
7416 - (NSURL *) navigationURL {
7417 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7418 return [NSURL URLWithString:@"cydia://search"];
7420 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7423 - (void) setSearchTerm:(NSString *)searchTerm {
7424 [search_ setText:searchTerm];
7428 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7429 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7430 [search_ resignFirstResponder];
7434 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7435 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7439 - (id) initWithDatabase:(Database *)database {
7440 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7441 search_ = [[UISearchBar alloc] init];
7445 - (void) viewDidAppear:(BOOL)animated {
7446 [super viewDidAppear:animated];
7448 if (!searchloaded_) {
7449 searchloaded_ = YES;
7450 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7451 [search_ layoutSubviews];
7452 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7454 UITextField *textField;
7455 if ([search_ respondsToSelector:@selector(searchField)])
7456 textField = [search_ searchField];
7458 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7460 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7461 [search_ setDelegate:self];
7462 [textField setEnablesReturnKeyAutomatically:NO];
7463 [[self navigationItem] setTitleView:textField];
7467 - (void) reloadData {
7468 [self setObject:[search_ text]];
7473 - (void) didSelectPackage:(Package *)package {
7474 [search_ resignFirstResponder];
7475 [super didSelectPackage:package];
7480 /* Package Settings Controller {{{ */
7481 @interface PackageSettingsController : CYViewController <
7482 UITableViewDataSource,
7485 _transient Database *database_;
7488 UITableView *table_;
7489 UISwitch *subscribedSwitch_;
7490 UISwitch *ignoredSwitch_;
7491 UITableViewCell *subscribedCell_;
7492 UITableViewCell *ignoredCell_;
7495 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7499 @implementation PackageSettingsController
7502 [self releaseSubviews];
7509 - (NSURL *) navigationURL {
7510 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7513 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7514 if (package_ == nil)
7517 if ([package_ installed] == nil)
7523 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7524 if (package_ == nil)
7527 // both sections contain just one item right now.
7531 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7535 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7537 return UCLocalize("SHOW_ALL_CHANGES_EX");
7539 return UCLocalize("IGNORE_UPGRADES_EX");
7542 - (void) onSubscribed:(id)control {
7543 bool value([control isOn]);
7544 if (package_ == nil)
7546 if ([package_ setSubscribed:value])
7547 [delegate_ updateData];
7550 - (void) _updateIgnored {
7551 const char *package([name_ UTF8String]);
7552 bool on([ignoredSwitch_ isOn]);
7554 pid_t pid(ExecFork());
7556 FILE *dpkg(popen("dpkg --set-selections", "w"));
7557 fwrite(package, strlen(package), 1, dpkg);
7560 fwrite(" hold\n", 6, 1, dpkg);
7562 fwrite(" install\n", 9, 1, dpkg);
7572 int result(waitpid(pid, &status, 0));
7575 _assert(result == pid);
7581 - (void) onIgnored:(id)control {
7582 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7583 [invocation setTarget:self];
7584 [invocation setSelector:@selector(_updateIgnored)];
7586 [delegate_ reloadDataWithInvocation:invocation];
7589 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7590 if (package_ == nil)
7593 switch ([indexPath section]) {
7594 case 0: return subscribedCell_;
7595 case 1: return ignoredCell_;
7604 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7606 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7607 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7608 [table_ setDataSource:self];
7609 [table_ setDelegate:self];
7610 [[self view] addSubview:table_];
7612 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7613 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7614 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7616 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7617 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7618 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7620 subscribedCell_ = [[UITableViewCell alloc] init];
7621 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7622 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7623 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7625 ignoredCell_ = [[UITableViewCell alloc] init];
7626 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7627 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7628 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7631 - (void) viewDidLoad {
7632 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7635 - (void) releaseSubviews {
7636 [ignoredCell_ release];
7639 [subscribedCell_ release];
7640 subscribedCell_ = nil;
7645 [ignoredSwitch_ release];
7646 ignoredSwitch_ = nil;
7648 [subscribedSwitch_ release];
7649 subscribedSwitch_ = nil;
7652 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7653 if ((self = [super init]) != nil) {
7654 database_ = database;
7655 name_ = [package retain];
7659 - (void) reloadData {
7662 if (package_ != nil)
7663 [package_ autorelease];
7664 package_ = [database_ packageWithName:name_];
7666 if (package_ != nil) {
7667 package_ = [package_ retain];
7668 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7669 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7670 } // XXX: what now, G?
7672 [table_ reloadData];
7678 /* Installed Controller {{{ */
7679 @interface InstalledController : FilteredPackageListController {
7683 - (id) initWithDatabase:(Database *)database;
7685 - (void) updateRoleButton;
7686 - (void) queueStatusDidChange;
7690 @implementation InstalledController
7696 - (NSURL *) navigationURL {
7697 return [NSURL URLWithString:@"cydia://installed"];
7700 - (id) initWithDatabase:(Database *)database {
7701 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7702 [self updateRoleButton];
7703 [self queueStatusDidChange];
7708 - (void) queueButtonClicked {
7713 - (void) queueStatusDidChange {
7717 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7718 initWithTitle:UCLocalize("QUEUE")
7719 style:UIBarButtonItemStyleDone
7721 action:@selector(queueButtonClicked)
7724 [[self navigationItem] setLeftBarButtonItem:nil];
7730 - (void) updateRoleButton {
7731 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7732 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7733 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7734 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7736 action:@selector(roleButtonClicked)
7740 - (void) roleButtonClicked {
7741 [self setObject:[NSNumber numberWithBool:expert_]];
7745 [self updateRoleButton];
7751 /* Source Cell {{{ */
7752 @interface SourceCell : CYTableViewCell <
7760 - (void) setSource:(Source *)source;
7764 @implementation SourceCell
7766 - (void) clearSource {
7776 - (void) setSource:(Source *)source {
7780 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7782 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7783 icon_ = [icon_ retain];
7785 origin_ = [[source name] retain];
7786 label_ = [[source uri] retain];
7788 [content_ setNeedsDisplay];
7796 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7797 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7798 UIView *content([self contentView]);
7799 CGRect bounds([content bounds]);
7801 content_ = [[ContentView alloc] initWithFrame:bounds];
7802 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7803 [content_ setBackgroundColor:[UIColor whiteColor]];
7804 [content addSubview:content_];
7806 [content_ setDelegate:self];
7807 [content_ setOpaque:YES];
7811 - (NSString *) accessibilityLabel {
7815 - (void) drawContentRect:(CGRect)rect {
7816 bool highlighted(highlighted_);
7817 float width(rect.size.width);
7820 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7827 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7831 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7836 /* Source Controller {{{ */
7837 @interface SourceController : FilteredPackageListController {
7838 _transient Source *source_;
7842 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7846 @implementation SourceController
7848 - (NSURL *) navigationURL {
7849 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7852 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7853 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7855 key_ = [[source key] retain];
7859 - (void) reloadData {
7860 source_ = [database_ sourceWithKey:key_];
7862 key_ = [[source_ key] retain];
7863 [self setObject:source_];
7864 [[self navigationItem] setTitle:[source_ label]];
7871 /* Sources Controller {{{ */
7872 @interface SourcesController : CYViewController <
7873 UITableViewDataSource,
7876 _transient Database *database_;
7878 NSMutableArray *sources_;
7882 UIProgressHUD *hud_;
7885 //NSURLConnection *installer_;
7886 NSURLConnection *trivial_;
7887 NSURLConnection *trivial_bz2_;
7888 NSURLConnection *trivial_gz_;
7889 //NSURLConnection *automatic_;
7894 - (id) initWithDatabase:(Database *)database;
7895 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7899 @implementation SourcesController
7901 - (void) _releaseConnection:(NSURLConnection *)connection {
7902 if (connection != nil) {
7903 [connection cancel];
7904 //[connection setDelegate:nil];
7905 [connection release];
7910 [self releaseSubviews];
7916 //[self _releaseConnection:installer_];
7917 [self _releaseConnection:trivial_];
7918 [self _releaseConnection:trivial_gz_];
7919 [self _releaseConnection:trivial_bz2_];
7920 //[self _releaseConnection:automatic_];
7926 - (NSURL *) navigationURL {
7927 return [NSURL URLWithString:@"cydia://sources"];
7930 - (void) viewDidAppear:(BOOL)animated {
7931 [super viewDidAppear:animated];
7932 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7935 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7936 return offset_ == 0 ? 1 : 2;
7939 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7940 switch (section + (offset_ == 0 ? 1 : 0)) {
7941 case 0: return UCLocalize("ENTERED_BY_USER");
7942 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7948 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7949 int count = [sources_ count];
7951 case 0: return (offset_ == 0 ? count : offset_);
7952 case 1: return count - offset_;
7958 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7960 switch (indexPath.section) {
7961 case 0: idx = indexPath.row; break;
7962 case 1: idx = indexPath.row + offset_; break;
7966 return [sources_ objectAtIndex:idx];
7969 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7970 static NSString *cellIdentifier = @"SourceCell";
7972 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7973 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7974 [cell setSource:[self sourceAtIndexPath:indexPath]];
7975 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7980 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7981 Source *source = [self sourceAtIndexPath:indexPath];
7983 SourceController *controller = [[[SourceController alloc]
7984 initWithDatabase:database_
7988 [controller setDelegate:delegate_];
7990 [[self navigationController] pushViewController:controller animated:YES];
7993 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7994 Source *source = [self sourceAtIndexPath:indexPath];
7995 return [source record] != nil;
7998 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7999 Source *source = [self sourceAtIndexPath:indexPath];
8000 [Sources_ removeObjectForKey:[source key]];
8001 [delegate_ syncData];
8005 [delegate_ addTrivialSource:href_];
8006 [delegate_ syncData];
8009 - (NSString *) getWarning {
8010 NSString *href(href_);
8011 NSRange colon([href rangeOfString:@"://"]);
8012 if (colon.location != NSNotFound)
8013 href = [href substringFromIndex:(colon.location + 3)];
8014 href = [href stringByAddingPercentEscapes];
8015 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8016 href = [href stringByCachingURLWithCurrentCDN];
8018 NSURL *url([NSURL URLWithString:href]);
8020 NSStringEncoding encoding;
8021 NSError *error(nil);
8023 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8024 return [warning length] == 0 ? nil : warning;
8028 - (void) _endConnection:(NSURLConnection *)connection {
8029 // XXX: the memory management in this method is horribly awkward
8031 NSURLConnection **field = NULL;
8032 if (connection == trivial_)
8034 else if (connection == trivial_bz2_)
8035 field = &trivial_bz2_;
8036 else if (connection == trivial_gz_)
8037 field = &trivial_gz_;
8038 _assert(field != NULL);
8039 [connection release];
8044 trivial_bz2_ == nil &&
8050 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8053 UIAlertView *alert = [[[UIAlertView alloc]
8054 initWithTitle:UCLocalize("SOURCE_WARNING")
8057 cancelButtonTitle:UCLocalize("CANCEL")
8059 UCLocalize("ADD_ANYWAY"),
8063 [alert setContext:@"warning"];
8064 [alert setNumberOfRows:1];
8068 } else if (error_ != nil) {
8069 UIAlertView *alert = [[[UIAlertView alloc]
8070 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8071 message:[error_ localizedDescription]
8073 cancelButtonTitle:UCLocalize("OK")
8074 otherButtonTitles:nil
8077 [alert setContext:@"urlerror"];
8080 UIAlertView *alert = [[[UIAlertView alloc]
8081 initWithTitle:UCLocalize("NOT_REPOSITORY")
8082 message:UCLocalize("NOT_REPOSITORY_EX")
8084 cancelButtonTitle:UCLocalize("OK")
8085 otherButtonTitles:nil
8088 [alert setContext:@"trivial"];
8092 [delegate_ releaseNetworkActivityIndicator];
8094 [delegate_ removeProgressHUD:hud_];
8103 if (error_ != nil) {
8110 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8111 switch ([response statusCode]) {
8117 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8118 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8120 error_ = [error retain];
8121 [self _endConnection:connection];
8124 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8125 [self _endConnection:connection];
8128 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8129 NSMutableURLRequest *request = [NSMutableURLRequest
8130 requestWithURL:[NSURL URLWithString:href]
8131 cachePolicy:NSURLRequestUseProtocolCachePolicy
8132 timeoutInterval:120.0
8135 [request setHTTPMethod:method];
8137 if (Machine_ != NULL)
8138 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8139 if (UniqueID_ != nil)
8140 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8142 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8144 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8147 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8148 NSString *context([alert context]);
8150 if ([context isEqualToString:@"source"]) {
8153 NSString *href = [[alert textField] text];
8155 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8157 if (![href hasSuffix:@"/"])
8158 href_ = [href stringByAppendingString:@"/"];
8161 href_ = [href_ retain];
8163 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8164 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8165 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8166 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8170 // XXX: this is stupid
8171 hud_ = [[delegate_ addProgressHUD] retain];
8172 [hud_ setText:UCLocalize("VERIFYING_URL")];
8173 [delegate_ retainNetworkActivityIndicator];
8182 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8183 } else if ([context isEqualToString:@"trivial"])
8184 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8185 else if ([context isEqualToString:@"urlerror"])
8186 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8187 else if ([context isEqualToString:@"warning"]) {
8202 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8207 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8209 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8210 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8211 [list_ setRowHeight:56];
8212 [list_ setDataSource:self];
8213 [list_ setDelegate:self];
8214 [[self view] addSubview:list_];
8217 - (void) viewDidLoad {
8218 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8219 [self updateButtonsForEditingStatus:NO animated:NO];
8222 - (void) releaseSubviews {
8227 - (id) initWithDatabase:(Database *)database {
8228 if ((self = [super init]) != nil) {
8229 database_ = database;
8230 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8234 - (void) reloadData {
8238 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8241 [sources_ removeAllObjects];
8242 [sources_ addObjectsFromArray:[database_ sources]];
8244 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8247 int count([sources_ count]);
8249 for (int i = 0; i != count; i++) {
8250 if ([[sources_ objectAtIndex:i] record] == nil)
8255 [list_ setEditing:NO];
8256 [self updateButtonsForEditingStatus:NO animated:NO];
8260 - (void) showAddSourcePrompt {
8261 UIAlertView *alert = [[[UIAlertView alloc]
8262 initWithTitle:UCLocalize("ENTER_APT_URL")
8265 cancelButtonTitle:UCLocalize("CANCEL")
8267 UCLocalize("ADD_SOURCE"),
8271 [alert setContext:@"source"];
8272 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8274 [alert setNumberOfRows:1];
8275 [alert addTextFieldWithValue:@"http://" label:@""];
8277 UITextInputTraits *traits = [[alert textField] textInputTraits];
8278 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8279 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8280 [traits setKeyboardType:UIKeyboardTypeURL];
8281 // XXX: UIReturnKeyDone
8282 [traits setReturnKeyType:UIReturnKeyNext];
8287 - (void) addButtonClicked {
8288 [self showAddSourcePrompt];
8291 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8292 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8293 initWithTitle:UCLocalize("ADD")
8294 style:UIBarButtonItemStylePlain
8296 action:@selector(addButtonClicked)
8297 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8299 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8300 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8301 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8303 action:@selector(editButtonClicked)
8304 ] autorelease] animated:animated];
8306 if (IsWildcat_ && !editing)
8307 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8308 initWithTitle:UCLocalize("SETTINGS")
8309 style:UIBarButtonItemStylePlain
8311 action:@selector(settingsButtonClicked)
8315 - (void) settingsButtonClicked {
8316 [delegate_ showSettings];
8319 - (void) editButtonClicked {
8320 [list_ setEditing:![list_ isEditing] animated:YES];
8322 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8328 /* Settings Controller {{{ */
8329 @interface SettingsController : CYViewController <
8330 UITableViewDataSource,
8333 _transient Database *database_;
8334 // XXX: ok, "roledelegate_"?...
8335 _transient id roledelegate_;
8336 UITableView *table_;
8337 UISegmentedControl *segment_;
8341 - (void) showDoneButton;
8342 - (void) resizeSegmentedControl;
8346 @implementation SettingsController
8349 [self releaseSubviews];
8355 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8357 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8358 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8359 [table_ setDelegate:self];
8360 [table_ setDataSource:self];
8361 [[self view] addSubview:table_];
8363 NSArray *items = [NSArray arrayWithObjects:
8365 UCLocalize("HACKER"),
8366 UCLocalize("DEVELOPER"),
8368 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8369 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8370 [container_ addSubview:segment_];
8373 - (void) viewDidLoad {
8374 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8377 if ([Role_ isEqualToString:@"User"]) index = 0;
8378 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8379 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8381 [segment_ setSelectedSegmentIndex:index];
8382 [self showDoneButton];
8385 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8386 [self resizeSegmentedControl];
8389 - (void) releaseSubviews {
8396 [container_ release];
8400 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8401 if ((self = [super init]) != nil) {
8402 database_ = database;
8403 roledelegate_ = delegate;
8407 - (void) resizeSegmentedControl {
8408 CGFloat width = [[self view] frame].size.width;
8409 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8412 - (void) viewWillAppear:(BOOL)animated {
8413 [super viewWillAppear:animated];
8415 [self resizeSegmentedControl];
8418 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8419 [self resizeSegmentedControl];
8422 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8423 [self resizeSegmentedControl];
8427 NSString *role(nil);
8429 switch ([segment_ selectedSegmentIndex]) {
8430 case 0: role = @"User"; break;
8431 case 1: role = @"Hacker"; break;
8432 case 2: role = @"Developer"; break;
8437 if (![role isEqualToString:Role_]) {
8438 bool rolling(Role_ == nil);
8441 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8445 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8449 [roledelegate_ loadData];
8451 [roledelegate_ updateData];
8455 - (void) segmentChanged:(UISegmentedControl *)control {
8456 [self showDoneButton];
8459 - (void) saveAndClose {
8462 [[self navigationItem] setRightBarButtonItem:nil];
8463 [[self navigationController] dismissModalViewControllerAnimated:YES];
8466 - (void) doneButtonClicked {
8467 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8468 [spinner startAnimating];
8469 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8470 [[self navigationItem] setRightBarButtonItem:spinItem];
8472 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8475 - (void) showDoneButton {
8476 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8477 initWithTitle:UCLocalize("DONE")
8478 style:UIBarButtonItemStyleDone
8480 action:@selector(doneButtonClicked)
8481 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8484 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8485 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8489 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8493 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8494 return nil; // This method is required by the protocol.
8497 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8499 return UCLocalize("ROLE_EX");
8501 return [NSString stringWithFormat:
8502 @"%@: %@\n%@: %@\n%@: %@",
8503 UCLocalize("USER"), UCLocalize("USER_EX"),
8504 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8505 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8510 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8511 return section == 3 ? 44.0f : 0;
8514 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8515 return section == 3 ? container_ : nil;
8518 - (void) reloadData {
8520 [table_ reloadData];
8525 /* Stash Controller {{{ */
8526 @interface StashController : CYViewController {
8527 UIActivityIndicatorView *spinner_;
8534 @implementation StashController
8537 [self releaseSubviews];
8543 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8544 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8546 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8547 CGRect spinrect = [spinner_ frame];
8548 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8549 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8550 [spinner_ setFrame:spinrect];
8551 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8552 [[self view] addSubview:spinner_];
8553 [spinner_ startAnimating];
8556 captrect.size.width = [[self view] frame].size.width;
8557 captrect.size.height = 40.0f;
8558 captrect.origin.x = 0;
8559 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8560 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8561 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8562 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8563 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8564 [caption_ setTextColor:[UIColor whiteColor]];
8565 [caption_ setBackgroundColor:[UIColor clearColor]];
8566 [caption_ setShadowColor:[UIColor blackColor]];
8567 [caption_ setTextAlignment:UITextAlignmentCenter];
8568 [[self view] addSubview:caption_];
8571 statusrect.size.width = [[self view] frame].size.width;
8572 statusrect.size.height = 30.0f;
8573 statusrect.origin.x = 0;
8574 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8575 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8576 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8577 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8578 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8579 [status_ setTextColor:[UIColor whiteColor]];
8580 [status_ setBackgroundColor:[UIColor clearColor]];
8581 [status_ setShadowColor:[UIColor blackColor]];
8582 [status_ setTextAlignment:UITextAlignmentCenter];
8583 [[self view] addSubview:status_];
8586 - (void) releaseSubviews {
8600 @interface Cydia : UIApplication <
8601 ConfirmationControllerDelegate,
8604 UINavigationControllerDelegate,
8605 UITabBarControllerDelegate
8607 // XXX: evaluate all fields for _transient
8610 CYTabBarController *tabbar_;
8611 CYEmulatedLoadingController *emulated_;
8613 NSMutableArray *essential_;
8614 NSMutableArray *broken_;
8616 Database *database_;
8623 StashController *stash_;
8632 @implementation Cydia
8634 - (void) beginUpdate {
8635 [tabbar_ beginUpdate];
8639 return [tabbar_ updating];
8643 if ([broken_ count] != 0) {
8644 int count = [broken_ count];
8646 UIAlertView *alert = [[[UIAlertView alloc]
8647 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8648 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8650 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8652 UCLocalize("TEMPORARY_IGNORE"),
8656 [alert setContext:@"fixhalf"];
8658 } else if (!Ignored_ && [essential_ count] != 0) {
8659 int count = [essential_ count];
8661 UIAlertView *alert = [[[UIAlertView alloc]
8662 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8663 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8665 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8667 UCLocalize("UPGRADE_ESSENTIAL"),
8668 UCLocalize("COMPLETE_UPGRADE"),
8672 [alert setContext:@"upgrade"];
8677 - (void) _saveConfig {
8683 NSString *error(nil);
8685 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8687 NSError *error(nil);
8688 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8689 NSLog(@"failure to save metadata data: %@", error);
8694 NSLog(@"failure to serialize metadata: %@", error);
8699 // Navigation controller for the queuing badge.
8700 - (CYNavigationController *) queueNavigationController {
8701 NSArray *controllers = [tabbar_ viewControllers];
8702 return [controllers objectAtIndex:3];
8705 - (void) _updateData {
8708 [tabbar_ reloadData];
8710 CYNavigationController *navigation = [self queueNavigationController];
8712 id queuedelegate = nil;
8713 if ([[navigation viewControllers] count] > 0)
8714 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8716 [queuedelegate queueStatusDidChange];
8717 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8720 - (void) _refreshIfPossible:(NSDate *)update {
8721 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8723 bool recently = false;
8724 if (update != nil) {
8725 NSTimeInterval interval([update timeIntervalSinceNow]);
8726 if (interval <= 0 && interval > -(15*60))
8730 // Don't automatic refresh if:
8731 // - We already refreshed recently.
8732 // - We already auto-refreshed this launch.
8733 // - Auto-refresh is disabled.
8734 if (recently || loaded_ || ManualRefresh) {
8735 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8737 // If we are cancelling, we need to make sure it knows it's already loaded.
8741 // We are going to load, so remember that.
8745 SCNetworkReachabilityFlags flags; {
8746 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8747 SCNetworkReachabilityGetFlags(reachability, &flags);
8748 CFRelease(reachability);
8751 // XXX: this elaborate mess is what Apple is using to determine this? :(
8752 // XXX: do we care if the user has to intervene? maybe that's ok?
8754 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8755 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8756 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8757 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8758 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8759 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8763 // If we can reach the server, auto-refresh!
8765 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8770 - (void) refreshIfPossible {
8771 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8774 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8775 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8776 [hud setText:UCLocalize("RELOADING_DATA")];
8778 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8781 [self removeProgressHUD:hud];
8785 [essential_ removeAllObjects];
8786 [broken_ removeAllObjects];
8788 NSArray *packages([database_ packages]);
8789 for (Package *package in packages) {
8791 [broken_ addObject:package];
8792 if ([package upgradableAndEssential:NO]) {
8793 if ([package essential])
8794 [essential_ addObject:package];
8799 NSLog(@"changes:#%u", changes);
8801 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8804 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8805 [changesItem setBadgeValue:badge];
8806 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8807 [self setApplicationIconBadgeNumber:changes];
8810 [changesItem setBadgeValue:nil];
8811 [changesItem setAnimatedBadge:NO];
8812 [self setApplicationIconBadgeNumber:0];
8817 [self refreshIfPossible];
8820 - (void) updateData {
8829 @synchronized (self) {
8830 [self _reloadDataWithInvocation:nil];
8834 - (void) presentModalViewController:(UIViewController *)controller {
8835 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
8837 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8838 [((UIViewController *) emulated_ ?: tabbar_) presentModalViewController:navigation animated:YES];
8841 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8842 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8844 if (navigation != nil)
8845 [navigation pushViewController:progress animated:YES];
8847 [self presentModalViewController:progress];
8849 [progress invoke:invocation withTitle:title];
8853 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8854 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8857 - (void) repairWithInvocation:(NSInvocation *)invocation {
8859 [self invokeNewProgress:invocation forController:nil withTitle:UCLocalize("REPAIRING")];
8863 - (void) repairWithSelector:(SEL)selector {
8864 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8870 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8871 _assert(file != NULL);
8873 for (NSString *key in [Sources_ allKeys]) {
8874 NSDictionary *source([Sources_ objectForKey:key]);
8876 fprintf(file, "%s %s %s\n",
8877 [[source objectForKey:@"Type"] UTF8String],
8878 [[source objectForKey:@"URI"] UTF8String],
8879 [[source objectForKey:@"Distribution"] UTF8String]
8885 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:UCLocalize("UPDATING_SOURCES")];
8890 - (void) addTrivialSource:(NSString *)href {
8891 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8894 @"./", @"Distribution",
8895 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8900 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8901 @synchronized (self) {
8902 [self _reloadDataWithInvocation:invocation];
8906 - (void) reloadData {
8907 [self reloadDataWithInvocation:nil];
8911 pkgProblemResolver *resolver = [database_ resolver];
8913 resolver->InstallProtect();
8914 if (!resolver->Resolve(true))
8919 // XXX: this is a really crappy way of doing this.
8920 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8921 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8922 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8923 if ([tabbar_ updating])
8924 [tabbar_ cancelUpdate];
8926 if (![database_ prepare])
8929 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8930 [page setDelegate:self];
8931 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8932 [confirm_ setDelegate:self];
8935 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8936 [tabbar_ presentModalViewController:confirm_ animated:YES];
8942 @synchronized (self) {
8947 - (void) clearPackage:(Package *)package {
8948 @synchronized (self) {
8955 - (void) installPackages:(NSArray *)packages {
8956 @synchronized (self) {
8957 for (Package *package in packages)
8964 - (void) installPackage:(Package *)package {
8965 @synchronized (self) {
8972 - (void) removePackage:(Package *)package {
8973 @synchronized (self) {
8980 - (void) distUpgrade {
8981 @synchronized (self) {
8982 if (![database_ upgrade])
8988 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8991 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:UCLocalize("RUNNING")];
8996 - (void) showSettings {
8997 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8998 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9000 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9001 [tabbar_ presentModalViewController:nav animated:YES];
9004 - (void) retainNetworkActivityIndicator {
9005 if (activity_++ == 0)
9006 [self setNetworkActivityIndicatorVisible:YES];
9009 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9013 - (void) releaseNetworkActivityIndicator {
9014 if (--activity_ == 0)
9015 [self setNetworkActivityIndicatorVisible:NO];
9018 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9023 - (void) cancelAndClear:(bool)clear {
9024 @synchronized (self) {
9036 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9037 NSString *context([alert context]);
9039 if ([context isEqualToString:@"conffile"]) {
9040 FILE *input = [database_ input];
9041 if (button == [alert cancelButtonIndex])
9042 fprintf(input, "N\n");
9043 else if (button == [alert firstOtherButtonIndex])
9044 fprintf(input, "Y\n");
9047 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9048 } else if ([context isEqualToString:@"fixhalf"]) {
9049 if (button == [alert cancelButtonIndex]) {
9050 @synchronized (self) {
9051 for (Package *broken in broken_) {
9054 NSString *id = [broken id];
9055 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9056 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9057 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9058 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9064 } else if (button == [alert firstOtherButtonIndex]) {
9065 [broken_ removeAllObjects];
9069 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9070 } else if ([context isEqualToString:@"upgrade"]) {
9071 if (button == [alert firstOtherButtonIndex]) {
9072 @synchronized (self) {
9073 for (Package *essential in essential_)
9074 [essential install];
9079 } else if (button == [alert firstOtherButtonIndex] + 1) {
9081 } else if (button == [alert cancelButtonIndex]) {
9085 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9089 - (void) system:(NSString *)command { _pooled
9091 system([command UTF8String]);
9095 - (void) applicationWillSuspend {
9097 [super applicationWillSuspend];
9100 - (BOOL) isSafeToSuspend {
9101 // Use external process status API internally.
9102 // This is probably a really bad idea.
9103 // XXX: what is the point of this? does this solve anything at all?
9104 uint64_t status = 0;
9106 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9107 notify_get_state(notify_token, &status);
9108 notify_cancel(notify_token);
9111 return locked_ == 0 && status == 0;
9114 - (void) applicationSuspend:(__GSEvent *)event {
9115 if ([self isSafeToSuspend])
9116 [super applicationSuspend:event];
9119 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9120 if ([self isSafeToSuspend])
9121 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9124 - (void) _setSuspended:(BOOL)value {
9125 if ([self isSafeToSuspend])
9126 [super _setSuspended:value];
9129 - (UIProgressHUD *) addProgressHUD {
9130 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9131 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9133 [window_ setUserInteractionEnabled:NO];
9136 UIViewController *target = tabbar_;
9137 while ([target modalViewController] != nil) target = [target modalViewController];
9138 [[target view] addSubview:hud];
9144 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9146 [hud removeFromSuperview];
9147 [window_ setUserInteractionEnabled:YES];
9151 - (CYViewController *) pageForPackage:(NSString *)name {
9152 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9155 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9156 NSString *scheme([[url scheme] lowercaseString]);
9157 if ([[url absoluteString] length] <= [scheme length] + 3)
9159 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9160 NSArray *components([path pathComponents]);
9162 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9163 return [self pageForPackage:[components objectAtIndex:1]];
9165 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9168 NSString *base([components objectAtIndex:0]);
9170 CYViewController *controller = nil;
9172 if ([base isEqualToString:@"url"]) {
9173 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9174 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9175 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9176 } else if (!external && [components count] == 1) {
9177 if ([base isEqualToString:@"manage"]) {
9178 controller = [[[ManageController alloc] init] autorelease];
9181 if ([base isEqualToString:@"sources"]) {
9182 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9185 if ([base isEqualToString:@"home"]) {
9186 controller = [[[HomeController alloc] init] autorelease];
9189 if ([base isEqualToString:@"sections"]) {
9190 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9193 if ([base isEqualToString:@"search"]) {
9194 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9197 if ([base isEqualToString:@"changes"]) {
9198 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9201 if ([base isEqualToString:@"installed"]) {
9202 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9204 } else if ([components count] == 2) {
9205 NSString *argument = [components objectAtIndex:1];
9207 if ([base isEqualToString:@"package"]) {
9208 controller = [self pageForPackage:argument];
9211 if (!external && [base isEqualToString:@"search"]) {
9212 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9213 [(SearchController *)controller setSearchTerm:argument];
9216 if (!external && [base isEqualToString:@"sections"]) {
9217 if ([argument isEqualToString:@"all"])
9219 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9222 if (!external && [base isEqualToString:@"sources"]) {
9223 if ([argument isEqualToString:@"add"]) {
9224 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9225 [(SourcesController *)controller showAddSourcePrompt];
9227 Source *source = [database_ sourceWithKey:argument];
9228 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9232 if (!external && [base isEqualToString:@"launch"]) {
9233 [self launchApplicationWithIdentifier:argument suspended:NO];
9236 } else if (!external && [components count] == 3) {
9237 NSString *arg1 = [components objectAtIndex:1];
9238 NSString *arg2 = [components objectAtIndex:2];
9240 if ([base isEqualToString:@"package"]) {
9241 if ([arg2 isEqualToString:@"settings"]) {
9242 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9243 } else if ([arg2 isEqualToString:@"files"]) {
9244 if (Package *package = [database_ packageWithName:arg1]) {
9245 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9246 [(FileTable *)controller setPackage:package];
9252 [controller setDelegate:self];
9256 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9257 CYViewController *page([self pageForURL:url forExternal:external]);
9260 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9261 [nav setViewControllers:[NSArray arrayWithObject:page]];
9262 [tabbar_ setUnselectedViewController:nav];
9268 - (void) applicationOpenURL:(NSURL *)url {
9269 [super applicationOpenURL:url];
9271 if (!loaded_) starturl_ = [url retain];
9272 else [self openCydiaURL:url forExternal:YES];
9275 - (void) applicationWillResignActive:(UIApplication *)application {
9276 // Stop refreshing if you get a phone call or lock the device.
9277 if ([tabbar_ updating])
9278 [tabbar_ cancelUpdate];
9280 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9281 [super applicationWillResignActive:application];
9284 - (void) applicationWillTerminate:(UIApplication *)application {
9286 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9287 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9288 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9293 - (void) setConfigurationData:(NSString *)data {
9294 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9296 if (!conffile_r(data)) {
9297 lprintf("E:invalid conffile\n");
9301 NSString *ofile = conffile_r[1];
9302 //NSString *nfile = conffile_r[2];
9304 UIAlertView *alert = [[[UIAlertView alloc]
9305 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9306 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9308 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9310 UCLocalize("ACCEPT_NEW_COPY"),
9311 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9315 [alert setContext:@"conffile"];
9319 - (void) addStashController {
9321 stash_ = [[StashController alloc] init];
9322 [window_ addSubview:[stash_ view]];
9325 - (void) removeStashController {
9326 [[stash_ view] removeFromSuperview];
9332 [self setIdleTimerDisabled:YES];
9334 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9335 UpdateExternalStatus(1);
9336 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9337 UpdateExternalStatus(0);
9339 [self removeStashController];
9341 if (ExecFork() == 0) {
9342 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9343 perror("launchctl stop");
9347 - (void) setupViewControllers {
9348 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9350 NSMutableArray *items([NSMutableArray arrayWithObjects:
9351 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9352 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9353 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9354 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9358 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9359 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9361 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9364 NSMutableArray *controllers([NSMutableArray array]);
9365 for (UITabBarItem *item in items) {
9366 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9367 [controller setTabBarItem:item];
9368 [controllers addObject:controller];
9370 [tabbar_ setViewControllers:controllers];
9372 [tabbar_ setUpdateDelegate:self];
9375 - (void) applicationDidFinishLaunching:(id)unused {
9377 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9378 [self setApplicationSupportsShakeToEdit:NO];
9380 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9381 initWithMemoryCapacity:524288
9382 diskCapacity:10485760
9383 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9386 [CYBrowserController _initialize];
9388 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9390 Font12_ = [[UIFont systemFontOfSize:12] retain];
9391 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9392 Font14_ = [[UIFont systemFontOfSize:14] retain];
9393 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9394 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9396 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9397 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9399 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9400 [window_ orderFront:self];
9401 [window_ makeKey:self];
9402 [window_ setHidden:NO];
9405 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9406 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9407 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9408 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9409 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9410 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9411 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9412 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9413 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9416 [self addStashController];
9417 // XXX: this would be much cleaner as a yieldToSelector:
9418 // that way the removeStashController could happen right here inline
9419 // we also could no longer require the useless stash_ field anymore
9420 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9424 database_ = [Database sharedInstance];
9425 [database_ setDelegate:self];
9427 [window_ setUserInteractionEnabled:NO];
9428 [self setupViewControllers];
9430 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9431 [window_ addSubview:[emulated_ view]];
9433 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9440 [window_ setUserInteractionEnabled:YES];
9441 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease]];
9444 if ([emulated_ modalViewController] != nil)
9445 [emulated_ dismissModalViewControllerAnimated:YES];
9446 [window_ setUserInteractionEnabled:NO];
9452 [window_ addSubview:[tabbar_ view]];
9454 [[emulated_ view] removeFromSuperview];
9455 [emulated_ release];
9458 [window_ setUserInteractionEnabled:YES];
9460 int selectedIndex = 0;
9461 NSMutableArray *items = nil;
9463 bool recently = false;
9464 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9465 if (closed != nil) {
9466 NSTimeInterval interval([closed timeIntervalSinceNow]);
9467 // XXX: Is 15 minutes the optimal time here?
9468 if (interval <= 0 && interval > -(15*60))
9472 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9473 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9476 for (NSArray *entry in items)
9477 if ([entry count] <= 0)
9480 if (!recently || !items || !enough) {
9482 items = [NSMutableArray array];
9483 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9484 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9485 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9487 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9489 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9490 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9492 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9495 [tabbar_ setSelectedIndex:selectedIndex];
9496 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9497 NSArray *stack = [items objectAtIndex:tab];
9498 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9499 NSMutableArray *current = [NSMutableArray array];
9501 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9502 NSString *addr = [stack objectAtIndex:nav];
9503 NSURL *url = [NSURL URLWithString:addr];
9504 CYViewController *page = [self pageForURL:url forExternal:NO];
9506 [current addObject:page];
9509 [navigation setViewControllers:current];
9512 // (Try to) show the startup URL.
9513 if (starturl_ != nil) {
9514 [self openCydiaURL:starturl_ forExternal:NO];
9515 [starturl_ release];
9520 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9521 if (item != nil && IsWildcat_) {
9522 [sheet showFromBarButtonItem:item animated:YES];
9524 [sheet showInView:window_];
9528 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9529 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9530 [progress setTitle:task];
9531 [progress addProgressEvent:event];
9534 - (void) addProgressEventForTask:(NSArray *)data {
9535 CydiaProgressEvent *event([data objectAtIndex:0]);
9536 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9537 [self addProgressEvent:event forTask:task];
9540 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9541 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9547 id Alloc_(id self, SEL selector) {
9548 id object = alloc_(self, selector);
9549 lprintf("[%s]A-%p\n", self->isa->name, object);
9554 id Dealloc_(id self, SEL selector) {
9555 id object = dealloc_(self, selector);
9556 lprintf("[%s]D-%p\n", self->isa->name, object);
9560 Class $WebDefaultUIKitDelegate;
9562 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9563 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9564 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9565 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9568 static NSNumber *shouldPlayKeyboardSounds;
9572 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9574 case 1104: // Keyboard Button Clicked
9575 case 1105: // Keyboard Delete Repeated
9576 if (shouldPlayKeyboardSounds == nil) {
9577 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9578 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9581 if (![shouldPlayKeyboardSounds boolValue])
9585 _UIHardware$_playSystemSound$(self, _cmd, sound);
9589 Class $UIApplication;
9591 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9592 static BOOL initialized = NO;
9593 static BOOL started = NO;
9595 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9596 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9598 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9599 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9600 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9601 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9603 if (initialized && !enabled) {
9605 [bundle performSelector:@selector(_accessibilityStopServer)];
9606 } else if (enabled) {
9610 [bundle performSelector:@selector(_accessibilityStartServer)];
9616 int main(int argc, char *argv[]) { _pooled
9619 UpdateExternalStatus(0);
9621 if (Class $UIDevice = objc_getClass("UIDevice")) {
9622 UIDevice *device([$UIDevice currentDevice]);
9623 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9627 UIScreen *screen([UIScreen mainScreen]);
9628 if ([screen respondsToSelector:@selector(scale)])
9629 ScreenScale_ = [screen scale];
9633 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9634 if (ScreenScale_ > 1)
9635 [parts addObject:@"@2x"];
9636 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9637 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9639 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9641 /* Library Hacks {{{ */
9642 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9644 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9645 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9646 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9647 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9648 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9651 $UIHardware = objc_getClass("UIHardware");
9652 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9653 if (UIHardware$_playSystemSound$ != NULL) {
9654 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9655 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9658 $UIApplication = objc_getClass("UIApplication");
9659 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9660 if (UIApplication$_updateApplicationAccessibility != NULL) {
9661 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9662 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9665 /* Set Locale {{{ */
9666 Locale_ = CFLocaleCopyCurrent();
9667 Languages_ = [NSLocale preferredLanguages];
9668 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9669 //NSLog(@"%@", [Languages_ description]);
9672 if (Languages_ == nil || [Languages_ count] == 0)
9673 // XXX: consider just setting to C and then falling through?
9676 lang = [[Languages_ objectAtIndex:0] UTF8String];
9677 setenv("LANG", lang, true);
9680 //std::setlocale(LC_ALL, lang);
9681 NSLog(@"Setting Language: %s", lang);
9684 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9686 /* Parse Arguments {{{ */
9687 bool substrate(false);
9693 for (int argi(1); argi != argc; ++argi)
9694 if (strcmp(argv[argi], "--") == 0) {
9696 argv[argi] = argv[0];
9702 for (int argi(1); argi != arge; ++argi)
9703 if (strcmp(args[argi], "--substrate") == 0)
9706 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9710 App_ = [[NSBundle mainBundle] bundlePath];
9711 Home_ = NSHomeDirectory();
9717 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9718 alloc_ = alloc->method_imp;
9719 alloc->method_imp = (IMP) &Alloc_;*/
9721 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9722 dealloc_ = dealloc->method_imp;
9723 dealloc->method_imp = (IMP) &Dealloc_;*/
9725 /* System Information {{{ */
9729 size = sizeof(maxproc);
9730 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9731 perror("sysctlbyname(\"kern.maxproc\", ?)");
9732 else if (maxproc < 64) {
9734 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9735 perror("sysctlbyname(\"kern.maxproc\", #)");
9738 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9739 char *osversion = new char[size];
9740 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9741 perror("sysctlbyname(\"kern.osversion\", ?)");
9743 System_ = [NSString stringWithUTF8String:osversion];
9745 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9746 char *machine = new char[size];
9747 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9748 perror("sysctlbyname(\"hw.machine\", ?)");
9752 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9753 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9754 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9755 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9759 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9760 NSData *data((NSData *) ecid);
9761 size_t length([data length]);
9762 uint8_t bytes[length];
9763 [data getBytes:bytes];
9764 char string[length * 2 + 1];
9765 for (size_t i(0); i != length; ++i)
9766 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9767 ChipID_ = [NSString stringWithUTF8String:string];
9771 IOObjectRelease(service);
9775 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9777 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9778 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9779 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9781 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9782 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9783 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9785 if (mcc != NULL && mnc != NULL)
9786 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9793 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9794 Build_ = [system objectForKey:@"ProductBuildVersion"];
9795 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9796 Product_ = [info objectForKey:@"SafariProductVersion"];
9797 Safari_ = [info objectForKey:@"CFBundleVersion"];
9800 /* Load Database {{{ */
9802 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9804 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9806 if (Metadata_ == NULL)
9807 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9809 Settings_ = [Metadata_ objectForKey:@"Settings"];
9811 Packages_ = [Metadata_ objectForKey:@"Packages"];
9812 Sections_ = [Metadata_ objectForKey:@"Sections"];
9813 Sources_ = [Metadata_ objectForKey:@"Sources"];
9815 Token_ = [Metadata_ objectForKey:@"Token"];
9818 if (Settings_ != nil)
9819 Role_ = [Settings_ objectForKey:@"Role"];
9821 if (Sections_ == nil) {
9822 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9823 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9826 if (Sources_ == nil) {
9827 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9828 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9833 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9836 if (Packages_ != nil) {
9838 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9842 [Metadata_ removeObjectForKey:@"Packages"];
9848 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9850 #define MobileSubstrate_(name) \
9851 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) \
9852 dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL);
9854 MobileSubstrate_(Activator)
9855 MobileSubstrate_(libstatusbar)
9856 MobileSubstrate_(SimulatedKeyEvents)
9857 MobileSubstrate_(WinterBoard)
9859 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9860 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9862 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9864 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9865 unlink("/tmp/.cydia.fw");
9867 } else if (access("/User", F_OK) != 0 || version < 2) {
9870 system("/usr/libexec/cydia/firmware.sh");
9874 _assert([[NSFileManager defaultManager]
9875 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9876 withIntermediateDirectories:YES
9881 if (access("/tmp/cydia.chk", F_OK) == 0) {
9882 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9883 _assert(errno == ENOENT);
9884 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9885 _assert(errno == ENOENT);
9888 /* APT Initialization {{{ */
9889 _assert(pkgInitConfig(*_config));
9890 _assert(pkgInitSystem(*_config, _system));
9893 _config->Set("APT::Acquire::Translation", lang);
9895 // XXX: this timeout might be important :(
9896 //_config->Set("Acquire::http::Timeout", 15);
9898 _config->Set("Acquire::http::MaxParallel", 3);
9900 /* Color Choices {{{ */
9901 space_ = CGColorSpaceCreateDeviceRGB();
9903 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9904 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9905 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9906 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9907 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9908 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9909 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9910 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9911 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9913 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9914 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9916 /* UIKit Configuration {{{ */
9917 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9918 if ($GSFontSetUseLegacyFontMetrics != NULL)
9919 $GSFontSetUseLegacyFontMetrics(YES);
9921 // XXX: I have a feeling this was important
9922 //UIKeyboardDisableAutomaticAppearance();
9925 Colon_ = UCLocalize("COLON_DELIMITED");
9926 Elision_ = UCLocalize("ELISION");
9927 Error_ = UCLocalize("ERROR");
9928 Warning_ = UCLocalize("WARNING");
9931 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9933 CGColorSpaceRelease(space_);