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]);
292 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
294 return [context count] == 0 ? nil : [context objectAtIndex:0];
297 - (id) yieldToSelector:(SEL)selector {
298 return [self yieldToSelector:selector withObject:nil];
304 /* Cydia Alert View {{{ */
305 @interface CYAlertView : UIAlertView {
309 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
313 @implementation CYAlertView
315 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
316 if ((self = [super init]) != nil) {
317 [self setTitle:title];
318 [self setDelegate:self];
319 for (NSString *button in buttons) [self addButtonWithTitle:button];
320 [self setCancelButtonIndex:index];
324 - (void) _updateFrameForDisplay {
325 [super _updateFrameForDisplay];
326 if ([self cancelButtonIndex] == -1) {
327 NSArray *buttons = [self buttons];
328 if ([buttons count]) {
329 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
330 for (UIThreePartButton *button in buttons)
331 [button setBackground:background forState:0];
336 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
337 button_ = buttonIndex + 1;
341 [self dismissWithClickedButtonIndex:-1 animated:YES];
344 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
345 [self setRunsModal:YES];
354 /* NSForcedOrderingSearch doesn't work on the iPhone */
355 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
356 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
357 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
359 #define lprintf(args...) fprintf(stderr, args)
362 #define TraceLogging (1 && !ForRelease)
363 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
364 #define ProfileTimes (0 && !ForRelease)
365 #define ForSaurik (0 && !ForRelease)
366 #define LogBrowser (0 && !ForRelease)
367 #define TrackResize (0 && !ForRelease)
368 #define ManualRefresh (1 && !ForRelease)
369 #define ShowInternals (0 && !ForRelease)
370 #define AlwaysReload (0 && !ForRelease)
371 #define TryIndexedCollation (0 && !ForRelease)
375 #define _trace(args...)
380 #define _profile(name) {
383 #define PrintTimes() do {} while (false)
387 typedef uint32_t (*SKRadixFunction)(id, void *);
389 @interface NSMutableArray (Radix)
390 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
398 @implementation NSMutableArray (Radix)
400 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
401 size_t count([self count]);
402 struct RadixItem_ *swap(new RadixItem_[count * 2]);
404 for (size_t i(0); i != count; ++i) {
405 RadixItem_ &item(swap[i]);
408 id object([self objectAtIndex:i]);
409 item.key = function(object, argument);
412 struct RadixItem_ *lhs(swap), *rhs(swap + count);
414 static const size_t width = 32;
415 static const size_t bits = 11;
416 static const size_t slots = 1 << bits;
417 static const size_t passes = (width + (bits - 1)) / bits;
419 size_t *hist(new size_t[slots]);
421 for (size_t pass(0); pass != passes; ++pass) {
422 memset(hist, 0, sizeof(size_t) * slots);
424 for (size_t i(0); i != count; ++i) {
425 uint32_t key(lhs[i].key);
427 key &= _not(uint32_t) >> width - bits;
432 for (size_t i(0); i != slots; ++i) {
433 size_t local(offset);
438 for (size_t i(0); i != count; ++i) {
439 uint32_t key(lhs[i].key);
441 key &= _not(uint32_t) >> width - bits;
442 rhs[hist[key]++] = lhs[i];
445 RadixItem_ *tmp(lhs);
452 const void **values(new const void *[count]);
453 for (size_t i(0); i != count; ++i)
454 values[i] = [self objectAtIndex:lhs[i].index];
455 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
463 /* Insertion Sort {{{ */
465 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
466 const char *ptr = (const char *)list;
468 CFIndex half = count / 2;
469 const char *probe = ptr + elementSize * half;
470 CFComparisonResult cr = comparator(element, probe, context);
471 if (0 == cr) return (probe - (const char *)list) / elementSize;
472 ptr = (cr < 0) ? ptr : probe + elementSize;
473 count = (cr < 0) ? half : (half + (count & 1) - 1);
475 return (ptr - (const char *)list) / elementSize;
478 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
479 const char *ptr = (const char *)list;
481 CFIndex half = count / 2;
482 const char *probe = ptr + elementSize * half;
483 CFComparisonResult cr = comparator(element, probe, context);
484 if (0 == cr) return (probe - (const char *)list) / elementSize;
485 ptr = (cr < 0) ? ptr : probe + elementSize;
486 count = (cr < 0) ? half : (half + (count & 1) - 1);
488 return (ptr - (const char *)list) / elementSize;
491 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
492 if (range.length == 0)
494 const void **values(new const void *[range.length]);
495 CFArrayGetValues(array, range, values);
497 #if HistogramInsertionSort > 0
498 uint32_t total(0), *offsets(new uint32_t[range.length]);
501 for (CFIndex index(1); index != range.length; ++index) {
502 const void *value(values[index]);
503 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
504 CFIndex correct(index);
505 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
506 #if HistogramInsertionSort > 1
507 NSLog(@"%@ < %@", value, values[correct - 1]);
512 if (correct != index) {
513 size_t offset(index - correct);
514 #if HistogramInsertionSort
518 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
520 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
521 values[correct] = value;
525 CFArrayReplaceValues(array, range, values, range.length);
528 #if HistogramInsertionSort > 0
529 for (CFIndex index(0); index != range.length; ++index)
530 if (offsets[index] != 0)
531 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
532 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
539 /* Apple Bug Fixes {{{ */
540 @implementation UIWebDocumentView (Cydia)
542 - (void) _setScrollerOffset:(CGPoint)offset {
543 UIScroller *scroller([self _scroller]);
545 CGSize size([scroller contentSize]);
546 CGSize bounds([scroller bounds].size);
549 max.x = size.width - bounds.width;
550 max.y = size.height - bounds.height;
558 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
559 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
561 [scroller setOffset:offset];
567 @implementation WebScriptObject (NSFastEnumeration)
569 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
570 size_t length([self count] - state->state);
573 else if (length > count)
575 for (size_t i(0); i != length; ++i)
576 objects[i] = [self objectAtIndex:state->state++];
577 state->itemsPtr = objects;
578 state->mutationsPtr = (unsigned long *) self;
584 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
585 size_t length([self length] - state->state);
588 else if (length > count)
590 for (size_t i(0); i != length; ++i)
591 objects[i] = [self item:state->state++];
592 state->itemsPtr = objects;
593 state->mutationsPtr = (unsigned long *) self;
597 /* Cydia NSString Additions {{{ */
598 @interface NSString (Cydia)
599 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
600 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
601 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
602 - (NSComparisonResult) compareByPath:(NSString *)other;
603 - (NSString *) stringByCachingURLWithCurrentCDN;
604 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
607 @implementation NSString (Cydia)
609 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
610 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
613 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
614 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
615 memcpy(data, bytes, length);
616 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
619 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
620 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
623 - (NSComparisonResult) compareByPath:(NSString *)other {
624 NSString *prefix = [self commonPrefixWithString:other options:0];
625 size_t length = [prefix length];
627 NSRange lrange = NSMakeRange(length, [self length] - length);
628 NSRange rrange = NSMakeRange(length, [other length] - length);
630 lrange = [self rangeOfString:@"/" options:0 range:lrange];
631 rrange = [other rangeOfString:@"/" options:0 range:rrange];
633 NSComparisonResult value;
635 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
636 value = NSOrderedSame;
637 else if (lrange.location == NSNotFound)
638 value = NSOrderedAscending;
639 else if (rrange.location == NSNotFound)
640 value = NSOrderedDescending;
642 value = NSOrderedSame;
644 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
645 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
646 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
647 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
649 NSComparisonResult result = [lpath compare:rpath];
650 return result == NSOrderedSame ? value : result;
653 - (NSString *) stringByCachingURLWithCurrentCDN {
655 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
656 withString:@"://cache.cydia.saurik.com/"
660 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
661 return [(id)CFURLCreateStringByAddingPercentEscapes(
666 kCFStringEncodingUTF8
673 /* C++ NSString Wrapper Cache {{{ */
674 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
675 return size == 0 ? NULL :
676 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
677 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
680 static _finline CFStringRef CYStringCreate(const char *data) {
681 return CYStringCreate(data, strlen(data));
690 _finline void clear_() {
691 if (cache_ != NULL) {
698 _finline bool empty() const {
702 _finline size_t size() const {
706 _finline char *data() const {
710 _finline void clear() {
715 _finline CYString() :
722 _finline ~CYString() {
726 void operator =(const CYString &rhs) {
730 if (rhs.cache_ == nil)
733 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
736 void copy(apr_pool_t *pool) {
737 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
738 memcpy(temp, data_, size_);
743 void set(apr_pool_t *pool, const char *data, size_t size) {
749 data_ = const_cast<char *>(data);
757 _finline void set(apr_pool_t *pool, const char *data) {
758 set(pool, data, data == NULL ? 0 : strlen(data));
761 _finline void set(apr_pool_t *pool, const std::string &rhs) {
762 set(pool, rhs.data(), rhs.size());
765 bool operator ==(const CYString &rhs) const {
766 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
769 _finline operator CFStringRef() {
771 cache_ = CYStringCreate(data_, size_);
775 _finline operator id() {
776 return (NSString *) static_cast<CFStringRef>(*this);
779 _finline operator const char *() {
780 return reinterpret_cast<const char *>(data_);
784 /* C++ NSString Algorithm Adapters {{{ */
786 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
789 struct NSStringMapHash :
790 std::unary_function<NSString *, size_t>
792 _finline size_t operator ()(NSString *value) const {
793 return CFStringHashNSString((CFStringRef) value);
797 struct NSStringMapLess :
798 std::binary_function<NSString *, NSString *, bool>
800 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
801 return [lhs compare:rhs] == NSOrderedAscending;
805 struct NSStringMapEqual :
806 std::binary_function<NSString *, NSString *, bool>
808 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
809 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
810 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
811 //[lhs isEqualToString:rhs];
816 /* Perl-Compatible RegEx {{{ */
826 Pcre(const char *regex) :
831 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
834 lprintf("%d:%s\n", offset, error);
838 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
839 matches_ = new int[(capture_ + 1) * 3];
847 NSString *operator [](size_t match) {
848 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
851 bool operator ()(NSString *data) {
852 // XXX: length is for characters, not for bytes
853 return operator ()([data UTF8String], [data length]);
856 bool operator ()(const char *data, size_t size) {
858 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
862 /* Mime Addresses {{{ */
863 @interface Address : NSObject {
869 - (NSString *) address;
871 - (void) setAddress:(NSString *)address;
873 + (Address *) addressWithString:(NSString *)string;
874 - (Address *) initWithString:(NSString *)string;
878 @implementation Address
887 - (NSString *) name {
891 - (NSString *) address {
895 - (void) setAddress:(NSString *)address {
897 [address_ autorelease];
901 address_ = [address retain];
904 + (Address *) addressWithString:(NSString *)string {
905 return [[[Address alloc] initWithString:string] autorelease];
908 + (NSArray *) _attributeKeys {
909 return [NSArray arrayWithObjects:
915 - (NSArray *) attributeKeys {
916 return [[self class] _attributeKeys];
919 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
920 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
923 - (Address *) initWithString:(NSString *)string {
924 if ((self = [super init]) != nil) {
925 const char *data = [string UTF8String];
926 size_t size = [string length];
928 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
930 if (address_r(data, size)) {
931 name_ = [address_r[1] retain];
932 address_ = [address_r[2] retain];
934 name_ = [string retain];
942 /* CoreGraphics Primitives {{{ */
947 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
948 CGFloat color[] = {red, green, blue, alpha};
949 return CGColorCreate(space, color);
958 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
959 color_(Create_(space, red, green, blue, alpha))
961 Set(space, red, green, blue, alpha);
966 CGColorRelease(color_);
973 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
975 color_ = Create_(space, red, green, blue, alpha);
978 operator CGColorRef() {
984 /* Random Global Variables {{{ */
985 static const int PulseInterval_ = 50000;
987 static const NSString *UI_;
990 static NSArray *Finishes_;
992 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
993 #define NotifyConfig_ "/etc/notify.conf"
995 static bool Queuing_;
997 static CYColor Blue_;
998 static CYColor Blueish_;
999 static CYColor Black_;
1000 static CYColor Off_;
1001 static CYColor White_;
1002 static CYColor Gray_;
1003 static CYColor Green_;
1004 static CYColor Purple_;
1005 static CYColor Purplish_;
1007 static UIColor *InstallingColor_;
1008 static UIColor *RemovingColor_;
1010 static NSString *App_;
1011 static NSString *Home_;
1013 static BOOL Advanced_;
1014 static BOOL Ignored_;
1016 static UIFont *Font12_;
1017 static UIFont *Font12Bold_;
1018 static UIFont *Font14_;
1019 static UIFont *Font18Bold_;
1020 static UIFont *Font22Bold_;
1022 static const char *Machine_ = NULL;
1023 static NSString *System_ = nil;
1024 static NSString *SerialNumber_ = nil;
1025 static NSString *ChipID_ = nil;
1026 static NSString *Token_ = nil;
1027 static NSString *UniqueID_ = nil;
1028 static NSString *PLMN_ = nil;
1029 static NSString *Build_ = nil;
1030 static NSString *Product_ = nil;
1031 static NSString *Safari_ = nil;
1033 static CFLocaleRef Locale_;
1034 static NSArray *Languages_;
1035 static CGColorSpaceRef space_;
1037 static NSDictionary *SectionMap_;
1038 static NSMutableDictionary *Metadata_;
1039 static _transient NSMutableDictionary *Settings_;
1040 static _transient NSString *Role_;
1041 static _transient NSMutableDictionary *Packages_;
1042 static _transient NSMutableDictionary *Sections_;
1043 static _transient NSMutableDictionary *Sources_;
1044 static bool Changed_;
1048 static CGFloat ScreenScale_;
1051 /* Display Helpers {{{ */
1052 inline float Interpolate(float begin, float end, float fraction) {
1053 return (end - begin) * fraction + begin;
1056 static _finline const char *StripVersion_(const char *version) {
1057 const char *colon(strchr(version, ':'));
1058 return colon == NULL ? version : colon + 1;
1061 NSString *LocalizeSection(NSString *section) {
1062 static Pcre title_r("^(.*?) \\((.*)\\)$");
1063 if (title_r(section)) {
1064 NSString *parent(title_r[1]);
1065 NSString *child(title_r[2]);
1067 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1068 LocalizeSection(parent),
1069 LocalizeSection(child)
1073 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1076 NSString *Simplify(NSString *title) {
1077 const char *data = [title UTF8String];
1078 size_t size = [title length];
1080 static Pcre square_r("^\\[(.*)\\]$");
1081 if (square_r(data, size))
1082 return Simplify(square_r[1]);
1084 static Pcre paren_r("^\\((.*)\\)$");
1085 if (paren_r(data, size))
1086 return Simplify(paren_r[1]);
1088 static Pcre title_r("^(.*?) \\((.*)\\)$");
1089 if (title_r(data, size))
1090 return Simplify(title_r[1]);
1096 NSString *GetLastUpdate() {
1097 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1100 return UCLocalize("NEVER_OR_UNKNOWN");
1102 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1103 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1105 CFRelease(formatter);
1107 return [(NSString *) formatted autorelease];
1110 bool isSectionVisible(NSString *section) {
1111 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1112 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1113 return hidden == nil || ![hidden boolValue];
1118 /* Delegate Prototypes {{{ */
1122 @interface NSObject (ProgressDelegate)
1125 @protocol ProgressDelegate
1126 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1127 - (void) setProgressTitle:(NSString *)title;
1128 - (void) setProgressPercent:(float)percent;
1129 - (void) startProgress;
1130 - (void) addProgressOutput:(NSString *)output;
1131 - (bool) isCancelling:(size_t)received;
1134 @protocol ConfigurationDelegate
1135 - (void) repairWithSelector:(SEL)selector;
1136 - (void) setConfigurationData:(NSString *)data;
1139 @class CYPackageController;
1141 @protocol CydiaDelegate
1142 - (void) retainNetworkActivityIndicator;
1143 - (void) releaseNetworkActivityIndicator;
1144 - (void) clearPackage:(Package *)package;
1145 - (void) installPackage:(Package *)package;
1146 - (void) installPackages:(NSArray *)packages;
1147 - (void) removePackage:(Package *)package;
1148 - (void) beginUpdate;
1150 - (void) distUpgrade;
1152 - (void) updateData;
1154 - (void) showSettings;
1155 - (UIProgressHUD *) addProgressHUD;
1156 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1157 - (CYViewController *) pageForPackage:(NSString *)name;
1158 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1159 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1162 static id<CydiaDelegate> CydiaApp;
1165 /* Status Delegation {{{ */
1167 public pkgAcquireStatus
1170 _transient NSObject<ProgressDelegate> *delegate_;
1178 void setDelegate(id delegate) {
1179 delegate_ = delegate;
1182 NSObject<ProgressDelegate> *getDelegate() const {
1186 virtual bool MediaChange(std::string media, std::string drive) {
1190 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1193 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1194 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1195 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1198 virtual void Done(pkgAcquire::ItemDesc &item) {
1201 virtual void Fail(pkgAcquire::ItemDesc &item) {
1203 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1204 item.Owner->Status == pkgAcquire::Item::StatDone
1208 std::string &error(item.Owner->ErrorText);
1212 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1213 NSArray *fields([description componentsSeparatedByString:@" "]);
1214 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1216 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1217 withObject:[NSArray arrayWithObjects:
1218 [NSString stringWithUTF8String:error.c_str()],
1225 virtual bool Pulse(pkgAcquire *Owner) {
1226 bool value = pkgAcquireStatus::Pulse(Owner);
1229 double(CurrentBytes + CurrentItems) /
1230 double(TotalBytes + TotalItems)
1233 [delegate_ setProgressPercent:percent];
1234 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1237 virtual void Start() {
1238 [delegate_ startProgress];
1241 virtual void Stop() {
1245 /* Progress Delegation {{{ */
1250 _transient id<ProgressDelegate> delegate_;
1254 virtual void Update() {
1255 /*if (abs(Percent - percent_) > 2)
1256 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1260 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1261 [delegate_ setProgressPercent:(Percent / 100)];*/
1271 void setDelegate(id delegate) {
1272 delegate_ = delegate;
1275 id getDelegate() const {
1279 virtual void Done() {
1281 //[delegate_ setProgressPercent:1];
1286 /* Database Interface {{{ */
1287 typedef std::map< unsigned long, _H<Source> > SourceMap;
1289 @interface Database : NSObject {
1295 pkgCacheFile cache_;
1296 pkgDepCache::Policy *policy_;
1297 pkgRecords *records_;
1298 pkgProblemResolver *resolver_;
1299 pkgAcquire *fetcher_;
1301 SPtr<pkgPackageManager> manager_;
1302 pkgSourceList *list_;
1305 CFMutableArrayRef deadSources_;
1306 CFMutableArrayRef packages_;
1308 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1316 std::map<const char *, _H<NSString> > sections_;
1319 + (Database *) sharedInstance;
1322 - (void) _readCydia:(NSNumber *)fd;
1323 - (void) _readStatus:(NSNumber *)fd;
1324 - (void) _readOutput:(NSNumber *)fd;
1328 - (Package *) packageWithName:(NSString *)name;
1330 - (pkgCacheFile &) cache;
1331 - (pkgDepCache::Policy *) policy;
1332 - (pkgRecords *) records;
1333 - (pkgProblemResolver *) resolver;
1334 - (pkgAcquire &) fetcher;
1335 - (pkgSourceList &) list;
1336 - (NSArray *) packages;
1337 - (NSArray *) sources;
1338 - (Source *) sourceWithKey:(NSString *)key;
1339 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1347 - (void) updateWithStatus:(Status &)status;
1349 - (void) setDelegate:(id)delegate;
1350 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1352 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1356 /* Delegate Helpers {{{ */
1357 @implementation NSObject (ProgressDelegate)
1359 - (void) _setProgressErrorPackage:(NSArray *)args {
1360 [self performSelector:@selector(setProgressError:forPackage:)
1361 withObject:[args objectAtIndex:0]
1362 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1366 - (void) _setProgressErrorTitle:(NSArray *)args {
1367 [self performSelector:@selector(setProgressError:withTitle:)
1368 withObject:[args objectAtIndex:0]
1369 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1373 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1374 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1375 withObject:[NSArray arrayWithObjects:error, title, nil]
1380 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1381 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1383 [self performSelector:@selector(setProgressError:withTitle:)
1385 withObject:(package == nil ? id : [package name])
1392 // Cytore Definitions {{{
1393 struct PackageValue :
1396 Cytore::Offset<PackageValue> next_;
1398 uint32_t index_ : 23;
1399 uint32_t subscribed_ : 1;
1416 Cytore::Offset<PackageValue> packages_[1 << 16];
1419 static Cytore::File<MetaValue> MetaFile_;
1421 // Cytore Helper Functions {{{
1422 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1423 SplitHash nhash = { hashlittle(name, length) };
1425 PackageValue *metadata;
1427 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1428 offset: if (offset->IsNull()) {
1429 *offset = MetaFile_.New<PackageValue>(length + 1);
1430 metadata = &MetaFile_.Get(*offset);
1432 if (metadata == NULL) {
1436 metadata = new PackageValue();
1437 memset(metadata, 0, sizeof(*metadata));
1440 memcpy(metadata->name_, name, length + 1);
1441 metadata->nhash_ = nhash.u16[1];
1443 metadata = &MetaFile_.Get(*offset);
1445 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1446 offset = &metadata->next_;
1454 static void PackageImport(const void *key, const void *value, void *context) {
1455 bool &fail(*reinterpret_cast<bool *>(context));
1458 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1459 NSLog(@"failed to import package %@", key);
1463 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1464 NSDictionary *package((NSDictionary *) value);
1466 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1467 if ([subscribed boolValue] && !metadata->subscribed_)
1468 metadata->subscribed_ = true;
1470 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1471 time_t time([date timeIntervalSince1970]);
1472 if (metadata->first_ > time || metadata->first_ == 0)
1473 metadata->first_ = time;
1476 NSDate *date([package objectForKey:@"LastSeen"]);
1477 NSString *version([package objectForKey:@"LastVersion"]);
1479 if (date != nil && version != nil) {
1480 time_t time([date timeIntervalSince1970]);
1481 if (metadata->last_ < time || metadata->last_ == 0)
1482 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1483 size_t length(strlen(buffer));
1484 uint16_t vhash(hashlittle(buffer, length));
1486 size_t capped(std::min<size_t>(8, length));
1487 char *latest(buffer + length - capped);
1489 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1490 metadata->vhash_ = vhash;
1492 metadata->last_ = time;
1498 /* Source Class {{{ */
1499 @interface Source : NSObject {
1500 CYString depiction_;
1501 CYString description_;
1507 CYString distribution_;
1512 NSString *authority_;
1514 CYString defaultIcon_;
1516 NSDictionary *record_;
1520 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1522 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1524 - (NSString *) depictionForPackage:(NSString *)package;
1525 - (NSString *) supportForPackage:(NSString *)package;
1527 - (NSDictionary *) record;
1531 - (NSString *) distribution;
1532 - (NSString *) type;
1534 - (NSString *) host;
1536 - (NSString *) name;
1537 - (NSString *) description;
1538 - (NSString *) label;
1539 - (NSString *) origin;
1540 - (NSString *) version;
1542 - (NSString *) defaultIcon;
1546 @implementation Source
1550 distribution_.clear();
1553 description_.clear();
1559 defaultIcon_.clear();
1561 if (record_ != nil) {
1571 if (authority_ != nil) {
1572 [authority_ release];
1578 // XXX: this is a very inefficient way to call these deconstructors
1583 + (NSArray *) _attributeKeys {
1584 return [NSArray arrayWithObjects:
1599 - (NSArray *) attributeKeys {
1600 return [[self class] _attributeKeys];
1603 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1604 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1607 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1610 trusted_ = index->IsTrusted();
1612 uri_.set(pool, index->GetURI());
1613 distribution_.set(pool, index->GetDist());
1614 type_.set(pool, index->GetType());
1616 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1617 if (dindex != NULL) {
1619 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1622 pkgTagFile tags(&fd);
1624 pkgTagSection section;
1631 {"default-icon", &defaultIcon_},
1632 {"depiction", &depiction_},
1633 {"description", &description_},
1635 {"origin", &origin_},
1636 {"support", &support_},
1637 {"version", &version_},
1640 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1641 const char *start, *end;
1643 if (section.Find(names[i].name_, start, end)) {
1644 CYString &value(*names[i].value_);
1645 value.set(pool, start, end - start);
1651 record_ = [Sources_ objectForKey:[self key]];
1653 record_ = [record_ retain];
1655 NSURL *url([NSURL URLWithString:uri_]);
1659 host_ = [[host_ lowercaseString] retain];
1664 authority_ = [url path];
1666 if (authority_ != nil)
1667 authority_ = [authority_ retain];
1670 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1671 if ((self = [super init]) != nil) {
1672 [self setMetaIndex:index inPool:pool];
1676 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1677 NSDictionary *lhr = [self record];
1678 NSDictionary *rhr = [source record];
1681 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1683 NSString *lhs = [self name];
1684 NSString *rhs = [source name];
1686 if ([lhs length] != 0 && [rhs length] != 0) {
1687 unichar lhc = [lhs characterAtIndex:0];
1688 unichar rhc = [rhs characterAtIndex:0];
1690 if (isalpha(lhc) && !isalpha(rhc))
1691 return NSOrderedAscending;
1692 else if (!isalpha(lhc) && isalpha(rhc))
1693 return NSOrderedDescending;
1696 return [lhs compare:rhs options:LaxCompareOptions_];
1699 - (NSString *) depictionForPackage:(NSString *)package {
1700 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1703 - (NSString *) supportForPackage:(NSString *)package {
1704 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1707 - (NSDictionary *) record {
1715 - (NSString *) uri {
1719 - (NSString *) distribution {
1720 return distribution_;
1723 - (NSString *) type {
1727 - (NSString *) key {
1728 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1731 - (NSString *) host {
1735 - (NSString *) name {
1736 return origin_.empty() ? authority_ : origin_;
1739 - (NSString *) description {
1740 return description_;
1743 - (NSString *) label {
1744 return label_.empty() ? authority_ : label_;
1747 - (NSString *) origin {
1751 - (NSString *) version {
1755 - (NSString *) defaultIcon {
1756 return defaultIcon_;
1761 /* CydiaOperation Class {{{ */
1762 @interface CydiaOperation : NSObject {
1763 NSString *operator_;
1767 - (NSString *) operator;
1768 - (NSString *) value;
1772 @implementation CydiaOperation
1775 [operator_ release];
1780 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1781 if ((self = [super init]) != nil) {
1782 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1783 value_ = [[NSString alloc] initWithUTF8String:value];
1787 + (NSArray *) _attributeKeys {
1788 return [NSArray arrayWithObjects:
1794 - (NSArray *) attributeKeys {
1795 return [[self class] _attributeKeys];
1798 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1799 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1802 - (NSString *) operator {
1806 - (NSString *) value {
1812 /* CydiaClause Class {{{ */
1813 @interface CydiaClause : NSObject {
1815 CydiaOperation *version_;
1818 - (NSString *) package;
1819 - (CydiaOperation *) version;
1823 @implementation CydiaClause
1831 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1832 if ((self = [super init]) != nil) {
1833 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1835 if (const char *version = dep.TargetVer())
1836 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1838 version_ = [[NSNull null] retain];
1842 + (NSArray *) _attributeKeys {
1843 return [NSArray arrayWithObjects:
1849 - (NSArray *) attributeKeys {
1850 return [[self class] _attributeKeys];
1853 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1854 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1857 - (NSString *) package {
1861 - (CydiaOperation *) version {
1867 /* CydiaRelation Class {{{ */
1868 @interface CydiaRelation : NSObject {
1869 NSString *relationship_;
1870 NSMutableArray *clauses_;
1873 - (NSString *) relationship;
1874 - (NSArray *) clauses;
1878 @implementation CydiaRelation
1881 [relationship_ release];
1886 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1887 if ((self = [super init]) != nil) {
1888 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1889 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1891 pkgCache::DepIterator start;
1892 pkgCache::DepIterator end;
1893 dep.GlobOr(start, end); // ++dep
1896 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1898 // yes, seriously. (wtf?)
1906 + (NSArray *) _attributeKeys {
1907 return [NSArray arrayWithObjects:
1913 - (NSArray *) attributeKeys {
1914 return [[self class] _attributeKeys];
1917 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1918 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1921 - (NSString *) relationship {
1922 return relationship_;
1925 - (NSArray *) clauses {
1929 - (void) addClause:(CydiaClause *)clause {
1930 [clauses_ addObject:clause];
1935 /* Package Class {{{ */
1936 struct ParsedPackage {
1941 CYString depiction_;
1951 @interface Package : NSObject {
1954 uint32_t essential_ : 1;
1955 uint32_t obsolete_ : 1;
1956 uint32_t ignored_ : 1;
1960 _transient Database *database_;
1962 pkgCache::VerIterator version_;
1963 pkgCache::PkgIterator iterator_;
1964 pkgCache::VerFileIterator file_;
1970 CYString installed_;
1972 const char *section_;
1973 _transient NSString *section$_;
1977 PackageValue *metadata_;
1978 ParsedPackage *parsed_;
1980 NSMutableArray *tags_;
1983 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1984 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1986 - (pkgCache::PkgIterator) iterator;
1989 - (NSString *) section;
1990 - (NSString *) simpleSection;
1992 - (NSString *) longSection;
1993 - (NSString *) shortSection;
1997 - (Address *) maintainer;
1999 - (NSString *) longDescription;
2000 - (NSString *) shortDescription;
2003 - (PackageValue *) metadata;
2006 - (bool) subscribed;
2007 - (bool) setSubscribed:(bool)subscribed;
2011 - (NSString *) latest;
2012 - (NSString *) installed;
2013 - (BOOL) uninstalled;
2016 - (BOOL) upgradableAndEssential:(BOOL)essential;
2019 - (BOOL) unfiltered;
2023 - (BOOL) halfConfigured;
2024 - (BOOL) halfInstalled;
2026 - (NSString *) mode;
2029 - (NSString *) name;
2031 - (NSString *) homepage;
2032 - (NSString *) depiction;
2033 - (Address *) author;
2035 - (NSString *) support;
2037 - (NSArray *) files;
2038 - (NSArray *) warnings;
2039 - (NSArray *) applications;
2041 - (Source *) source;
2043 - (BOOL) matches:(NSString *)text;
2045 - (bool) hasSupportingRole;
2046 - (BOOL) hasTag:(NSString *)tag;
2047 - (NSString *) primaryPurpose;
2048 - (NSArray *) purposes;
2049 - (bool) isCommercial;
2051 - (void) setIndex:(size_t)index;
2053 - (CYString &) cyname;
2055 - (uint32_t) compareBySection:(NSArray *)sections;
2060 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2061 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2062 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2063 - (bool) isVisibleInSection:(NSString *)section;
2064 - (bool) isVisibleInSource:(Source *)source;
2068 uint32_t PackageChangesRadix(Package *self, void *) {
2073 uint32_t timestamp : 30;
2074 uint32_t ignored : 1;
2075 uint32_t upgradable : 1;
2079 bool upgradable([self upgradableAndEssential:YES]);
2080 value.bits.upgradable = upgradable ? 1 : 0;
2083 value.bits.timestamp = 0;
2084 value.bits.ignored = [self ignored] ? 0 : 1;
2085 value.bits.upgradable = 1;
2087 value.bits.timestamp = [self seen] >> 2;
2088 value.bits.ignored = 0;
2089 value.bits.upgradable = 0;
2092 return _not(uint32_t) - value.key;
2095 uint32_t PackagePrefixRadix(Package *self, void *context) {
2096 size_t offset(reinterpret_cast<size_t>(context));
2097 CYString &name([self cyname]);
2099 size_t size(name.size());
2102 char *text(name.data());
2105 if (!isdigit(text[0]))
2109 while (size != digits && isdigit(text[digits]))
2117 if (offset == 0 && zeros != 0) {
2118 memset(data, '0', zeros);
2119 memcpy(data + zeros, text, 4 - zeros);
2121 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2122 if (size <= offset - zeros)
2125 text += offset - zeros;
2126 size -= offset - zeros;
2129 memcpy(data, text, 4);
2131 memcpy(data, text, size);
2132 memset(data + size, 0, 4 - size);
2135 for (size_t i(0); i != 4; ++i)
2136 if (isalpha(data[i]))
2144 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2146 /* XXX: ntohl may be more honest */
2147 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2150 CYString &(*PackageName)(Package *self, SEL sel);
2152 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2153 _profile(PackageNameCompare)
2154 CYString &lhi(PackageName(lhs, @selector(cyname)));
2155 CYString &rhi(PackageName(rhs, @selector(cyname)));
2156 CFStringRef lhn(lhi), rhn(rhi);
2159 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2160 else if (rhn == NULL)
2161 return NSOrderedDescending;
2163 _profile(PackageNameCompare$NumbersLast)
2164 if (!lhi.empty() && !rhi.empty()) {
2165 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2166 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2167 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2168 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2169 return lha ? NSOrderedAscending : NSOrderedDescending;
2173 CFIndex length = CFStringGetLength(lhn);
2175 _profile(PackageNameCompare$Compare)
2176 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2181 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2182 return PackageNameCompare(*lhs, *rhs, context);
2185 struct PackageNameOrdering :
2186 std::binary_function<Package *, Package *, bool>
2188 _finline bool operator ()(Package *lhs, Package *rhs) const {
2189 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2193 @implementation Package
2195 - (NSString *) description {
2196 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2200 if (parsed_ != NULL)
2209 + (NSString *) webScriptNameForSelector:(SEL)selector {
2211 else if (selector == @selector(clear))
2213 else if (selector == @selector(hasTag:))
2215 else if (selector == @selector(install))
2217 else if (selector == @selector(remove))
2223 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2224 return [self webScriptNameForSelector:selector] == nil;
2227 + (NSArray *) _attributeKeys {
2228 return [NSArray arrayWithObjects:
2246 @"shortDescription",
2257 - (NSArray *) attributeKeys {
2258 return [[self class] _attributeKeys];
2261 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2262 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2265 - (NSArray *) relations {
2266 @synchronized (database_) {
2267 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2268 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2269 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2274 if (parsed_ != NULL)
2276 @synchronized (database_) {
2277 if ([database_ era] != era_ || file_.end())
2280 ParsedPackage *parsed(new ParsedPackage);
2283 _profile(Package$parse)
2284 pkgRecords::Parser *parser;
2286 _profile(Package$parse$Lookup)
2287 parser = &[database_ records]->Lookup(file_);
2292 _profile(Package$parse$Find)
2297 {"icon", &parsed->icon_},
2298 {"depiction", &parsed->depiction_},
2299 {"homepage", &parsed->homepage_},
2300 {"website", &website},
2301 {"bugs", &parsed->bugs_},
2302 {"support", &parsed->support_},
2303 {"sponsor", &parsed->sponsor_},
2304 {"author", &parsed->author_},
2307 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2308 const char *start, *end;
2310 if (parser->Find(names[i].name_, start, end)) {
2311 CYString &value(*names[i].value_);
2312 _profile(Package$parse$Value)
2313 value.set(pool_, start, end - start);
2319 _profile(Package$parse$Tagline)
2320 const char *start, *end;
2321 if (parser->ShortDesc(start, end)) {
2322 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2325 while (stop != start && stop[-1] == '\r')
2327 parsed->tagline_.set(pool_, start, stop - start);
2331 _profile(Package$parse$Retain)
2332 if (parsed->homepage_.empty())
2333 parsed->homepage_ = website;
2334 if (parsed->homepage_ == parsed->depiction_)
2335 parsed->homepage_.clear();
2340 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2341 if ((self = [super init]) != nil) {
2342 _profile(Package$initWithVersion)
2345 database_ = database;
2346 era_ = [database era];
2350 pkgCache::PkgIterator iterator(version.ParentPkg());
2351 iterator_ = iterator;
2353 _profile(Package$initWithVersion$Version)
2354 if (!version_.end())
2355 file_ = version_.FileList();
2357 pkgCache &cache([database_ cache]);
2358 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2362 _profile(Package$initWithVersion$Cache)
2363 name_.set(NULL, iterator.Display());
2365 latest_.set(NULL, StripVersion_(version_.VerStr()));
2367 pkgCache::VerIterator current(iterator.CurrentVer());
2369 installed_.set(NULL, StripVersion_(current.VerStr()));
2372 _profile(Package$initWithVersion$Tags)
2373 pkgCache::TagIterator tag(iterator.TagList());
2375 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2377 const char *name(tag.Name());
2378 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2380 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2381 if (strcmp(name + 6, "enduser") == 0)
2383 else if (strcmp(name + 6, "hacker") == 0)
2385 else if (strcmp(name + 6, "developer") == 0)
2387 else if (strcmp(name + 6, "cydia") == 0)
2393 if (strncmp(name, "cydia::", 7) == 0) {
2394 if (strcmp(name + 7, "essential") == 0)
2396 else if (strcmp(name + 7, "obsolete") == 0)
2401 } while (!tag.end());
2405 _profile(Package$initWithVersion$Metadata)
2406 const char *mixed(iterator.Name());
2407 size_t size(strlen(mixed));
2408 char lower[size + 1];
2410 for (size_t i(0); i != size; ++i)
2411 lower[i] = mixed[i] | 0x20;
2414 PackageValue *metadata(PackageFind(lower, size));
2415 metadata_ = metadata;
2417 id_.set(NULL, metadata->name_, size);
2419 const char *latest(version_.VerStr());
2420 size_t length(strlen(latest));
2422 uint16_t vhash(hashlittle(latest, length));
2424 size_t capped(std::min<size_t>(8, length));
2425 latest = latest + length - capped;
2427 if (metadata->first_ == 0)
2428 metadata->first_ = now_;
2430 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2431 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2432 metadata->vhash_ = vhash;
2433 metadata->last_ = now_;
2434 } else if (metadata->last_ == 0)
2435 metadata->last_ = metadata->first_;
2438 _profile(Package$initWithVersion$Section)
2439 section_ = iterator.Section();
2442 _profile(Package$initWithVersion$Flags)
2443 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2444 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2449 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2450 pkgCache::VerIterator version;
2452 _profile(Package$packageWithIterator$GetCandidateVer)
2453 version = [database policy]->GetCandidateVer(iterator);
2461 _profile(Package$packageWithIterator$Allocate)
2462 package = [Package allocWithZone:zone];
2465 _profile(Package$packageWithIterator$Initialize)
2467 initWithVersion:version
2474 _profile(Package$packageWithIterator$Autorelease)
2475 package = [package autorelease];
2481 - (pkgCache::PkgIterator) iterator {
2485 - (NSString *) section {
2486 if (section$_ == nil) {
2487 if (section_ == NULL)
2490 _profile(Package$section$mappedSectionForPointer)
2491 section$_ = [database_ mappedSectionForPointer:section_];
2496 - (NSString *) simpleSection {
2497 if (NSString *section = [self section])
2498 return Simplify(section);
2503 - (NSString *) longSection {
2504 return LocalizeSection([self section]);
2507 - (NSString *) shortSection {
2508 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2511 - (NSString *) uri {
2514 pkgIndexFile *index;
2515 pkgCache::PkgFileIterator file(file_.File());
2516 if (![database_ list].FindIndex(file, index))
2518 return [NSString stringWithUTF8String:iterator_->Path];
2519 //return [NSString stringWithUTF8String:file.Site()];
2520 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2524 - (Address *) maintainer {
2525 @synchronized (database_) {
2526 if ([database_ era] != era_ || file_.end())
2529 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2530 const std::string &maintainer(parser->Maintainer());
2531 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2535 @synchronized (database_) {
2536 if ([database_ era] != era_ || version_.end())
2539 return version_->InstalledSize;
2542 - (NSString *) longDescription {
2543 @synchronized (database_) {
2544 if ([database_ era] != era_ || file_.end())
2547 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2548 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2550 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2551 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2552 if ([lines count] < 2)
2555 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2556 for (size_t i(1), e([lines count]); i != e; ++i) {
2557 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2558 [trimmed addObject:trim];
2561 return [trimmed componentsJoinedByString:@"\n"];
2564 - (NSString *) shortDescription {
2565 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2569 _profile(Package$index)
2570 CFStringRef name((CFStringRef) [self name]);
2571 if (CFStringGetLength(name) == 0)
2573 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2574 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2576 return toupper(character);
2580 - (PackageValue *) metadata {
2585 PackageValue *metadata([self metadata]);
2586 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2589 - (bool) subscribed {
2590 return [self metadata]->subscribed_;
2593 - (bool) setSubscribed:(bool)subscribed {
2594 PackageValue *metadata([self metadata]);
2595 if (metadata->subscribed_ == subscribed)
2597 metadata->subscribed_ = subscribed;
2605 - (NSString *) latest {
2609 - (NSString *) installed {
2613 - (BOOL) uninstalled {
2614 return installed_.empty();
2618 return !version_.end();
2621 - (BOOL) upgradableAndEssential:(BOOL)essential {
2622 _profile(Package$upgradableAndEssential)
2623 pkgCache::VerIterator current(iterator_.CurrentVer());
2625 return essential && essential_;
2627 return !version_.end() && version_ != current;
2631 - (BOOL) essential {
2636 return [database_ cache][iterator_].InstBroken();
2639 - (BOOL) unfiltered {
2640 _profile(Package$unfiltered$obsolete)
2641 if (_unlikely(obsolete_))
2645 _profile(Package$unfiltered$hasSupportingRole)
2646 if (_unlikely(![self hasSupportingRole]))
2654 if (![self unfiltered])
2659 _profile(Package$visible$section)
2660 section = [self section];
2663 _profile(Package$visible$isSectionVisible)
2664 if (!isSectionVisible(section))
2672 unsigned char current(iterator_->CurrentState);
2673 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2676 - (BOOL) halfConfigured {
2677 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2680 - (BOOL) halfInstalled {
2681 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2685 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2686 return state.Mode != pkgDepCache::ModeKeep;
2689 - (NSString *) mode {
2690 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2692 switch (state.Mode) {
2693 case pkgDepCache::ModeDelete:
2694 if ((state.iFlags & pkgDepCache::Purge) != 0)
2698 case pkgDepCache::ModeKeep:
2699 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2700 return @"REINSTALL";
2701 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2705 case pkgDepCache::ModeInstall:
2706 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2707 return @"REINSTALL";
2708 else*/ switch (state.Status) {
2710 return @"DOWNGRADE";
2716 return @"NEW_INSTALL";
2727 - (NSString *) name {
2728 return name_.empty() ? id_ : name_;
2731 - (UIImage *) icon {
2732 NSString *section = [self simpleSection];
2735 if (parsed_ != NULL)
2736 if (NSString *href = parsed_->icon_)
2737 if ([href hasPrefix:@"file:///"])
2738 // XXX: correct escaping
2739 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2740 if (icon == nil) if (section != nil)
2741 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2742 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2743 if ([dicon hasPrefix:@"file:///"])
2744 // XXX: correct escaping
2745 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2747 icon = [UIImage applicationImageNamed:@"unknown.png"];
2751 - (NSString *) homepage {
2752 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2755 - (NSString *) depiction {
2756 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2759 - (Address *) sponsor {
2760 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2763 - (Address *) author {
2764 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2767 - (NSString *) support {
2768 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2771 - (NSArray *) files {
2772 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2773 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2776 fin.open([path UTF8String]);
2781 while (std::getline(fin, line))
2782 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2787 - (NSArray *) warnings {
2788 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2789 const char *name(iterator_.Name());
2791 size_t length(strlen(name));
2792 if (length < 2) invalid:
2793 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2794 else for (size_t i(0); i != length; ++i)
2796 /* XXX: technically this is not allowed */
2797 (name[i] < 'A' || name[i] > 'Z') &&
2798 (name[i] < 'a' || name[i] > 'z') &&
2799 (name[i] < '0' || name[i] > '9') &&
2800 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2803 if (strcmp(name, "cydia") != 0) {
2806 bool _private = false;
2809 bool repository = [[self section] isEqualToString:@"Repositories"];
2811 if (NSArray *files = [self files])
2812 for (NSString *file in files)
2813 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2815 else if (!user && [file isEqualToString:@"/User"])
2817 else if (!_private && [file isEqualToString:@"/private"])
2819 else if (!stash && [file isEqualToString:@"/var/stash"])
2822 /* XXX: this is not sensitive enough. only some folders are valid. */
2823 if (cydia && !repository)
2824 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2826 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2828 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2830 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2833 return [warnings count] == 0 ? nil : warnings;
2836 - (NSArray *) applications {
2837 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2839 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2841 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2842 if (NSArray *files = [self files])
2843 for (NSString *file in files)
2844 if (application_r(file)) {
2845 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2846 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2847 if ([id isEqualToString:me])
2850 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2852 display = application_r[1];
2854 NSString *bundle([file stringByDeletingLastPathComponent]);
2855 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2856 if (icon == nil || [icon length] == 0)
2858 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2860 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2861 [applications addObject:application];
2863 [application addObject:id];
2864 [application addObject:display];
2865 [application addObject:url];
2868 return [applications count] == 0 ? nil : applications;
2871 - (Source *) source {
2872 if (source_ == nil) {
2873 @synchronized (database_) {
2874 if ([database_ era] != era_ || file_.end())
2875 source_ = (Source *) [NSNull null];
2877 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2881 return source_ == (Source *) [NSNull null] ? nil : source_;
2884 - (BOOL) matches:(NSString *)text {
2890 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2891 if (range.location != NSNotFound)
2894 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2895 if (range.location != NSNotFound)
2900 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2901 if (range.location != NSNotFound)
2907 - (bool) hasSupportingRole {
2912 if ([Role_ isEqualToString:@"User"])
2916 if ([Role_ isEqualToString:@"Hacker"])
2920 if ([Role_ isEqualToString:@"Developer"])
2925 - (BOOL) hasTag:(NSString *)tag {
2926 return tags_ == nil ? NO : [tags_ containsObject:tag];
2929 - (NSString *) primaryPurpose {
2930 for (NSString *tag in tags_)
2931 if ([tag hasPrefix:@"purpose::"])
2932 return [tag substringFromIndex:9];
2936 - (NSArray *) purposes {
2937 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2938 for (NSString *tag in tags_)
2939 if ([tag hasPrefix:@"purpose::"])
2940 [purposes addObject:[tag substringFromIndex:9]];
2941 return [purposes count] == 0 ? nil : purposes;
2944 - (bool) isCommercial {
2945 return [self hasTag:@"cydia::commercial"];
2948 - (void) setIndex:(size_t)index {
2949 if (metadata_->index_ != index)
2950 metadata_->index_ = index;
2953 - (CYString &) cyname {
2954 return name_.empty() ? id_ : name_;
2957 - (uint32_t) compareBySection:(NSArray *)sections {
2958 NSString *section([self section]);
2959 for (size_t i(0), e([sections count]); i != e; ++i) {
2960 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2964 return _not(uint32_t);
2968 @synchronized (database_) {
2969 pkgProblemResolver *resolver = [database_ resolver];
2970 resolver->Clear(iterator_);
2972 pkgCacheFile &cache([database_ cache]);
2973 cache->SetReInstall(iterator_, false);
2974 cache->MarkKeep(iterator_, false);
2978 @synchronized (database_) {
2979 pkgProblemResolver *resolver = [database_ resolver];
2980 resolver->Clear(iterator_);
2981 resolver->Protect(iterator_);
2983 pkgCacheFile &cache([database_ cache]);
2984 cache->SetReInstall(iterator_, false);
2985 cache->MarkInstall(iterator_, false);
2987 pkgDepCache::StateCache &state((*cache)[iterator_]);
2988 if (!state.Install())
2989 cache->SetReInstall(iterator_, true);
2993 @synchronized (database_) {
2994 pkgProblemResolver *resolver = [database_ resolver];
2995 resolver->Clear(iterator_);
2996 resolver->Remove(iterator_);
2997 resolver->Protect(iterator_);
2999 pkgCacheFile &cache([database_ cache]);
3000 cache->SetReInstall(iterator_, false);
3001 cache->MarkDelete(iterator_, true);
3004 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3005 _profile(Package$isUnfilteredAndSearchedForBy)
3008 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3009 value &= [self unfiltered];
3012 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3013 value &= [self matches:search];
3020 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3021 if ([search length] == 0)
3024 _profile(Package$isUnfilteredAndSelectedForBy)
3027 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3028 value &= [self unfiltered];
3031 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3032 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3039 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3040 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3043 - (bool) isVisibleInSection:(NSString *)name {
3044 NSString *section([self section]);
3048 section == nil && [name length] == 0 ||
3049 [name isEqualToString:section]
3050 ) && [self visible];
3053 - (bool) isVisibleInSource:(Source *)source {
3054 return [self source] == source && [self visible];
3059 /* Section Class {{{ */
3060 @interface Section : NSObject {
3065 NSString *localized_;
3068 - (NSComparisonResult) compareByLocalized:(Section *)section;
3069 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3070 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3071 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3072 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3073 - (NSString *) name;
3080 - (void) addToCount;
3082 - (void) setCount:(size_t)count;
3083 - (NSString *) localized;
3087 @implementation Section
3091 if (localized_ != nil)
3092 [localized_ release];
3096 - (NSComparisonResult) compareByLocalized:(Section *)section {
3097 NSString *lhs(localized_);
3098 NSString *rhs([section localized]);
3100 /*if ([lhs length] != 0 && [rhs length] != 0) {
3101 unichar lhc = [lhs characterAtIndex:0];
3102 unichar rhc = [rhs characterAtIndex:0];
3104 if (isalpha(lhc) && !isalpha(rhc))
3105 return NSOrderedAscending;
3106 else if (!isalpha(lhc) && isalpha(rhc))
3107 return NSOrderedDescending;
3110 return [lhs compare:rhs options:LaxCompareOptions_];
3113 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3114 if ((self = [self initWithName:name localize:NO]) != nil) {
3115 if (localized != nil)
3116 localized_ = [localized retain];
3120 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3121 return [self initWithName:name row:0 localize:localize];
3124 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3125 if ((self = [super init]) != nil) {
3126 name_ = [name retain];
3130 localized_ = [LocalizeSection(name_) retain];
3134 /* XXX: localize the index thingees */
3135 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3136 if ((self = [super init]) != nil) {
3137 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3143 - (NSString *) name {
3163 - (void) addToCount {
3167 - (void) setCount:(size_t)count {
3171 - (NSString *) localized {
3178 static NSString *Colon_;
3179 static NSString *Elision_;
3180 static NSString *Error_;
3181 static NSString *Warning_;
3183 /* Database Implementation {{{ */
3184 @implementation Database
3186 + (Database *) sharedInstance {
3187 static Database *instance;
3188 if (instance == nil)
3189 instance = [[Database alloc] init];
3197 - (void) releasePackages {
3198 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3199 CFArrayRemoveAllValues(packages_);
3203 // XXX: actually implement this thing
3206 CFRelease(deadSources_);
3207 [self releasePackages];
3208 apr_pool_destroy(pool_);
3209 NSRecycleZone(zone_);
3213 - (void) _readCydia:(NSNumber *)fd { _pooled
3214 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3215 std::istream is(&ib);
3218 static Pcre finish_r("^finish:([^:]*)$");
3220 while (std::getline(is, line)) {
3221 const char *data(line.c_str());
3222 size_t size = line.size();
3223 lprintf("C:%s\n", data);
3225 if (finish_r(data, size)) {
3226 NSString *finish = finish_r[1];
3227 int index = [Finishes_ indexOfObject:finish];
3228 if (index != INT_MAX && index > Finish_)
3236 - (void) _readStatus:(NSNumber *)fd { _pooled
3237 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3238 std::istream is(&ib);
3241 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3242 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3244 while (std::getline(is, line)) {
3245 const char *data(line.c_str());
3246 size_t size(line.size());
3247 lprintf("S:%s\n", data);
3249 if (conffile_r(data, size)) {
3250 [delegate_ setConfigurationData:conffile_r[1]];
3251 } else if (strncmp(data, "status: ", 8) == 0) {
3252 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3253 [delegate_ setProgressTitle:string];
3254 } else if (pmstatus_r(data, size)) {
3255 std::string type([pmstatus_r[1] UTF8String]);
3256 NSString *id = pmstatus_r[2];
3258 float percent([pmstatus_r[3] floatValue]);
3259 [delegate_ setProgressPercent:(percent / 100)];
3261 NSString *string = pmstatus_r[4];
3263 if (type == "pmerror")
3264 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3265 withObject:[NSArray arrayWithObjects:string, id, nil]
3268 else if (type == "pmstatus") {
3269 [delegate_ setProgressTitle:string];
3270 } else if (type == "pmconffile")
3271 [delegate_ setConfigurationData:string];
3273 lprintf("E:unknown pmstatus\n");
3275 lprintf("E:unknown status\n");
3281 - (void) _readOutput:(NSNumber *)fd { _pooled
3282 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3283 std::istream is(&ib);
3286 while (std::getline(is, line)) {
3287 lprintf("O:%s\n", line.c_str());
3288 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3298 - (Package *) packageWithName:(NSString *)name {
3299 @synchronized (self) {
3300 if (static_cast<pkgDepCache *>(cache_) == NULL)
3302 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3303 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3307 if ((self = [super init]) != nil) {
3314 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3315 apr_pool_create(&pool_, NULL);
3317 size_t capacity(MetaFile_->active_);
3323 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3324 deadSources_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
3328 _assert(pipe(fds) != -1);
3331 _config->Set("APT::Keep-Fds::", cydiafd_);
3332 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3335 detachNewThreadSelector:@selector(_readCydia:)
3337 withObject:[NSNumber numberWithInt:fds[0]]
3340 _assert(pipe(fds) != -1);
3344 detachNewThreadSelector:@selector(_readStatus:)
3346 withObject:[NSNumber numberWithInt:fds[0]]
3349 _assert(pipe(fds) != -1);
3350 _assert(dup2(fds[0], 0) != -1);
3351 _assert(close(fds[0]) != -1);
3353 input_ = fdopen(fds[1], "a");
3355 _assert(pipe(fds) != -1);
3356 _assert(dup2(fds[1], 1) != -1);
3357 _assert(close(fds[1]) != -1);
3360 detachNewThreadSelector:@selector(_readOutput:)
3362 withObject:[NSNumber numberWithInt:fds[0]]
3367 - (pkgCacheFile &) cache {
3371 - (pkgDepCache::Policy *) policy {
3375 - (pkgRecords *) records {
3379 - (pkgProblemResolver *) resolver {
3383 - (pkgAcquire &) fetcher {
3387 - (pkgSourceList &) list {
3391 - (NSArray *) packages {
3392 return (NSArray *) packages_;
3395 - (NSArray *) sources {
3396 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3397 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3398 [sources addObject:i->second];
3399 [sources addObjectsFromArray:(NSArray *)deadSources_];
3403 - (Source *) sourceWithKey:(NSString *)key {
3404 for (Source *source in [self sources]) {
3405 if ([[source key] isEqualToString:key])
3410 - (bool) popErrorWithTitle:(NSString *)title {
3412 std::string message;
3414 while (!_error->empty()) {
3416 bool warning(!_error->PopMessage(error));
3420 size_t size(error.size());
3421 if (size == 0 || error[size - 1] != '\n')
3423 error.resize(size - 1);
3425 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3427 if (!message.empty())
3432 if (fatal && !message.empty())
3433 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3438 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3439 return [self popErrorWithTitle:title] || !success;
3442 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3443 @synchronized (self) {
3446 [self releasePackages];
3449 CFArrayRemoveAllValues(deadSources_);
3469 apr_pool_clear(pool_);
3471 NSRecycleZone(zone_);
3472 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3474 int chk(creat("/tmp/cydia.chk", 0644));
3478 if (invocation != nil)
3479 [invocation invoke];
3481 NSString *title(UCLocalize("DATABASE"));
3484 while (!cache_.Open(progress_, true)) { pop:
3486 bool warning(!_error->PopMessage(error));
3487 lprintf("cache_.Open():[%s]\n", error.c_str());
3489 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3490 [delegate_ repairWithSelector:@selector(configure)];
3491 else if (error == "The package lists or status file could not be parsed or opened.")
3492 [delegate_ repairWithSelector:@selector(update)];
3493 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3494 else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3495 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, Error_, title]];
3496 // else if (error == "The list of sources could not be read.")
3498 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3508 unlink("/tmp/cydia.chk");
3510 now_ = [[NSDate date] timeIntervalSince1970];
3512 policy_ = new pkgDepCache::Policy();
3513 records_ = new pkgRecords(cache_);
3514 resolver_ = new pkgProblemResolver(cache_);
3515 fetcher_ = new pkgAcquire(&status_);
3518 list_ = new pkgSourceList();
3519 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3522 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3523 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3527 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3530 if (cache_->BrokenCount() != 0) {
3531 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3534 if (cache_->BrokenCount() != 0) {
3535 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3539 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3543 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3545 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3546 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3547 // XXX: this could be more intelligent
3548 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3549 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3550 if (!cached.end()) {
3551 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3556 CFArrayAppendValue(deadSources_, [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3560 /*std::vector<Package *> packages;
3561 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3562 [packages_ release];
3567 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3568 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3569 //packages.push_back(package);
3570 CFArrayAppendValue(packages_, [package retain]);
3574 /*if (packages.empty())
3575 packages_ = [[NSArray alloc] init];
3577 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3580 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3581 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3582 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3590 /*if (!packages.empty())
3591 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3592 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3594 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3596 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3598 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3602 size_t count(CFArrayGetCount(packages_));
3603 MetaFile_->active_ = count;
3605 for (size_t index(0); index != count; ++index)
3606 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3610 } } CYPoolEnd() _trace(); }
3613 @synchronized (self) {
3615 resolver_ = new pkgProblemResolver(cache_);
3617 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3618 if (!cache_[iterator].Keep())
3619 cache_->MarkKeep(iterator, false);
3620 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3621 cache_->SetReInstall(iterator, false);
3624 - (void) configure {
3625 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3627 system([dpkg UTF8String]);
3632 // XXX: I don't remember this condition
3637 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3639 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3641 if ([self popErrorWithTitle:title])
3645 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3648 public pkgArchiveCleaner
3651 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3656 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3663 fetcher_->Shutdown();
3665 pkgRecords records(cache_);
3667 lock_ = new FileFd();
3668 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3670 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3672 if ([self popErrorWithTitle:title])
3676 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3679 manager_ = (_system->CreatePM(cache_));
3680 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3687 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3689 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3691 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3693 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3694 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3697 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3702 [CydiaApp retainNetworkActivityIndicator];
3704 bool failed = false;
3705 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3706 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3708 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3711 std::string uri = (*item)->DescURI();
3712 std::string error = (*item)->ErrorText;
3714 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3717 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3718 withObject:[NSArray arrayWithObjects:
3719 [NSString stringWithUTF8String:error.c_str()],
3725 [CydiaApp releaseNetworkActivityIndicator];
3733 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3735 if (_error->PendingError()) {
3740 if (result == pkgPackageManager::Failed) {
3745 if (result != pkgPackageManager::Completed) {
3750 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3752 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3754 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3755 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3758 if (![before isEqualToArray:after])
3763 NSString *title(UCLocalize("UPGRADE"));
3764 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3770 [self updateWithStatus:status_];
3773 - (void) updateWithStatus:(Status &)status {
3774 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3775 NSString *title(UCLocalize("REFRESHING_DATA"));
3778 if (!list.ReadMainList())
3779 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3782 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3783 if ([self popErrorWithTitle:title])
3786 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3787 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3788 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3790 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3794 - (void) setDelegate:(id)delegate {
3795 delegate_ = delegate;
3796 status_.setDelegate(delegate);
3797 progress_.setDelegate(delegate);
3800 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3801 SourceMap::const_iterator i(sources_.find(file->ID));
3802 return i == sources_.end() ? nil : i->second;
3805 - (NSString *) mappedSectionForPointer:(const char *)section {
3806 _H<NSString> *mapped;
3808 _profile(Database$mappedSectionForPointer$Cache)
3809 mapped = §ions_[section];
3812 if (*mapped == NULL) {
3813 size_t length(strlen(section));
3814 char spaced[length + 1];
3816 _profile(Database$mappedSectionForPointer$Replace)
3817 for (size_t index(0); index != length; ++index)
3818 spaced[index] = section[index] == '_' ? ' ' : section[index];
3819 spaced[length] = '\0';
3824 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3825 string = [NSString stringWithUTF8String:spaced];
3828 _profile(Database$mappedSectionForPointer$Map)
3829 string = [SectionMap_ objectForKey:string] ?: string;
3839 /* Web Scripting {{{ */
3840 @interface CydiaObject : NSObject {
3842 _transient id delegate_;
3845 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3849 @implementation CydiaObject
3852 [indirect_ release];
3856 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3857 if ((self = [super init]) != nil) {
3858 indirect_ = [indirect retain];
3862 - (void) setDelegate:(id)delegate {
3863 delegate_ = delegate;
3866 + (NSArray *) _attributeKeys {
3867 return [NSArray arrayWithObjects:
3876 - (NSArray *) attributeKeys {
3877 return [[self class] _attributeKeys];
3880 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3881 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3884 - (NSString *) device {
3885 return [[UIDevice currentDevice] uniqueIdentifier];
3888 #if 0 // XXX: implement!
3889 - (NSString *) mac {
3890 if (![indirect_ promptForSensitive:@"Mac Address"])
3894 - (NSString *) serial {
3895 if (![indirect_ promptForSensitive:@"Serial #"])
3899 - (NSString *) firewire {
3900 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3904 - (NSString *) imei {
3905 if (![indirect_ promptForSensitive:@"IMEI"])
3910 + (NSString *) webScriptNameForSelector:(SEL)selector {
3912 else if (selector == @selector(close))
3914 else if (selector == @selector(du:))
3916 else if (selector == @selector(stringWithFormat:arguments:))
3918 else if (selector == @selector(getInstalledPackages))
3919 return @"getInstalledPackages";
3920 else if (selector == @selector(getPackageById:))
3921 return @"getPackageById";
3922 else if (selector == @selector(installPackages:))
3923 return @"installPackages";
3924 else if (selector == @selector(localizedStringForKey:value:table:))
3926 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3927 return @"setButtonImage";
3928 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3929 return @"setButtonTitle";
3930 else if (selector == @selector(setPopupHook:))
3931 return @"setPopupHook";
3932 else if (selector == @selector(setSpecial:))
3933 return @"setSpecial";
3934 else if (selector == @selector(setToken:))
3936 else if (selector == @selector(setViewportWidth:))
3937 return @"setViewportWidth";
3938 else if (selector == @selector(statfs:))
3940 else if (selector == @selector(supports:))
3946 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3947 return [self webScriptNameForSelector:selector] == nil;
3950 - (BOOL) supports:(NSString *)feature {
3951 return [feature isEqualToString:@"window.open"];
3954 - (NSArray *) getInstalledPackages {
3955 NSArray *packages([[Database sharedInstance] packages]);
3956 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3957 for (Package *package in packages)
3958 if ([package installed] != nil)
3959 [installed addObject:package];
3963 - (Package *) getPackageById:(NSString *)id {
3964 Package *package([[Database sharedInstance] packageWithName:id]);
3969 - (NSArray *) statfs:(NSString *)path {
3972 if (path == nil || statfs([path UTF8String], &stat) == -1)
3975 return [NSArray arrayWithObjects:
3976 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3977 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3978 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3982 - (NSNumber *) du:(NSString *)path {
3983 NSNumber *value(nil);
3986 _assert(pipe(fds) != -1);
3988 pid_t pid(ExecFork());
3990 _assert(dup2(fds[1], 1) != -1);
3991 _assert(close(fds[0]) != -1);
3992 _assert(close(fds[1]) != -1);
3993 /* XXX: this should probably not use du */
3994 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3999 _assert(close(fds[1]) != -1);
4001 if (FILE *du = fdopen(fds[0], "r")) {
4003 while (fgets(line, sizeof(line), du) != NULL) {
4004 size_t length(strlen(line));
4005 while (length != 0 && line[length - 1] == '\n')
4006 line[--length] = '\0';
4007 if (char *tab = strchr(line, '\t')) {
4009 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4014 } else _assert(close(fds[0]));
4018 if (waitpid(pid, &status, 0) == -1)
4021 else _assert(false);
4030 - (void) installPackages:(NSArray *)packages {
4031 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4034 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4035 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4038 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4039 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4042 - (void) setSpecial:(id)function {
4043 [indirect_ setSpecial:function];
4046 - (void) setToken:(NSString *)token {
4049 Token_ = [token retain];
4051 [Metadata_ setObject:Token_ forKey:@"Token"];
4055 - (void) setPopupHook:(id)function {
4056 [indirect_ setPopupHook:function];
4059 - (void) setViewportWidth:(float)width {
4060 [indirect_ setViewportWidth:width];
4063 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4064 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4065 unsigned count([arguments count]);
4067 for (unsigned i(0); i != count; ++i)
4068 values[i] = [arguments objectAtIndex:i];
4069 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4072 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4073 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4075 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4077 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4083 /* @ Loading... Indicator {{{ */
4084 @interface CYLoadingIndicator : UIView {
4085 UIActivityIndicatorView *spinner_;
4090 @property (readonly, nonatomic) UILabel *label;
4091 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4095 @implementation CYLoadingIndicator
4097 - (id) initWithFrame:(CGRect)frame {
4098 if ((self = [super initWithFrame:frame]) != nil) {
4099 container_ = [[[UIView alloc] init] autorelease];
4100 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4102 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4103 [spinner_ startAnimating];
4104 [container_ addSubview:spinner_];
4106 label_ = [[[UILabel alloc] init] autorelease];
4107 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4108 [label_ setBackgroundColor:[UIColor clearColor]];
4109 [label_ setTextColor:[UIColor blackColor]];
4110 [label_ setShadowColor:[UIColor whiteColor]];
4111 [label_ setShadowOffset:CGSizeMake(0, 1)];
4112 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4113 [container_ addSubview:label_];
4115 CGSize viewsize = frame.size;
4116 CGSize spinnersize = [spinner_ bounds].size;
4117 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4118 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4120 CGRect containrect = {
4121 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4122 CGSizeMake(bothwidth, spinnersize.height)
4125 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4133 [container_ setFrame:containrect];
4134 [spinner_ setFrame:spinrect];
4135 [label_ setFrame:textrect];
4136 [self addSubview:container_];
4140 - (UILabel *) label {
4144 - (UIActivityIndicatorView *) activityIndicatorView {
4150 /* Emulated Loading Controller {{{ */
4151 @interface CYEmulatedLoadingController : CYViewController <
4153 ConfigurationDelegate
4155 _transient Database *database_;
4156 CYLoadingIndicator *indicator_;
4158 UINavigationBar *navbar_;
4163 @implementation CYEmulatedLoadingController
4166 [self releaseSubviews];
4167 [database_ setDelegate:nil];
4172 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4173 CYAlertView *sheet([[[CYAlertView alloc]
4175 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4176 defaultButtonIndex:0
4179 [sheet setMessage:error];
4180 [sheet yieldToPopupAlertAnimated:YES];
4184 - (void) setProgressTitle:(NSString *)title { }
4185 - (void) setProgressPercent:(float)percent { }
4186 - (void) startProgress { }
4187 - (void) addProgressOutput:(NSString *)output { }
4188 - (bool) isCancelling:(size_t)received { return NO; }
4189 - (void) setConfigurationData:(NSString *)data { }
4191 - (void) repairWithSelector:(SEL)selector {
4192 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("REPAIRING"), nil] waitUntilDone:YES];
4193 [database_ performSelector:selector];
4195 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil] waitUntilDone:YES];
4198 - (id) initWithDatabase:(Database *)database {
4199 if ((self = [super init]) != nil) {
4200 database_ = database;
4201 [database_ setDelegate:self];
4206 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4207 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4209 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4210 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4211 [[self view] addSubview:indicator_];
4213 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4214 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4215 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4216 [[self view] addSubview:tabbar_];
4218 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4219 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4220 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4221 [[self view] addSubview:navbar_];
4224 - (void) releaseSubviews {
4225 [indicator_ release];
4238 /* Cydia Browser Controller {{{ */
4239 @interface CYBrowserController : BrowserController {
4240 CydiaObject *cydia_;
4245 @implementation CYBrowserController
4252 - (NSURL *) navigationURL {
4253 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4256 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4259 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4260 [super webView:view didClearWindowObject:window forFrame:frame];
4262 WebDataSource *source([frame dataSource]);
4263 NSURLResponse *response([source response]);
4265 NSURL *url([response URL]);
4266 NSString *scheme([url scheme]);
4267 NSString *host([url host]);
4269 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4270 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4271 NSDictionary *headers([http allHeaderFields]);
4272 [self setHeaders:headers forHost:host];
4276 [host isEqualToString:@"cydia.saurik.com"] ||
4277 [host hasSuffix:@".cydia.saurik.com"] ||
4278 [scheme isEqualToString:@"file"]
4280 [window setValue:cydia_ forKey:@"cydia"];
4283 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4284 if (System_ != NULL)
4285 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4286 if (Machine_ != NULL)
4287 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4289 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4291 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4294 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4295 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4296 [self _setMoreHeaders:copy];
4300 - (void) setDelegate:(id)delegate {
4301 [super setDelegate:delegate];
4302 [cydia_ setDelegate:delegate];
4306 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4307 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4309 WebView *webview([[webview_ _documentView] webView]);
4311 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4313 NSString *application = package == nil ? @"Cydia" : [NSString
4314 stringWithFormat:@"Cydia/%@",
4319 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4321 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4322 if (Product_ != nil)
4323 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4325 [webview setApplicationNameForUserAgent:application];
4333 @interface NSObject (CydiaScript)
4334 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4337 @implementation NSObject (CydiaScript)
4339 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4345 @implementation NSArray (CydiaScript)
4347 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4348 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4349 for (size_t i(0), e([self count]); i != e; ++i)
4350 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4356 @implementation NSDictionary (CydiaScript)
4358 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4359 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4361 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4368 /* Confirmation Controller {{{ */
4369 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4370 if (!iterator.end())
4371 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4372 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4374 pkgCache::PkgIterator package(dep.TargetPkg());
4377 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4384 @protocol ConfirmationControllerDelegate
4385 - (void) cancelAndClear:(bool)clear;
4386 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4390 @interface ConfirmationController : CYBrowserController {
4391 _transient Database *database_;
4393 UIAlertView *essential_;
4395 NSDictionary *changes_;
4396 NSMutableArray *issues_;
4397 NSDictionary *sizes_;
4402 - (id) initWithDatabase:(Database *)database;
4406 @implementation ConfirmationController
4413 if (essential_ != nil)
4414 [essential_ release];
4419 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4420 NSString *context([alert context]);
4422 if ([context isEqualToString:@"remove"]) {
4423 if (button == [alert cancelButtonIndex]) {
4424 [self dismissModalViewControllerAnimated:YES];
4425 } else if (button == [alert firstOtherButtonIndex]) {
4428 [delegate_ confirmWithNavigationController:[self navigationController]];
4431 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4432 } else if ([context isEqualToString:@"unable"]) {
4433 [self dismissModalViewControllerAnimated:YES];
4434 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4436 [super alertView:alert clickedButtonAtIndex:button];
4440 - (void) _doContinue {
4441 [self dismissModalViewControllerAnimated:YES];
4442 [delegate_ cancelAndClear:NO];
4445 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4446 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4450 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4451 [super webView:view didClearWindowObject:window forFrame:frame];
4453 [window setValue:[changes_ Cydia$webScriptObjectInContext:window] forKey:@"changes"];
4454 [window setValue:[issues_ Cydia$webScriptObjectInContext:window] forKey:@"issues"];
4455 [window setValue:[sizes_ Cydia$webScriptObjectInContext:window] forKey:@"sizes"];
4457 [window setValue:self forKey:@"queue"];
4460 - (id) initWithDatabase:(Database *)database {
4461 if ((self = [super init]) != nil) {
4462 database_ = database;
4464 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4465 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4466 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4467 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4468 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4472 pkgCacheFile &cache([database_ cache]);
4473 NSArray *packages([database_ packages]);
4474 pkgDepCache::Policy *policy([database_ policy]);
4476 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4478 for (Package *package in packages) {
4479 pkgCache::PkgIterator iterator([package iterator]);
4480 NSString *name([package id]);
4482 if ([package broken]) {
4483 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4485 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4487 reasons, @"reasons",
4490 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4494 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4495 pkgCache::DepIterator start;
4496 pkgCache::DepIterator end;
4497 dep.GlobOr(start, end); // ++dep
4499 if (!cache->IsImportantDep(end))
4501 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4504 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4506 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4507 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4508 clauses, @"clauses",
4512 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4514 pkgCache::PkgIterator target(start.TargetPkg());
4515 if (target->ProvidesList != 0)
4516 reason = @"missing";
4518 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4520 reason = @"installed";
4521 installed = [NSString stringWithUTF8String:ver.VerStr()];
4522 } else if (!cache[target].CandidateVerIter(cache).end())
4523 reason = @"uninstalled";
4524 else if (target->ProvidesList == 0)
4525 reason = @"uninstallable";
4527 reason = @"virtual";
4530 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4531 [NSString stringWithUTF8String:start.CompType()], @"operator",
4532 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4535 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4536 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4537 version, @"version",
4539 installed, @"installed",
4542 // yes, seriously. (wtf?)
4550 pkgDepCache::StateCache &state(cache[iterator]);
4552 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4554 if (state.NewInstall())
4555 [installs addObject:name];
4556 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4557 [reinstalls addObject:name];
4558 else if (state.Upgrade())
4559 [upgrades addObject:name];
4560 else if (state.Downgrade())
4561 [downgrades addObject:name];
4562 else if (!state.Delete())
4564 else if (special_r(name))
4565 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4566 [NSNull null], @"package",
4567 [NSArray arrayWithObjects:
4568 [NSDictionary dictionaryWithObjectsAndKeys:
4569 @"Conflicts", @"relationship",
4570 [NSArray arrayWithObjects:
4571 [NSDictionary dictionaryWithObjectsAndKeys:
4573 [NSNull null], @"version",
4574 @"installed", @"reason",
4581 if ([package essential])
4583 [removes addObject:name];
4586 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4587 substrate_ |= DepSubstrate(iterator.CurrentVer());
4592 else if (Advanced_) {
4593 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4595 essential_ = [[UIAlertView alloc]
4596 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4597 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4599 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4601 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4605 [essential_ setContext:@"remove"];
4607 essential_ = [[UIAlertView alloc]
4608 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4609 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4611 cancelButtonTitle:UCLocalize("OKAY")
4612 otherButtonTitles:nil
4615 [essential_ setContext:@"unable"];
4618 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4619 installs, @"installs",
4620 reinstalls, @"reinstalls",
4621 upgrades, @"upgrades",
4622 downgrades, @"downgrades",
4623 removes, @"removes",
4626 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4627 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4628 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4631 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4633 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4634 initWithTitle:UCLocalize("CANCEL")
4635 style:UIBarButtonItemStylePlain
4637 action:@selector(cancelButtonClicked)
4643 - (void) applyRightButton {
4644 if ([issues_ count] == 0 && ![self isLoading])
4645 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4646 initWithTitle:UCLocalize("CONFIRM")
4647 style:UIBarButtonItemStyleDone
4649 action:@selector(confirmButtonClicked)
4652 [[self navigationItem] setRightBarButtonItem:nil];
4656 - (void) cancelButtonClicked {
4657 [self dismissModalViewControllerAnimated:YES];
4658 [delegate_ cancelAndClear:YES];
4662 - (void) confirmButtonClicked {
4663 if (essential_ != nil)
4668 [delegate_ confirmWithNavigationController:[self navigationController]];
4676 /* Progress Data {{{ */
4677 @interface ProgressData : NSObject {
4679 // XXX: should these really both be _transient?
4680 _transient id target_;
4681 _transient id object_;
4684 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4692 @implementation ProgressData
4694 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4695 if ((self = [super init]) != nil) {
4696 selector_ = selector;
4716 /* Progress Controller {{{ */
4717 @interface ProgressController : CYViewController <
4718 ConfigurationDelegate,
4721 _transient Database *database_;
4722 UIProgressBar *progress_;
4723 UITextView *output_;
4724 UITextLabel *status_;
4725 UIPushButton *close_;
4727 SHA1SumValue springlist_;
4728 SHA1SumValue notifyconf_;
4732 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4734 - (void) _retachThread;
4735 - (void) _detachNewThreadData:(ProgressData *)data;
4736 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4742 @protocol ProgressControllerDelegate
4743 - (void) progressControllerIsComplete:(ProgressController *)sender;
4746 @implementation ProgressController
4749 [database_ setDelegate:nil];
4750 [progress_ release];
4759 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4760 if ((self = [super init]) != nil) {
4761 database_ = database;
4762 [database_ setDelegate:self];
4763 delegate_ = delegate;
4765 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4767 progress_ = [[UIProgressBar alloc] init];
4768 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4769 [progress_ setStyle:0];
4771 status_ = [[UITextLabel alloc] init];
4772 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4773 [status_ setColor:[UIColor whiteColor]];
4774 [status_ setBackgroundColor:[UIColor clearColor]];
4775 [status_ setCentersHorizontally:YES];
4776 //[status_ setFont:font];
4778 output_ = [[UITextView alloc] init];
4779 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4780 //[output_ setTextFont:@"Courier New"];
4781 [output_ setFont:[[output_ font] fontWithSize:12]];
4782 [output_ setTextColor:[UIColor whiteColor]];
4783 [output_ setBackgroundColor:[UIColor clearColor]];
4784 [output_ setMarginTop:0];
4785 [output_ setAllowsRubberBanding:YES];
4786 [output_ setEditable:NO];
4787 [[self view] addSubview:output_];
4789 close_ = [[UIPushButton alloc] init];
4790 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4791 [close_ setAutosizesToFit:NO];
4792 [close_ setDrawsShadow:YES];
4793 [close_ setStretchBackground:YES];
4794 [close_ setEnabled:YES];
4795 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4796 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4797 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4798 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4802 - (void) positionViews {
4803 CGRect bounds = [[self view] bounds];
4804 CGSize prgsize = [UIProgressBar defaultSize];
4807 (bounds.size.width - prgsize.width) / 2,
4808 bounds.size.height - prgsize.height - 20
4811 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4813 [progress_ setFrame:prgrect];
4814 [status_ setFrame:CGRectMake(
4816 bounds.size.height - prgsize.height - 50,
4817 bounds.size.width - 20,
4820 [output_ setFrame:CGRectMake(
4823 bounds.size.width - 20,
4824 bounds.size.height - 96
4826 [close_ setFrame:CGRectMake(
4827 (bounds.size.width - closewidth) / 2,
4828 bounds.size.height - prgsize.height - 50,
4834 - (void) viewWillAppear:(BOOL)animated {
4835 [super viewDidAppear:animated];
4836 [[self navigationItem] setHidesBackButton:YES];
4837 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4839 [self positionViews];
4842 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4843 [self positionViews];
4846 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4847 NSString *context([alert context]);
4849 if ([context isEqualToString:@"conffile"]) {
4850 FILE *input = [database_ input];
4851 if (button == [alert cancelButtonIndex])
4852 fprintf(input, "N\n");
4853 else if (button == [alert firstOtherButtonIndex])
4854 fprintf(input, "Y\n");
4859 - (void) closeButtonPushed {
4862 UpdateExternalStatus(0);
4866 [self dismissModalViewControllerAnimated:YES];
4870 [delegate_ terminateWithSuccess];
4871 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4872 [delegate_ suspendWithAnimation:YES];
4874 [delegate_ suspend];*/
4886 system("/usr/bin/sbreload");
4892 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4893 SBReboot(SBSSpringBoardServerPort());
4895 reboot2(RB_AUTOBOOT);
4900 - (void) _retachThread {
4901 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4903 [[self view] addSubview:close_];
4904 [progress_ removeFromSuperview];
4905 [status_ removeFromSuperview];
4907 [database_ popErrorWithTitle:title_];
4908 [delegate_ progressControllerIsComplete:self];
4912 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4915 MMap mmap(file, MMap::ReadOnly);
4917 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4918 if (!(notifyconf_ == sha1.Result()))
4925 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4928 MMap mmap(file, MMap::ReadOnly);
4930 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4931 if (!(springlist_ == sha1.Result()))
4937 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4938 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4939 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4940 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4941 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4945 system("su -c /usr/bin/uicache mobile");
4948 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4950 [delegate_ setStatusBarShowsProgress:NO];
4953 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4954 [[data target] performSelector:[data selector] withObject:[data object]];
4955 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4958 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4959 UpdateExternalStatus(1);
4966 title_ = [title retain];
4968 [[self navigationItem] setTitle:title_];
4970 [status_ setText:nil];
4971 [output_ setText:@""];
4972 [progress_ setProgress:0];
4974 [close_ removeFromSuperview];
4975 [[self view] addSubview:progress_];
4976 [[self view] addSubview:status_];
4978 [delegate_ setStatusBarShowsProgress:YES];
4983 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4986 MMap mmap(file, MMap::ReadOnly);
4988 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4989 notifyconf_ = sha1.Result();
4995 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4998 MMap mmap(file, MMap::ReadOnly);
5000 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5001 springlist_ = sha1.Result();
5006 detachNewThreadSelector:@selector(_detachNewThreadData:)
5008 withObject:[[[ProgressData alloc]
5009 initWithSelector:selector
5016 - (void) repairWithSelector:(SEL)selector {
5018 detachNewThreadSelector:selector
5021 title:UCLocalize("REPAIRING")
5025 - (void) setConfigurationData:(NSString *)data {
5027 performSelectorOnMainThread:@selector(_setConfigurationData:)
5033 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
5034 CYAlertView *sheet([[[CYAlertView alloc]
5036 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
5037 defaultButtonIndex:0
5040 [sheet setMessage:error];
5041 [sheet yieldToPopupAlertAnimated:YES];
5045 - (void) setProgressTitle:(NSString *)title {
5047 performSelectorOnMainThread:@selector(_setProgressTitle:)
5053 - (void) setProgressPercent:(float)percent {
5055 performSelectorOnMainThread:@selector(_setProgressPercent:)
5056 withObject:[NSNumber numberWithFloat:percent]
5061 - (void) startProgress {
5064 - (void) addProgressOutput:(NSString *)output {
5066 performSelectorOnMainThread:@selector(_addProgressOutput:)
5072 - (bool) isCancelling:(size_t)received {
5076 - (void) _setConfigurationData:(NSString *)data {
5077 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
5079 if (!conffile_r(data)) {
5080 lprintf("E:invalid conffile\n");
5084 NSString *ofile = conffile_r[1];
5085 //NSString *nfile = conffile_r[2];
5087 UIAlertView *alert = [[[UIAlertView alloc]
5088 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
5089 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
5091 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
5093 UCLocalize("ACCEPT_NEW_COPY"),
5094 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
5098 [alert setContext:@"conffile"];
5102 - (void) _setProgressTitle:(NSString *)title {
5103 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
5104 for (size_t i(0), e([words count]); i != e; ++i) {
5105 NSString *word([words objectAtIndex:i]);
5106 if (Package *package = [database_ packageWithName:word])
5107 [words replaceObjectAtIndex:i withObject:[package name]];
5110 [status_ setText:[words componentsJoinedByString:@" "]];
5113 - (void) _setProgressPercent:(NSNumber *)percent {
5114 [progress_ setProgress:[percent floatValue]];
5117 - (void) _addProgressOutput:(NSString *)output {
5118 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
5119 CGSize size = [output_ contentSize];
5120 CGPoint offset = [output_ contentOffset];
5121 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
5122 CGRect rect = {{0, size.height-1}, {size.width, 1}};
5123 [output_ scrollRectToVisible:rect animated:YES];
5127 - (BOOL) isRunning {
5134 /* Cell Content View {{{ */
5135 @protocol ContentDelegate
5136 - (void) drawContentRect:(CGRect)rect;
5139 @interface ContentView : UIView {
5140 _transient id<ContentDelegate> delegate_;
5145 @implementation ContentView
5147 - (id) initWithFrame:(CGRect)frame {
5148 if ((self = [super initWithFrame:frame]) != nil) {
5149 [self setNeedsDisplayOnBoundsChange:YES];
5153 - (void) setDelegate:(id<ContentDelegate>)delegate {
5154 delegate_ = delegate;
5157 - (void) drawRect:(CGRect)rect {
5158 [super drawRect:rect];
5159 [delegate_ drawContentRect:rect];
5164 /* Cydia TableView Cell {{{ */
5165 @interface CYTableViewCell : UITableViewCell {
5166 ContentView *content_;
5172 @implementation CYTableViewCell
5179 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5180 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5182 if (view == content_) {
5183 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5184 highlighted_ = highlighted;
5187 [super _updateHighlightColorsForView:view highlighted:highlighted];
5190 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5191 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5192 highlighted_ = selected;
5194 [super setSelected:selected animated:animated];
5195 [content_ setNeedsDisplay];
5201 /* Package Cell {{{ */
5202 @interface PackageCell : CYTableViewCell <
5207 NSString *description_;
5215 - (PackageCell *) init;
5216 - (void) setPackage:(Package *)package;
5218 - (void) drawContentRect:(CGRect)rect;
5222 @implementation PackageCell
5224 - (void) clearPackage {
5235 if (description_ != nil) {
5236 [description_ release];
5240 if (source_ != nil) {
5245 if (badge_ != nil) {
5250 if (placard_ != nil) {
5260 [self clearPackage];
5264 - (PackageCell *) init {
5265 CGRect frame(CGRectMake(0, 0, 320, 74));
5266 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5267 UIView *content([self contentView]);
5268 CGRect bounds([content bounds]);
5270 content_ = [[ContentView alloc] initWithFrame:bounds];
5271 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5272 [content addSubview:content_];
5274 [content_ setDelegate:self];
5275 [content_ setOpaque:YES];
5279 - (NSString *) accessibilityLabel {
5280 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5283 - (void) setPackage:(Package *)package {
5284 [self clearPackage];
5287 Source *source = [package source];
5289 icon_ = [[package icon] retain];
5290 name_ = [[package name] retain];
5293 description_ = [package longDescription];
5294 if (description_ == nil)
5295 description_ = [package shortDescription];
5296 if (description_ != nil)
5297 description_ = [description_ retain];
5299 commercial_ = [package isCommercial];
5301 package_ = [package retain];
5303 NSString *label = nil;
5304 bool trusted = false;
5306 if (source != nil) {
5307 label = [source label];
5308 trusted = [source trusted];
5309 } else if ([[package id] isEqualToString:@"firmware"])
5310 label = UCLocalize("APPLE");
5312 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5314 NSString *from(label);
5316 NSString *section = [package simpleSection];
5317 if (section != nil && ![section isEqualToString:label]) {
5318 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5319 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5322 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5323 source_ = [from retain];
5325 if (NSString *purpose = [package primaryPurpose])
5326 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5327 badge_ = [badge_ retain];
5332 if (NSString *mode = [package_ mode]) {
5333 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5334 color = RemovingColor_;
5335 //placard = @"removing";
5337 color = InstallingColor_;
5338 //placard = @"installing";
5341 // XXX: the removing/installing placards are not @2x
5344 color = [UIColor whiteColor];
5346 if ([package installed] != nil)
5347 placard = @"installed";
5352 [content_ setBackgroundColor:color];
5355 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5356 placard_ = [placard_ retain];
5358 [self setNeedsDisplay];
5359 [content_ setNeedsDisplay];
5362 - (void) drawContentRect:(CGRect)rect {
5363 bool highlighted(highlighted_);
5364 float width([self bounds].size.width);
5367 CGContextRef context(UIGraphicsGetCurrentContext());
5368 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5369 CGContextFillRect(context, rect);
5374 rect.size = [icon_ size];
5376 rect.size.width /= 2;
5377 rect.size.height /= 2;
5379 rect.origin.x = 25 - rect.size.width / 2;
5380 rect.origin.y = 25 - rect.size.height / 2;
5382 [icon_ drawInRect:rect];
5385 if (badge_ != nil) {
5387 rect.size = [badge_ size];
5389 rect.size.width /= 2;
5390 rect.size.height /= 2;
5392 rect.origin.x = 36 - rect.size.width / 2;
5393 rect.origin.y = 36 - rect.size.height / 2;
5395 [badge_ drawInRect:rect];
5402 UISetColor(commercial_ ? Purple_ : Black_);
5403 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5404 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5407 UISetColor(commercial_ ? Purplish_ : Gray_);
5408 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5410 if (placard_ != nil)
5411 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5416 /* Section Cell {{{ */
5417 @interface SectionCell : CYTableViewCell <
5429 - (void) setSection:(Section *)section editing:(BOOL)editing;
5433 @implementation SectionCell
5435 - (void) clearSection {
5436 if (basic_ != nil) {
5441 if (section_ != nil) {
5451 if (count_ != nil) {
5458 [self clearSection];
5464 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5465 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5466 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5467 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5468 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5470 UIView *content([self contentView]);
5471 CGRect bounds([content bounds]);
5473 content_ = [[ContentView alloc] initWithFrame:bounds];
5474 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5475 [content addSubview:content_];
5476 [content_ setBackgroundColor:[UIColor whiteColor]];
5478 [content_ setDelegate:self];
5482 - (void) onSwitch:(id)sender {
5483 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5484 if (metadata == nil) {
5485 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5486 [Sections_ setObject:metadata forKey:basic_];
5489 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5493 - (void) setSection:(Section *)section editing:(BOOL)editing {
5494 if (editing != editing_) {
5496 [switch_ removeFromSuperview];
5498 [self addSubview:switch_];
5502 [self clearSection];
5504 if (section == nil) {
5505 name_ = [UCLocalize("ALL_PACKAGES") retain];
5508 basic_ = [section name];
5510 basic_ = [basic_ retain];
5512 section_ = [section localized];
5513 if (section_ != nil)
5514 section_ = [section_ retain];
5516 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5517 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5520 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5523 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5524 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5526 [content_ setNeedsDisplay];
5529 - (void) setFrame:(CGRect)frame {
5530 [super setFrame:frame];
5532 CGRect rect([switch_ frame]);
5533 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5536 - (NSString *) accessibilityLabel {
5540 - (void) drawContentRect:(CGRect)rect {
5541 bool highlighted(highlighted_ && !editing_);
5543 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5548 float width(rect.size.width);
5554 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5556 CGSize size = [count_ sizeWithFont:Font14_];
5560 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5566 /* File Table {{{ */
5567 @interface FileTable : CYViewController <
5568 UITableViewDataSource,
5571 _transient Database *database_;
5574 NSMutableArray *files_;
5578 - (id) initWithDatabase:(Database *)database;
5579 - (void) setPackage:(Package *)package;
5583 @implementation FileTable
5586 [self releaseSubviews];
5595 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5596 return files_ == nil ? 0 : [files_ count];
5599 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5603 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5604 static NSString *reuseIdentifier = @"Cell";
5606 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5608 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5609 [cell setFont:[UIFont systemFontOfSize:16]];
5611 [cell setText:[files_ objectAtIndex:indexPath.row]];
5612 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5617 - (NSURL *) navigationURL {
5618 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5622 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5624 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5625 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5626 [list_ setRowHeight:24.0f];
5627 [list_ setDataSource:self];
5628 [list_ setDelegate:self];
5629 [[self view] addSubview:list_];
5632 - (void) viewDidLoad {
5633 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5636 - (void) releaseSubviews {
5641 - (id) initWithDatabase:(Database *)database {
5642 if ((self = [super init]) != nil) {
5643 database_ = database;
5645 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5649 - (void) setPackage:(Package *)package {
5650 if (package_ != nil) {
5651 [package_ autorelease];
5660 [files_ removeAllObjects];
5662 if (package != nil) {
5663 package_ = [package retain];
5664 name_ = [[package id] retain];
5666 if (NSArray *files = [package files])
5667 [files_ addObjectsFromArray:files];
5669 if ([files_ count] != 0) {
5670 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5671 [files_ removeObjectAtIndex:0];
5672 [files_ sortUsingSelector:@selector(compareByPath:)];
5674 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5675 [stack addObject:@"/"];
5677 for (int i(0), e([files_ count]); i != e; ++i) {
5678 NSString *file = [files_ objectAtIndex:i];
5679 while (![file hasPrefix:[stack lastObject]])
5680 [stack removeLastObject];
5681 NSString *directory = [stack lastObject];
5682 [stack addObject:[file stringByAppendingString:@"/"]];
5683 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5684 ([stack count] - 2) * 3, "",
5685 [file substringFromIndex:[directory length]]
5694 - (void) reloadData {
5697 [self setPackage:[database_ packageWithName:name_]];
5702 /* Package Controller {{{ */
5703 @interface CYPackageController : CYBrowserController <
5704 UIActionSheetDelegate
5706 _transient Database *database_;
5710 NSMutableArray *buttons_;
5711 UIBarButtonItem *button_;
5714 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5718 @implementation CYPackageController
5721 if (package_ != nil)
5734 - (NSURL *) navigationURL {
5735 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5738 /* XXX: this is not safe at all... localization of /fail/ */
5739 - (void) _clickButtonWithName:(NSString *)name {
5740 if ([name isEqualToString:UCLocalize("CLEAR")])
5741 [delegate_ clearPackage:package_];
5742 else if ([name isEqualToString:UCLocalize("INSTALL")])
5743 [delegate_ installPackage:package_];
5744 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5745 [delegate_ installPackage:package_];
5746 else if ([name isEqualToString:UCLocalize("REMOVE")])
5747 [delegate_ removePackage:package_];
5748 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5749 [delegate_ installPackage:package_];
5750 else _assert(false);
5753 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5754 NSString *context([sheet context]);
5756 if ([context isEqualToString:@"modify"]) {
5757 if (button != [sheet cancelButtonIndex]) {
5758 NSString *buttonName = [buttons_ objectAtIndex:button];
5759 [self _clickButtonWithName:buttonName];
5762 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5766 - (bool) _allowJavaScriptPanel {
5771 - (void) _customButtonClicked {
5772 int count([buttons_ count]);
5777 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5779 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5780 [buttons addObjectsFromArray:buttons_];
5782 UIActionSheet *sheet = [[[UIActionSheet alloc]
5785 cancelButtonTitle:nil
5786 destructiveButtonTitle:nil
5787 otherButtonTitles:nil
5790 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5792 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5793 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5795 [sheet setContext:@"modify"];
5797 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5801 // We don't want to allow non-commercial packages to do custom things to the install button,
5802 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5803 - (void) customButtonClicked {
5805 [super customButtonClicked];
5807 [self _customButtonClicked];
5810 - (void) reloadButtonClicked {
5811 // Don't reload a commerical package by tapping the loading button,
5812 // but if it's not an Install button, we should forward it on.
5813 if (![package_ uninstalled])
5814 [self _customButtonClicked];
5817 - (void) applyLoadingTitle {
5818 // Don't show "Loading" as the title. Ever.
5821 - (UIBarButtonItem *) rightButton {
5826 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5827 if ((self = [super init]) != nil) {
5828 database_ = database;
5829 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5830 name_ = [[NSString alloc] initWithString:name];
5831 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5835 - (void) reloadData {
5836 if (package_ != nil)
5837 [package_ autorelease];
5838 package_ = [database_ packageWithName:name_];
5840 [buttons_ removeAllObjects];
5842 if (package_ != nil) {
5845 package_ = [package_ retain];
5846 commercial_ = [package_ isCommercial];
5848 if ([package_ mode] != nil)
5849 [buttons_ addObject:UCLocalize("CLEAR")];
5850 if ([package_ source] == nil);
5851 else if ([package_ upgradableAndEssential:NO])
5852 [buttons_ addObject:UCLocalize("UPGRADE")];
5853 else if ([package_ uninstalled])
5854 [buttons_ addObject:UCLocalize("INSTALL")];
5856 [buttons_ addObject:UCLocalize("REINSTALL")];
5857 if (![package_ uninstalled])
5858 [buttons_ addObject:UCLocalize("REMOVE")];
5865 switch ([buttons_ count]) {
5866 case 0: title = nil; break;
5867 case 1: title = [buttons_ objectAtIndex:0]; break;
5868 default: title = UCLocalize("MODIFY"); break;
5871 button_ = [[UIBarButtonItem alloc]
5873 style:UIBarButtonItemStylePlain
5875 action:@selector(customButtonClicked)
5881 - (bool) isLoading {
5882 return commercial_ ? [super isLoading] : false;
5888 /* Package List Controller {{{ */
5889 @interface PackageListController : CYViewController <
5890 UITableViewDataSource,
5893 _transient Database *database_;
5895 NSMutableArray *packages_;
5896 NSMutableArray *sections_;
5898 NSMutableArray *index_;
5899 NSMutableDictionary *indices_;
5903 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5904 - (void) setDelegate:(id)delegate;
5905 - (void) resetCursor;
5909 @implementation PackageListController
5912 [packages_ release];
5913 [sections_ release];
5922 - (void) deselectWithAnimation:(BOOL)animated {
5923 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5926 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5927 CGRect base = [[self view] bounds];
5928 base.size.height -= bounds.size.height;
5929 base.origin = [list_ frame].origin;
5931 [UIView beginAnimations:nil context:NULL];
5932 [UIView setAnimationBeginsFromCurrentState:YES];
5933 [UIView setAnimationCurve:curve];
5934 [UIView setAnimationDuration:duration];
5935 [list_ setFrame:base];
5936 [UIView commitAnimations];
5939 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5940 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5943 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5944 [self resizeForKeyboardBounds:bounds duration:0];
5947 - (void) keyboardWillShow:(NSNotification *)notification {
5950 NSTimeInterval duration;
5951 UIViewAnimationCurve curve;
5952 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5953 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5954 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5955 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5957 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);
5958 UIViewController *base = self;
5959 while ([base parentViewController] != nil)
5960 base = [base parentViewController];
5961 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5962 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5964 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5967 - (void) keyboardWillHide:(NSNotification *)notification {
5968 NSTimeInterval duration;
5969 UIViewAnimationCurve curve;
5970 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5971 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5973 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5976 - (void) viewWillAppear:(BOOL)animated {
5977 [super viewWillAppear:animated];
5979 [self resizeForKeyboardBounds:CGRectZero];
5980 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5981 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5984 - (void) viewWillDisappear:(BOOL)animated {
5985 [super viewWillDisappear:animated];
5987 [self resizeForKeyboardBounds:CGRectZero];
5988 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5989 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5992 - (void) viewDidAppear:(BOOL)animated {
5993 [super viewDidAppear:animated];
5994 [self deselectWithAnimation:animated];
5997 - (void) didSelectPackage:(Package *)package {
5998 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5999 [view setDelegate:delegate_];
6000 [[self navigationController] pushViewController:view animated:YES];
6003 #if TryIndexedCollation
6004 + (BOOL) hasIndexedCollation {
6005 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6009 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6010 NSInteger count([sections_ count]);
6011 return count == 0 ? 1 : count;
6014 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6015 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6017 return [[sections_ objectAtIndex:section] name];
6020 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6021 if ([sections_ count] == 0)
6023 return [[sections_ objectAtIndex:section] count];
6026 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6027 @synchronized (database_) {
6028 if ([database_ era] != era_)
6031 Section *section([sections_ objectAtIndex:[path section]]);
6032 NSInteger row([path row]);
6033 Package *package([packages_ objectAtIndex:([section row] + row)]);
6034 return [[package retain] autorelease];
6037 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6038 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6040 cell = [[[PackageCell alloc] init] autorelease];
6041 [cell setPackage:[self packageAtIndexPath:path]];
6045 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6046 Package *package([self packageAtIndexPath:path]);
6047 package = [database_ packageWithName:[package id]];
6048 [self didSelectPackage:package];
6051 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6052 // XXX: is 20 the most optimal number here?
6053 return [packages_ count] > 20 ? index_ : nil;
6056 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6057 #if TryIndexedCollation
6058 if ([[self class] hasIndexedCollation]) {
6059 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6066 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6067 if ((self = [super init]) != nil) {
6068 database_ = database;
6069 title_ = [title copy];
6070 [[self navigationItem] setTitle:title_];
6072 #if TryIndexedCollation
6073 if ([[self class] hasIndexedCollation])
6074 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6077 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6079 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6081 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6082 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6084 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6085 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6086 [list_ setRowHeight:73];
6087 [[self view] addSubview:list_];
6089 [list_ setDataSource:self];
6090 [list_ setDelegate:self];
6094 - (void) setDelegate:(id)delegate {
6095 delegate_ = delegate;
6098 - (bool) hasPackage:(Package *)package {
6102 - (void) reloadData {
6105 era_ = [database_ era];
6106 NSArray *packages = [database_ packages];
6108 [packages_ removeAllObjects];
6109 [sections_ removeAllObjects];
6111 _profile(PackageTable$reloadData$Filter)
6112 for (Package *package in packages)
6113 if ([self hasPackage:package])
6114 [packages_ addObject:package];
6117 [indices_ removeAllObjects];
6119 Section *section = nil;
6121 #if TryIndexedCollation
6122 if ([[self class] hasIndexedCollation]) {
6123 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6124 NSArray *titles = [collation sectionIndexTitles];
6127 _profile(PackageTable$reloadData$Section)
6128 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6132 _profile(PackageTable$reloadData$Section$Package)
6133 package = [packages_ objectAtIndex:offset];
6134 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6137 while (secidx < index) {
6140 _profile(PackageTable$reloadData$Section$Allocate)
6141 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6144 _profile(PackageTable$reloadData$Section$Add)
6145 [sections_ addObject:section];
6149 [section addToCount];
6155 [index_ removeAllObjects];
6157 _profile(PackageTable$reloadData$Section)
6158 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6162 _profile(PackageTable$reloadData$Section$Package)
6163 package = [packages_ objectAtIndex:offset];
6164 index = [package index];
6167 if (section == nil || [section index] != index) {
6168 _profile(PackageTable$reloadData$Section$Allocate)
6169 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6172 [index_ addObject:[section name]];
6173 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6175 _profile(PackageTable$reloadData$Section$Add)
6176 [sections_ addObject:section];
6180 [section addToCount];
6185 _profile(PackageTable$reloadData$List)
6190 - (void) resetCursor {
6191 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6196 /* Filtered Package List Controller {{{ */
6197 @interface FilteredPackageListController : PackageListController {
6203 - (void) setObject:(id)object;
6204 - (void) setObject:(id)object forFilter:(SEL)filter;
6206 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6210 @implementation FilteredPackageListController
6218 - (void) setFilter:(SEL)filter {
6221 /* XXX: this is an unsafe optimization of doomy hell */
6222 Method method(class_getInstanceMethod([Package class], filter));
6223 _assert(method != NULL);
6224 imp_ = method_getImplementation(method);
6225 _assert(imp_ != NULL);
6228 - (void) setObject:(id)object {
6234 object_ = [object retain];
6237 - (void) setObject:(id)object forFilter:(SEL)filter {
6238 [self setFilter:filter];
6239 [self setObject:object];
6242 - (bool) hasPackage:(Package *)package {
6243 _profile(FilteredPackageTable$hasPackage)
6244 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6248 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6249 if ((self = [super initWithDatabase:database title:title]) != nil) {
6250 [self setFilter:filter];
6251 [self setObject:object];
6259 /* Home Controller {{{ */
6260 @interface HomeController : CYBrowserController {
6265 @implementation HomeController
6267 + (BOOL) shouldHideNavigationBar {
6271 - (NSURL *) navigationURL {
6272 return [NSURL URLWithString:@"cydia://home"];
6275 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6276 [super _setMoreHeaders:request];
6279 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6280 if (UniqueID_ != nil)
6281 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6283 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6286 - (void) aboutButtonClicked {
6287 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6289 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6290 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6291 [alert setCancelButtonIndex:0];
6294 @"Copyright (C) 2008-2011\n"
6295 "Jay Freeman (saurik)\n"
6296 "saurik@saurik.com\n"
6297 "http://www.saurik.com/"
6303 - (void) viewWillDisappear:(BOOL)animated {
6304 [super viewWillDisappear:animated];
6306 if ([[self class] shouldHideNavigationBar])
6307 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6310 - (void) viewWillAppear:(BOOL)animated {
6311 if (![self hasLoaded])
6312 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6314 [super viewWillAppear:animated];
6316 if ([[self class] shouldHideNavigationBar])
6317 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6320 - (void) viewDidLoad {
6321 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6322 initWithTitle:UCLocalize("ABOUT")
6323 style:UIBarButtonItemStylePlain
6325 action:@selector(aboutButtonClicked)
6331 /* Manage Controller {{{ */
6332 @interface ManageController : CYBrowserController {
6335 - (void) queueStatusDidChange;
6339 @implementation ManageController
6341 - (NSURL *) navigationURL {
6342 return [NSURL URLWithString:@"cydia://manage"];
6345 - (void) viewWillAppear:(BOOL)animated {
6346 if (![self hasLoaded])
6347 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6349 [super viewWillAppear:animated];
6352 - (void) viewDidLoad {
6353 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6354 initWithTitle:UCLocalize("SETTINGS")
6355 style:UIBarButtonItemStylePlain
6357 action:@selector(settingsButtonClicked)
6360 [self queueStatusDidChange];
6363 - (void) settingsButtonClicked {
6364 [delegate_ showSettings];
6368 - (void) queueButtonClicked {
6372 - (void) applyLoadingTitle {
6373 // Disable "Loading" title.
6376 - (void) applyRightButton {
6377 // Disable right button.
6381 - (void) queueStatusDidChange {
6383 if (!IsWildcat_ && Queuing_) {
6384 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6385 initWithTitle:UCLocalize("QUEUE")
6386 style:UIBarButtonItemStyleDone
6388 action:@selector(queueButtonClicked)
6391 [[self navigationItem] setRightBarButtonItem:nil];
6396 - (bool) isLoading {
6397 // Never show as loading.
6404 /* Refresh Bar {{{ */
6405 @interface RefreshBar : UINavigationBar {
6406 UIProgressIndicator *indicator_;
6407 UITextLabel *prompt_;
6408 UIProgressBar *progress_;
6409 UINavigationButton *cancel_;
6414 @implementation RefreshBar
6417 [indicator_ release];
6419 [progress_ release];
6424 - (void) positionViews {
6425 CGRect frame = [cancel_ frame];
6426 frame.size = [cancel_ sizeThatFits:frame.size];
6427 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6428 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6429 [cancel_ setFrame:frame];
6431 CGSize prgsize = {75, 100};
6433 [self frame].size.width - prgsize.width - 10,
6434 ([self frame].size.height - prgsize.height) / 2
6436 [progress_ setFrame:prgrect];
6438 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6439 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6440 CGRect indrect = {{indoffset, indoffset}, indsize};
6441 [indicator_ setFrame:indrect];
6443 CGSize prmsize = {215, indsize.height + 4};
6445 indoffset * 2 + indsize.width,
6446 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6448 [prompt_ setFrame:prmrect];
6451 - (void) setFrame:(CGRect)frame {
6452 [super setFrame:frame];
6453 [self positionViews];
6456 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6457 if ((self = [super initWithFrame:frame]) != nil) {
6458 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6460 [self setBarStyle:UIBarStyleBlack];
6462 UIBarStyle barstyle([self _barStyle:NO]);
6463 bool ugly(barstyle == UIBarStyleDefault);
6465 UIProgressIndicatorStyle style = ugly ?
6466 UIProgressIndicatorStyleMediumBrown :
6467 UIProgressIndicatorStyleMediumWhite;
6469 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6470 [indicator_ setStyle:style];
6471 [indicator_ startAnimation];
6472 [self addSubview:indicator_];
6474 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6475 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6476 [prompt_ setBackgroundColor:[UIColor clearColor]];
6477 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6478 [self addSubview:prompt_];
6480 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6481 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6482 [progress_ setStyle:0];
6483 [self addSubview:progress_];
6485 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6486 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6487 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6488 [cancel_ setBarStyle:barstyle];
6490 [self positionViews];
6495 [cancel_ removeFromSuperview];
6499 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6500 [progress_ setProgress:0];
6501 [self addSubview:cancel_];
6505 [cancel_ removeFromSuperview];
6508 - (void) setPrompt:(NSString *)prompt {
6509 [prompt_ setText:prompt];
6512 - (void) setProgress:(float)progress {
6513 [progress_ setProgress:progress];
6519 @class CYNavigationController;
6521 /* Cydia Tab Bar Controller {{{ */
6522 @interface CYTabBarController : UITabBarController <
6523 UITabBarControllerDelegate,
6526 _transient Database *database_;
6527 RefreshBar *refreshbar_;
6531 // XXX: ok, "updatedelegate_"?...
6532 _transient NSObject<CydiaDelegate> *updatedelegate_;
6535 UIViewController *remembered_;
6536 _transient UIViewController *transient_;
6539 - (NSArray *) navigationURLCollection;
6540 - (void) dropBar:(BOOL)animated;
6541 - (void) beginUpdate;
6542 - (void) raiseBar:(BOOL)animated;
6547 @implementation CYTabBarController
6549 - (void) setUnselectedViewController:(UIViewController *)transient {
6550 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6551 if (transient != nil) {
6552 if (transient_ == nil)
6553 remembered_ = [[controllers objectAtIndex:0] retain];
6554 transient_ = transient;
6555 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6556 [controllers replaceObjectAtIndex:0 withObject:transient_];
6557 [self setSelectedIndex:0];
6558 [self setViewControllers:controllers];
6559 [self concealTabBarSelection];
6560 } else if (remembered_ != nil) {
6561 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6562 transient_ = transient;
6563 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6564 [remembered_ release];
6566 [self setViewControllers:controllers];
6567 [self revealTabBarSelection];
6571 - (UIViewController *) unselectedViewController {
6575 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6576 if ([self unselectedViewController])
6577 [self setUnselectedViewController:nil];
6580 - (NSArray *) navigationURLCollection {
6581 NSMutableArray *items([NSMutableArray array]);
6583 // XXX: Should this deal with transient view controllers?
6584 for (id navigation in [self viewControllers]) {
6585 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6587 [items addObject:stack];
6593 - (void) reloadData {
6594 for (CYViewController *controller in [self viewControllers])
6595 [controller reloadData];
6597 [(CYNavigationController *)[self unselectedViewController] reloadData];
6601 [refreshbar_ release];
6602 [[NSNotificationCenter defaultCenter] removeObserver:self];
6607 - (id) initWithDatabase:(Database *)database {
6608 if ((self = [super init]) != nil) {
6609 database_ = database;
6610 [self setDelegate:self];
6612 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6613 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6615 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6619 - (void) setUpdate:(NSDate *)date {
6623 - (void) beginUpdate {
6624 [refreshbar_ start];
6627 [updatedelegate_ retainNetworkActivityIndicator];
6631 detachNewThreadSelector:@selector(performUpdate)
6637 - (void) performUpdate { _pooled
6639 status.setDelegate(self);
6640 [database_ updateWithStatus:status];
6643 performSelectorOnMainThread:@selector(completeUpdate)
6649 - (void) stopUpdateWithSelector:(SEL)selector {
6651 [updatedelegate_ releaseNetworkActivityIndicator];
6653 [self raiseBar:YES];
6656 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6659 - (void) completeUpdate {
6662 [self stopUpdateWithSelector:@selector(reloadData)];
6665 - (void) cancelUpdate {
6666 [self stopUpdateWithSelector:@selector(updateData)];
6669 - (void) cancelPressed {
6670 [self cancelUpdate];
6677 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6678 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6681 - (void) startProgress {
6684 - (void) setProgressTitle:(NSString *)title {
6686 performSelectorOnMainThread:@selector(_setProgressTitle:)
6692 - (bool) isCancelling:(size_t)received {
6696 - (void) setProgressPercent:(float)percent {
6698 performSelectorOnMainThread:@selector(_setProgressPercent:)
6699 withObject:[NSNumber numberWithFloat:percent]
6704 - (void) addProgressOutput:(NSString *)output {
6706 performSelectorOnMainThread:@selector(_addProgressOutput:)
6712 - (void) _setProgressTitle:(NSString *)title {
6713 [refreshbar_ setPrompt:title];
6716 - (void) _setProgressPercent:(NSNumber *)percent {
6717 [refreshbar_ setProgress:[percent floatValue]];
6720 - (void) _addProgressOutput:(NSString *)output {
6723 - (void) setUpdateDelegate:(id)delegate {
6724 updatedelegate_ = delegate;
6727 - (CGFloat) statusBarHeight {
6728 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6729 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6731 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6735 - (UIView *) transitionView {
6736 if ([self respondsToSelector:@selector(_transitionView)])
6737 return [self _transitionView];
6739 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6742 - (void) dropBar:(BOOL)animated {
6747 UIView *transition([self transitionView]);
6748 [[self view] addSubview:refreshbar_];
6750 CGRect barframe([refreshbar_ frame]);
6752 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6753 barframe.origin.y = [self statusBarHeight];
6755 barframe.origin.y = 0;
6757 [refreshbar_ setFrame:barframe];
6760 [UIView beginAnimations:nil context:NULL];
6762 CGRect viewframe = [transition frame];
6763 viewframe.origin.y += barframe.size.height;
6764 viewframe.size.height -= barframe.size.height;
6765 [transition setFrame:viewframe];
6768 [UIView commitAnimations];
6770 // Ensure bar has the proper width for our view, it might have changed
6771 barframe.size.width = viewframe.size.width;
6772 [refreshbar_ setFrame:barframe];
6774 // XXX: fix Apple's layout bug
6775 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6778 - (void) raiseBar:(BOOL)animated {
6783 UIView *transition([self transitionView]);
6784 [refreshbar_ removeFromSuperview];
6786 CGRect barframe([refreshbar_ frame]);
6789 [UIView beginAnimations:nil context:NULL];
6791 CGRect viewframe = [transition frame];
6792 viewframe.origin.y -= barframe.size.height;
6793 viewframe.size.height += barframe.size.height;
6794 [transition setFrame:viewframe];
6797 [UIView commitAnimations];
6799 // XXX: fix Apple's layout bug
6800 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6804 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6805 // XXX: fix Apple's layout bug
6806 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6810 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6811 bool dropped(dropped_);
6816 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6821 // XXX: fix Apple's layout bug
6822 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6825 - (void) statusBarFrameChanged:(NSNotification *)notification {
6834 /* Cydia Navigation Controller {{{ */
6835 @interface CYNavigationController : UINavigationController {
6836 _transient Database *database_;
6837 _transient id<UINavigationControllerDelegate> delegate_;
6840 - (NSArray *) navigationURLCollection;
6841 - (id) initWithDatabase:(Database *)database;
6842 - (void) reloadData;
6847 @implementation CYNavigationController
6849 - (NSArray *) navigationURLCollection {
6850 NSMutableArray *stack([NSMutableArray array]);
6852 for (CYViewController *controller in [self viewControllers]) {
6853 NSString *url = [[controller navigationURL] absoluteString];
6855 [stack addObject:url];
6861 - (void) reloadData {
6862 for (CYViewController *page in [self viewControllers]) {
6863 // Only reload controllers that have already loaded.
6864 // This prevents a page from accidentally loading too
6865 // early if it hasn't been shown on the screen yet.
6866 if ([page hasLoaded])
6871 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6872 delegate_ = delegate;
6875 - (id) initWithDatabase:(Database *)database {
6876 if ((self = [super init]) != nil) {
6877 database_ = database;
6884 /* Cydia:// Protocol {{{ */
6885 @interface CydiaURLProtocol : NSURLProtocol {
6890 @implementation CydiaURLProtocol
6892 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6893 NSURL *url([request URL]);
6896 NSString *scheme([[url scheme] lowercaseString]);
6897 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6902 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6906 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6907 id<NSURLProtocolClient> client([self client]);
6909 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6911 NSData *data(UIImagePNGRepresentation(icon));
6913 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6914 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6915 [client URLProtocol:self didLoadData:data];
6916 [client URLProtocolDidFinishLoading:self];
6920 - (void) startLoading {
6921 id<NSURLProtocolClient> client([self client]);
6922 NSURLRequest *request([self request]);
6924 NSURL *url([request URL]);
6925 NSString *href([url absoluteString]);
6927 NSString *path([href substringFromIndex:8]);
6928 NSRange slash([path rangeOfString:@"/"]);
6931 if (slash.location == NSNotFound) {
6935 command = [path substringToIndex:slash.location];
6936 path = [path substringFromIndex:(slash.location + 1)];
6939 Database *database([Database sharedInstance]);
6941 if ([command isEqualToString:@"package-icon"]) {
6944 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6945 Package *package([database packageWithName:path]);
6948 UIImage *icon([package icon]);
6949 [self _returnPNGWithImage:icon forRequest:request];
6950 } else if ([command isEqualToString:@"source-icon"]) {
6953 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6954 NSString *source(Simplify(path));
6955 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6957 icon = [UIImage applicationImageNamed:@"unknown.png"];
6958 [self _returnPNGWithImage:icon forRequest:request];
6959 } else if ([command isEqualToString:@"uikit-image"]) {
6962 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6963 UIImage *icon(_UIImageWithName(path));
6964 [self _returnPNGWithImage:icon forRequest:request];
6965 } else if ([command isEqualToString:@"section-icon"]) {
6968 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6969 NSString *section(Simplify(path));
6970 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6972 icon = [UIImage applicationImageNamed:@"unknown.png"];
6973 [self _returnPNGWithImage:icon forRequest:request];
6975 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6979 - (void) stopLoading {
6985 /* Section Controller {{{ */
6986 @interface SectionController : FilteredPackageListController {
6990 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6994 @implementation SectionController
6996 - (NSURL *) navigationURL {
6997 NSString *name = section_;
7001 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7004 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7007 title = UCLocalize("ALL_PACKAGES");
7008 else if (![name isEqual:@""])
7009 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7011 title = UCLocalize("NO_SECTION");
7013 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7020 /* Sections Controller {{{ */
7021 @interface SectionsController : CYViewController <
7022 UITableViewDataSource,
7025 _transient Database *database_;
7026 NSMutableArray *sections_;
7027 NSMutableArray *filtered_;
7032 - (id) initWithDatabase:(Database *)database;
7033 - (void) editButtonClicked;
7037 @implementation SectionsController
7040 [self releaseSubviews];
7041 [sections_ release];
7042 [filtered_ release];
7047 - (NSURL *) navigationURL {
7048 return [NSURL URLWithString:@"cydia://sections"];
7051 - (void) updateNavigationItem {
7052 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7053 if ([sections_ count] == 0) {
7054 [[self navigationItem] setRightBarButtonItem:nil];
7056 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7057 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7059 action:@selector(editButtonClicked)
7060 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7064 - (BOOL) isEditing {
7068 - (void) setEditing:(BOOL)editing {
7069 if ((editing_ = editing))
7072 [delegate_ updateData];
7074 [self updateNavigationItem];
7077 - (void) viewDidAppear:(BOOL)animated {
7078 [super viewDidAppear:animated];
7079 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7082 - (void) viewWillDisappear:(BOOL)animated {
7083 [super viewWillDisappear:animated];
7084 if (editing_) [self setEditing:NO];
7087 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7088 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7092 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7093 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7096 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7100 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7101 static NSString *reuseIdentifier = @"SectionCell";
7103 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7105 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7107 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7112 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7116 Section *section = [self sectionAtIndexPath:indexPath];
7118 SectionController *controller = [[[SectionController alloc]
7119 initWithDatabase:database_
7120 section:[section name]
7122 [controller setDelegate:delegate_];
7124 [[self navigationController] pushViewController:controller animated:YES];
7128 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7130 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7131 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7132 [list_ setRowHeight:45.0f];
7133 [list_ setDataSource:self];
7134 [list_ setDelegate:self];
7135 [[self view] addSubview:list_];
7138 - (void) viewDidLoad {
7139 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7142 - (void) releaseSubviews {
7147 - (id) initWithDatabase:(Database *)database {
7148 if ((self = [super init]) != nil) {
7149 database_ = database;
7151 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7152 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7156 - (void) reloadData {
7159 NSArray *packages = [database_ packages];
7161 [sections_ removeAllObjects];
7162 [filtered_ removeAllObjects];
7164 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7167 for (Package *package in packages) {
7168 NSString *name([package section]);
7169 NSString *key(name == nil ? @"" : name);
7173 _profile(SectionsView$reloadData$Section)
7174 section = [sections objectForKey:key];
7175 if (section == nil) {
7176 _profile(SectionsView$reloadData$Section$Allocate)
7177 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7178 [sections setObject:section forKey:key];
7183 [section addToCount];
7185 _profile(SectionsView$reloadData$Filter)
7186 if (![package valid] || ![package visible])
7194 [sections_ addObjectsFromArray:[sections allValues]];
7196 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7198 for (Section *section in sections_) {
7199 size_t count([section row]);
7203 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7204 [section setCount:count];
7205 [filtered_ addObject:section];
7208 [self updateNavigationItem];
7213 - (void) editButtonClicked {
7214 [self setEditing:(!editing_)];
7220 /* Changes Controller {{{ */
7221 @interface ChangesController : CYViewController <
7222 UITableViewDataSource,
7225 _transient Database *database_;
7227 CFMutableArrayRef packages_;
7228 NSMutableArray *sections_;
7231 BOOL hasSentFirstLoad_;
7234 - (id) initWithDatabase:(Database *)database;
7238 @implementation ChangesController
7241 [self releaseSubviews];
7242 CFRelease(packages_);
7243 [sections_ release];
7248 - (NSURL *) navigationURL {
7249 return [NSURL URLWithString:@"cydia://changes"];
7252 - (void) viewWillAppear:(BOOL)animated {
7253 // Loads after it appears, so don't load beforehand.
7255 [super viewWillAppear:animated];
7258 - (void) viewDidAppear:(BOOL)animated {
7259 [super viewDidAppear:animated];
7261 if (!hasSentFirstLoad_) {
7262 hasSentFirstLoad_ = YES;
7263 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7265 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7269 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7270 NSInteger count([sections_ count]);
7271 return count == 0 ? 1 : count;
7274 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7275 if ([sections_ count] == 0)
7277 return [[sections_ objectAtIndex:section] name];
7280 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7281 if ([sections_ count] == 0)
7283 return [[sections_ objectAtIndex:section] count];
7286 - (Package *) packageAtIndex:(NSUInteger)index {
7287 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7290 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7291 @synchronized (database_) {
7292 if ([database_ era] != era_)
7295 NSUInteger sectionIndex([path section]);
7296 if (sectionIndex >= [sections_ count])
7298 Section *section([sections_ objectAtIndex:sectionIndex]);
7299 NSInteger row([path row]);
7300 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7303 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7304 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7306 cell = [[[PackageCell alloc] init] autorelease];
7307 [cell setPackage:[self packageAtIndexPath:path]];
7311 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7312 Package *package([self packageAtIndexPath:path]);
7313 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7314 [view setDelegate:delegate_];
7315 [[self navigationController] pushViewController:view animated:YES];
7319 - (void) refreshButtonClicked {
7320 [delegate_ beginUpdate];
7321 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7324 - (void) upgradeButtonClicked {
7325 [delegate_ distUpgrade];
7329 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7331 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7332 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7333 [list_ setRowHeight:73];
7334 [list_ setDataSource:self];
7335 [list_ setDelegate:self];
7336 [[self view] addSubview:list_];
7339 - (void) viewDidLoad {
7340 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7343 - (void) releaseSubviews {
7348 - (id) initWithDatabase:(Database *)database {
7349 if ((self = [super init]) != nil) {
7350 database_ = database;
7352 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7353 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7357 - (void) _reloadPackages:(NSArray *)packages {
7358 CFRelease(packages_);
7359 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7362 _profile(ChangesController$_reloadPackages$Filter)
7363 for (Package *package in packages)
7364 if ([package upgradableAndEssential:YES] || [package visible])
7365 CFArrayAppendValue(packages_, package);
7368 _profile(ChangesController$_reloadPackages$radixSort)
7369 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7374 - (void) reloadData {
7375 @synchronized (database_) {
7376 era_ = [database_ era];
7377 NSArray *packages = [database_ packages];
7379 [sections_ removeAllObjects];
7382 UIProgressHUD *hud([delegate_ addProgressHUD]);
7383 [hud setText:UCLocalize("LOADING")];
7384 //NSLog(@"HUD:%@::%@", delegate_, hud);
7385 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7386 [delegate_ removeProgressHUD:hud];
7388 [self _reloadPackages:packages];
7391 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7392 Section *ignored = nil;
7393 Section *section = nil;
7397 bool unseens = false;
7399 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7401 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7402 Package *package = [self packageAtIndex:offset];
7404 BOOL uae = [package upgradableAndEssential:YES];
7408 time_t seen([package seen]);
7410 if (section == nil || last != seen) {
7414 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7417 _profile(ChangesController$reloadData$Allocate)
7418 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7419 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7420 [sections_ addObject:section];
7424 [section addToCount];
7425 } else if ([package ignored]) {
7426 if (ignored == nil) {
7427 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7429 [ignored addToCount];
7432 [upgradable addToCount];
7437 CFRelease(formatter);
7440 Section *last = [sections_ lastObject];
7441 size_t count = [last count];
7442 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7443 [sections_ removeLastObject];
7446 if ([ignored count] != 0)
7447 [sections_ insertObject:ignored atIndex:0];
7449 [sections_ insertObject:upgradable atIndex:0];
7454 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7455 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7456 style:UIBarButtonItemStylePlain
7458 action:@selector(upgradeButtonClicked)
7461 if (![delegate_ updating])
7462 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7463 initWithTitle:UCLocalize("REFRESH")
7464 style:UIBarButtonItemStylePlain
7466 action:@selector(refreshButtonClicked)
7474 /* Search Controller {{{ */
7475 @interface SearchController : FilteredPackageListController <
7478 UISearchBar *search_;
7482 - (id) initWithDatabase:(Database *)database;
7483 - (void) setSearchTerm:(NSString *)term;
7484 - (void) reloadData;
7488 @implementation SearchController
7495 - (NSURL *) navigationURL {
7496 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7497 return [NSURL URLWithString:@"cydia://search"];
7499 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7502 - (void) setSearchTerm:(NSString *)searchTerm {
7503 [search_ setText:searchTerm];
7507 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7508 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7509 [search_ resignFirstResponder];
7513 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7514 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7518 - (id) initWithDatabase:(Database *)database {
7519 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7520 search_ = [[UISearchBar alloc] init];
7524 - (void) viewDidAppear:(BOOL)animated {
7525 [super viewDidAppear:animated];
7527 if (!searchloaded_) {
7528 searchloaded_ = YES;
7529 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7530 [search_ layoutSubviews];
7531 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7533 UITextField *textField;
7534 if ([search_ respondsToSelector:@selector(searchField)])
7535 textField = [search_ searchField];
7537 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7539 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7540 [search_ setDelegate:self];
7541 [textField setEnablesReturnKeyAutomatically:NO];
7542 [[self navigationItem] setTitleView:textField];
7546 - (void) reloadData {
7547 [self setObject:[search_ text]];
7552 - (void) didSelectPackage:(Package *)package {
7553 [search_ resignFirstResponder];
7554 [super didSelectPackage:package];
7559 /* Package Settings Controller {{{ */
7560 @interface PackageSettingsController : CYViewController <
7561 UITableViewDataSource,
7564 _transient Database *database_;
7567 UITableView *table_;
7568 UISwitch *subscribedSwitch_;
7569 UISwitch *ignoredSwitch_;
7570 UITableViewCell *subscribedCell_;
7571 UITableViewCell *ignoredCell_;
7574 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7578 @implementation PackageSettingsController
7581 [self releaseSubviews];
7588 - (NSURL *) navigationURL {
7589 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7592 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7593 if (package_ == nil)
7599 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7600 if (package_ == nil)
7606 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7607 return UCLocalize("CHANGE_PACKAGE_SETTINGS");
7610 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7611 return UCLocalize("SHOW_ALL_CHANGES_EX");
7614 - (void) onSubscribed:(id)control {
7615 bool value([control isOn]);
7616 if (package_ == nil)
7618 if ([package_ setSubscribed:value])
7619 [delegate_ updateData];
7622 - (void) _updateIgnored {
7623 const char *package([name_ UTF8String]);
7624 bool on([ignoredSwitch_ isOn]);
7626 pid_t pid(ExecFork());
7628 FILE *dpkg(popen("dpkg --set-selections", "w"));
7629 fwrite(package, strlen(package), 1, dpkg);
7632 fwrite(" hold\n", 6, 1, dpkg);
7634 fwrite(" install\n", 9, 1, dpkg);
7644 int result(waitpid(pid, &status, 0));
7647 _assert(result == pid);
7653 - (void) onIgnored:(id)control {
7654 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7655 [invocation setTarget:self];
7656 [invocation setSelector:@selector(_updateIgnored)];
7658 [delegate_ reloadDataWithInvocation:invocation];
7661 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7662 if (package_ == nil)
7665 switch ([indexPath row]) {
7666 case 0: return subscribedCell_;
7667 case 1: return ignoredCell_;
7676 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7678 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7679 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7680 [table_ setDataSource:self];
7681 [table_ setDelegate:self];
7682 [[self view] addSubview:table_];
7684 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7685 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7686 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7688 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7689 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7690 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7692 subscribedCell_ = [[UITableViewCell alloc] init];
7693 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7694 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7695 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7697 ignoredCell_ = [[UITableViewCell alloc] init];
7698 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7699 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7700 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7703 - (void) viewDidLoad {
7704 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7707 - (void) releaseSubviews {
7708 [ignoredCell_ release];
7711 [subscribedCell_ release];
7712 subscribedCell_ = nil;
7717 [ignoredSwitch_ release];
7718 ignoredSwitch_ = nil;
7720 [subscribedSwitch_ release];
7721 subscribedSwitch_ = nil;
7724 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7725 if ((self = [super init]) != nil) {
7726 database_ = database;
7727 name_ = [package retain];
7731 - (void) reloadData {
7734 if (package_ != nil)
7735 [package_ autorelease];
7736 package_ = [database_ packageWithName:name_];
7738 if (package_ != nil) {
7739 package_ = [package_ retain];
7740 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7741 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7742 } // XXX: what now, G?
7744 [table_ reloadData];
7750 /* Installed Controller {{{ */
7751 @interface InstalledController : FilteredPackageListController {
7755 - (id) initWithDatabase:(Database *)database;
7757 - (void) updateRoleButton;
7758 - (void) queueStatusDidChange;
7762 @implementation InstalledController
7768 - (NSURL *) navigationURL {
7769 return [NSURL URLWithString:@"cydia://installed"];
7772 - (id) initWithDatabase:(Database *)database {
7773 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7774 [self updateRoleButton];
7775 [self queueStatusDidChange];
7780 - (void) queueButtonClicked {
7785 - (void) queueStatusDidChange {
7789 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7790 initWithTitle:UCLocalize("QUEUE")
7791 style:UIBarButtonItemStyleDone
7793 action:@selector(queueButtonClicked)
7796 [[self navigationItem] setLeftBarButtonItem:nil];
7802 - (void) updateRoleButton {
7803 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7804 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7805 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7806 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7808 action:@selector(roleButtonClicked)
7812 - (void) roleButtonClicked {
7813 [self setObject:[NSNumber numberWithBool:expert_]];
7817 [self updateRoleButton];
7823 /* Source Cell {{{ */
7824 @interface SourceCell : CYTableViewCell <
7832 - (void) setSource:(Source *)source;
7836 @implementation SourceCell
7838 - (void) clearSource {
7848 - (void) setSource:(Source *)source {
7852 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7854 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7855 icon_ = [icon_ retain];
7857 origin_ = [[source name] retain];
7858 label_ = [[source uri] retain];
7860 [content_ setNeedsDisplay];
7868 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7869 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7870 UIView *content([self contentView]);
7871 CGRect bounds([content bounds]);
7873 content_ = [[ContentView alloc] initWithFrame:bounds];
7874 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7875 [content_ setBackgroundColor:[UIColor whiteColor]];
7876 [content addSubview:content_];
7878 [content_ setDelegate:self];
7879 [content_ setOpaque:YES];
7883 - (NSString *) accessibilityLabel {
7887 - (void) drawContentRect:(CGRect)rect {
7888 bool highlighted(highlighted_);
7889 float width(rect.size.width);
7892 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7899 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7903 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7908 /* Source Controller {{{ */
7909 @interface SourceController : FilteredPackageListController {
7910 _transient Source *source_;
7914 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7918 @implementation SourceController
7920 - (NSURL *) navigationURL {
7921 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7924 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7925 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7927 key_ = [[source key] retain];
7931 - (void) reloadData {
7932 source_ = [database_ sourceWithKey:key_];
7934 key_ = [[source_ key] retain];
7935 [self setObject:source_];
7936 [[self navigationItem] setTitle:[source_ label]];
7943 /* Sources Controller {{{ */
7944 @interface SourcesController : CYViewController <
7945 UITableViewDataSource,
7948 _transient Database *database_;
7950 NSMutableArray *sources_;
7954 UIProgressHUD *hud_;
7957 //NSURLConnection *installer_;
7958 NSURLConnection *trivial_;
7959 NSURLConnection *trivial_bz2_;
7960 NSURLConnection *trivial_gz_;
7961 //NSURLConnection *automatic_;
7966 - (id) initWithDatabase:(Database *)database;
7967 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7971 @implementation SourcesController
7973 - (void) _releaseConnection:(NSURLConnection *)connection {
7974 if (connection != nil) {
7975 [connection cancel];
7976 //[connection setDelegate:nil];
7977 [connection release];
7982 [self releaseSubviews];
7988 //[self _releaseConnection:installer_];
7989 [self _releaseConnection:trivial_];
7990 [self _releaseConnection:trivial_gz_];
7991 [self _releaseConnection:trivial_bz2_];
7992 //[self _releaseConnection:automatic_];
7998 - (NSURL *) navigationURL {
7999 return [NSURL URLWithString:@"cydia://sources"];
8002 - (void) viewDidAppear:(BOOL)animated {
8003 [super viewDidAppear:animated];
8004 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8007 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8008 return offset_ == 0 ? 1 : 2;
8011 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8012 switch (section + (offset_ == 0 ? 1 : 0)) {
8013 case 0: return UCLocalize("ENTERED_BY_USER");
8014 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8020 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8021 int count = [sources_ count];
8023 case 0: return (offset_ == 0 ? count : offset_);
8024 case 1: return count - offset_;
8030 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8032 switch (indexPath.section) {
8033 case 0: idx = indexPath.row; break;
8034 case 1: idx = indexPath.row + offset_; break;
8038 return [sources_ objectAtIndex:idx];
8041 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8042 static NSString *cellIdentifier = @"SourceCell";
8044 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8045 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8046 [cell setSource:[self sourceAtIndexPath:indexPath]];
8047 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8052 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8053 Source *source = [self sourceAtIndexPath:indexPath];
8055 SourceController *controller = [[[SourceController alloc]
8056 initWithDatabase:database_
8060 [controller setDelegate:delegate_];
8062 [[self navigationController] pushViewController:controller animated:YES];
8065 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8066 Source *source = [self sourceAtIndexPath:indexPath];
8067 return [source record] != nil;
8070 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8071 Source *source = [self sourceAtIndexPath:indexPath];
8072 [Sources_ removeObjectForKey:[source key]];
8073 [delegate_ syncData];
8077 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8080 @"./", @"Distribution",
8081 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
8083 [delegate_ syncData];
8086 - (NSString *) getWarning {
8087 NSString *href(href_);
8088 NSRange colon([href rangeOfString:@"://"]);
8089 if (colon.location != NSNotFound)
8090 href = [href substringFromIndex:(colon.location + 3)];
8091 href = [href stringByAddingPercentEscapes];
8092 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8093 href = [href stringByCachingURLWithCurrentCDN];
8095 NSURL *url([NSURL URLWithString:href]);
8097 NSStringEncoding encoding;
8098 NSError *error(nil);
8100 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8101 return [warning length] == 0 ? nil : warning;
8105 - (void) _endConnection:(NSURLConnection *)connection {
8106 // XXX: the memory management in this method is horribly awkward
8108 NSURLConnection **field = NULL;
8109 if (connection == trivial_)
8111 else if (connection == trivial_bz2_)
8112 field = &trivial_bz2_;
8113 else if (connection == trivial_gz_)
8114 field = &trivial_gz_;
8115 _assert(field != NULL);
8116 [connection release];
8121 trivial_bz2_ == nil &&
8127 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8130 UIAlertView *alert = [[[UIAlertView alloc]
8131 initWithTitle:UCLocalize("SOURCE_WARNING")
8134 cancelButtonTitle:UCLocalize("CANCEL")
8136 UCLocalize("ADD_ANYWAY"),
8140 [alert setContext:@"warning"];
8141 [alert setNumberOfRows:1];
8145 } else if (error_ != nil) {
8146 UIAlertView *alert = [[[UIAlertView alloc]
8147 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8148 message:[error_ localizedDescription]
8150 cancelButtonTitle:UCLocalize("OK")
8151 otherButtonTitles:nil
8154 [alert setContext:@"urlerror"];
8157 UIAlertView *alert = [[[UIAlertView alloc]
8158 initWithTitle:UCLocalize("NOT_REPOSITORY")
8159 message:UCLocalize("NOT_REPOSITORY_EX")
8161 cancelButtonTitle:UCLocalize("OK")
8162 otherButtonTitles:nil
8165 [alert setContext:@"trivial"];
8169 [delegate_ setStatusBarShowsProgress:NO];
8170 [delegate_ removeProgressHUD:hud_];
8180 if (error_ != nil) {
8187 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8188 switch ([response statusCode]) {
8194 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8195 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8197 error_ = [error retain];
8198 [self _endConnection:connection];
8201 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8202 [self _endConnection:connection];
8205 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8206 NSMutableURLRequest *request = [NSMutableURLRequest
8207 requestWithURL:[NSURL URLWithString:href]
8208 cachePolicy:NSURLRequestUseProtocolCachePolicy
8209 timeoutInterval:120.0
8212 [request setHTTPMethod:method];
8214 if (Machine_ != NULL)
8215 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8216 if (UniqueID_ != nil)
8217 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8219 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8221 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8224 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8225 NSString *context([alert context]);
8227 if ([context isEqualToString:@"source"]) {
8230 NSString *href = [[alert textField] text];
8232 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8234 if (![href hasSuffix:@"/"])
8235 href_ = [href stringByAppendingString:@"/"];
8238 href_ = [href_ retain];
8240 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8241 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8242 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8243 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8247 // XXX: this is stupid
8248 hud_ = [[delegate_ addProgressHUD] retain];
8249 [hud_ setText:UCLocalize("VERIFYING_URL")];
8258 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8259 } else if ([context isEqualToString:@"trivial"])
8260 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8261 else if ([context isEqualToString:@"urlerror"])
8262 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8263 else if ([context isEqualToString:@"warning"]) {
8278 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8283 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8285 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8286 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8287 [list_ setRowHeight:56];
8288 [list_ setDataSource:self];
8289 [list_ setDelegate:self];
8290 [[self view] addSubview:list_];
8293 - (void) viewDidLoad {
8294 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8295 [self updateButtonsForEditingStatus:NO animated:NO];
8298 - (void) releaseSubviews {
8303 - (id) initWithDatabase:(Database *)database {
8304 if ((self = [super init]) != nil) {
8305 database_ = database;
8306 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8310 - (void) reloadData {
8314 if (!list.ReadMainList())
8317 [sources_ removeAllObjects];
8318 [sources_ addObjectsFromArray:[database_ sources]];
8320 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8323 int count([sources_ count]);
8325 for (int i = 0; i != count; i++) {
8326 if ([[sources_ objectAtIndex:i] record] == nil)
8331 [list_ setEditing:NO];
8332 [self updateButtonsForEditingStatus:NO animated:NO];
8336 - (void) showAddSourcePrompt {
8337 UIAlertView *alert = [[[UIAlertView alloc]
8338 initWithTitle:UCLocalize("ENTER_APT_URL")
8341 cancelButtonTitle:UCLocalize("CANCEL")
8343 UCLocalize("ADD_SOURCE"),
8347 [alert setContext:@"source"];
8348 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8350 [alert setNumberOfRows:1];
8351 [alert addTextFieldWithValue:@"http://" label:@""];
8353 UITextInputTraits *traits = [[alert textField] textInputTraits];
8354 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8355 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8356 [traits setKeyboardType:UIKeyboardTypeURL];
8357 // XXX: UIReturnKeyDone
8358 [traits setReturnKeyType:UIReturnKeyNext];
8363 - (void) addButtonClicked {
8364 [self showAddSourcePrompt];
8367 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8368 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8369 initWithTitle:UCLocalize("ADD")
8370 style:UIBarButtonItemStylePlain
8372 action:@selector(addButtonClicked)
8373 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8375 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8376 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8377 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8379 action:@selector(editButtonClicked)
8380 ] autorelease] animated:animated];
8382 if (IsWildcat_ && !editing)
8383 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8384 initWithTitle:UCLocalize("SETTINGS")
8385 style:UIBarButtonItemStylePlain
8387 action:@selector(settingsButtonClicked)
8391 - (void) settingsButtonClicked {
8392 [delegate_ showSettings];
8395 - (void) editButtonClicked {
8396 [list_ setEditing:![list_ isEditing] animated:YES];
8398 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8404 /* Settings Controller {{{ */
8405 @interface SettingsController : CYViewController <
8406 UITableViewDataSource,
8409 _transient Database *database_;
8410 // XXX: ok, "roledelegate_"?...
8411 _transient id roledelegate_;
8412 UITableView *table_;
8413 UISegmentedControl *segment_;
8417 - (void) showDoneButton;
8418 - (void) resizeSegmentedControl;
8422 @implementation SettingsController
8425 [self releaseSubviews];
8431 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8433 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8434 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8435 [table_ setDelegate:self];
8436 [table_ setDataSource:self];
8437 [[self view] addSubview:table_];
8439 NSArray *items = [NSArray arrayWithObjects:
8441 UCLocalize("HACKER"),
8442 UCLocalize("DEVELOPER"),
8444 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8445 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8446 [container_ addSubview:segment_];
8449 - (void) viewDidLoad {
8450 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8453 if ([Role_ isEqualToString:@"User"]) index = 0;
8454 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8455 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8457 [segment_ setSelectedSegmentIndex:index];
8458 [self showDoneButton];
8461 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8462 [self resizeSegmentedControl];
8465 - (void) releaseSubviews {
8472 [container_ release];
8476 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8477 if ((self = [super init]) != nil) {
8478 database_ = database;
8479 roledelegate_ = delegate;
8483 - (void) resizeSegmentedControl {
8484 CGFloat width = [[self view] frame].size.width;
8485 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8488 - (void) viewWillAppear:(BOOL)animated {
8489 [super viewWillAppear:animated];
8491 [self resizeSegmentedControl];
8494 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8495 [self resizeSegmentedControl];
8498 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8499 [self resizeSegmentedControl];
8503 NSString *role(nil);
8505 switch ([segment_ selectedSegmentIndex]) {
8506 case 0: role = @"User"; break;
8507 case 1: role = @"Hacker"; break;
8508 case 2: role = @"Developer"; break;
8513 if (![role isEqualToString:Role_]) {
8514 bool rolling(Role_ == nil);
8517 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8521 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8525 [roledelegate_ loadData];
8527 [roledelegate_ updateData];
8531 - (void) segmentChanged:(UISegmentedControl *)control {
8532 [self showDoneButton];
8535 - (void) saveAndClose {
8538 [[self navigationItem] setRightBarButtonItem:nil];
8539 [[self navigationController] dismissModalViewControllerAnimated:YES];
8542 - (void) doneButtonClicked {
8543 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8544 [spinner startAnimating];
8545 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8546 [[self navigationItem] setRightBarButtonItem:spinItem];
8548 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8551 - (void) showDoneButton {
8552 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8553 initWithTitle:UCLocalize("DONE")
8554 style:UIBarButtonItemStyleDone
8556 action:@selector(doneButtonClicked)
8557 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8560 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8561 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8565 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8569 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8570 return nil; // This method is required by the protocol.
8573 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8575 return UCLocalize("ROLE_EX");
8577 return [NSString stringWithFormat:
8578 @"%@: %@\n%@: %@\n%@: %@",
8579 UCLocalize("USER"), UCLocalize("USER_EX"),
8580 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8581 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8586 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8587 return section == 3 ? 44.0f : 0;
8590 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8591 return section == 3 ? container_ : nil;
8594 - (void) reloadData {
8596 [table_ reloadData];
8601 /* Stash Controller {{{ */
8602 @interface StashController : CYViewController {
8603 UIActivityIndicatorView *spinner_;
8610 @implementation StashController
8613 [self releaseSubviews];
8619 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8620 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8622 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8623 CGRect spinrect = [spinner_ frame];
8624 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8625 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8626 [spinner_ setFrame:spinrect];
8627 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8628 [[self view] addSubview:spinner_];
8629 [spinner_ startAnimating];
8632 captrect.size.width = [[self view] frame].size.width;
8633 captrect.size.height = 40.0f;
8634 captrect.origin.x = 0;
8635 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8636 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8637 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8638 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8639 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8640 [caption_ setTextColor:[UIColor whiteColor]];
8641 [caption_ setBackgroundColor:[UIColor clearColor]];
8642 [caption_ setShadowColor:[UIColor blackColor]];
8643 [caption_ setTextAlignment:UITextAlignmentCenter];
8644 [[self view] addSubview:caption_];
8647 statusrect.size.width = [[self view] frame].size.width;
8648 statusrect.size.height = 30.0f;
8649 statusrect.origin.x = 0;
8650 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8651 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8652 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8653 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8654 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8655 [status_ setTextColor:[UIColor whiteColor]];
8656 [status_ setBackgroundColor:[UIColor clearColor]];
8657 [status_ setShadowColor:[UIColor blackColor]];
8658 [status_ setTextAlignment:UITextAlignmentCenter];
8659 [[self view] addSubview:status_];
8662 - (void) releaseSubviews {
8676 @interface Cydia : UIApplication <
8677 ConfirmationControllerDelegate,
8678 ProgressControllerDelegate,
8680 UINavigationControllerDelegate,
8681 UITabBarControllerDelegate
8683 // XXX: evaluate all fields for _transient
8686 CYTabBarController *tabbar_;
8688 NSMutableArray *essential_;
8689 NSMutableArray *broken_;
8691 Database *database_;
8698 StashController *stash_;
8707 @implementation Cydia
8709 - (void) beginUpdate {
8710 [tabbar_ beginUpdate];
8714 return [tabbar_ updating];
8718 if ([broken_ count] != 0) {
8719 int count = [broken_ count];
8721 UIAlertView *alert = [[[UIAlertView alloc]
8722 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8723 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8725 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8727 UCLocalize("TEMPORARY_IGNORE"),
8731 [alert setContext:@"fixhalf"];
8733 } else if (!Ignored_ && [essential_ count] != 0) {
8734 int count = [essential_ count];
8736 UIAlertView *alert = [[[UIAlertView alloc]
8737 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8738 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8740 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8742 UCLocalize("UPGRADE_ESSENTIAL"),
8743 UCLocalize("COMPLETE_UPGRADE"),
8747 [alert setContext:@"upgrade"];
8752 - (void) _saveConfig {
8758 NSString *error(nil);
8760 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8762 NSError *error(nil);
8763 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8764 NSLog(@"failure to save metadata data: %@", error);
8769 NSLog(@"failure to serialize metadata: %@", error);
8774 // Navigation controller for the queuing badge.
8775 - (CYNavigationController *) queueNavigationController {
8776 NSArray *controllers = [tabbar_ viewControllers];
8777 return [controllers objectAtIndex:3];
8780 - (void) _updateData {
8783 [tabbar_ reloadData];
8785 CYNavigationController *navigation = [self queueNavigationController];
8787 id queuedelegate = nil;
8788 if ([[navigation viewControllers] count] > 0)
8789 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8791 [queuedelegate queueStatusDidChange];
8792 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8795 - (void) _refreshIfPossible {
8796 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8798 bool recently = false;
8799 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8800 if (update != nil) {
8801 NSTimeInterval interval([update timeIntervalSinceNow]);
8802 if (interval <= 0 && interval > -(15*60))
8806 // Don't automatic refresh if:
8807 // - We already refreshed recently.
8808 // - We already auto-refreshed this launch.
8809 // - Auto-refresh is disabled.
8810 if (recently || loaded_ || ManualRefresh) {
8811 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8813 // If we are cancelling, we need to make sure it knows it's already loaded.
8817 // We are going to load, so remember that.
8821 SCNetworkReachabilityFlags flags; {
8822 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8823 SCNetworkReachabilityGetFlags(reachability, &flags);
8824 CFRelease(reachability);
8827 // XXX: this elaborate mess is what Apple is using to determine this? :(
8828 // XXX: do we care if the user has to intervene? maybe that's ok?
8830 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8831 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8832 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8833 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8834 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8835 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8839 // If we can reach the server, auto-refresh!
8841 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8846 - (void) refreshIfPossible {
8847 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8850 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8851 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8852 [hud setText:UCLocalize("RELOADING_DATA")];
8854 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8857 [self removeProgressHUD:hud];
8861 [essential_ removeAllObjects];
8862 [broken_ removeAllObjects];
8864 NSArray *packages([database_ packages]);
8865 for (Package *package in packages) {
8867 [broken_ addObject:package];
8868 if ([package upgradableAndEssential:NO]) {
8869 if ([package essential])
8870 [essential_ addObject:package];
8875 NSLog(@"changes:#%u", changes);
8877 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8880 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8881 [changesItem setBadgeValue:badge];
8882 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8883 [self setApplicationIconBadgeNumber:changes];
8886 [changesItem setBadgeValue:nil];
8887 [changesItem setAnimatedBadge:NO];
8888 [self setApplicationIconBadgeNumber:0];
8893 [self refreshIfPossible];
8896 - (void) updateData {
8905 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8906 _assert(file != NULL);
8908 for (NSString *key in [Sources_ allKeys]) {
8909 NSDictionary *source([Sources_ objectForKey:key]);
8911 fprintf(file, "%s %s %s\n",
8912 [[source objectForKey:@"Type"] UTF8String],
8913 [[source objectForKey:@"URI"] UTF8String],
8914 [[source objectForKey:@"Distribution"] UTF8String]
8922 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8923 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8925 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8926 [tabbar_ presentModalViewController:navigation animated:YES];
8929 detachNewThreadSelector:@selector(update_)
8932 title:UCLocalize("UPDATING_SOURCES")
8936 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8937 @synchronized (self) {
8938 [self _reloadDataWithInvocation:invocation];
8942 - (void) reloadData {
8943 [self reloadDataWithInvocation:nil];
8947 pkgProblemResolver *resolver = [database_ resolver];
8949 resolver->InstallProtect();
8950 if (!resolver->Resolve(true))
8955 // XXX: this is a really crappy way of doing this.
8956 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8957 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8958 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8959 if ([tabbar_ updating])
8960 [tabbar_ cancelUpdate];
8962 if (![database_ prepare])
8965 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8966 [page setDelegate:self];
8967 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8968 [confirm_ setDelegate:self];
8971 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8972 [tabbar_ presentModalViewController:confirm_ animated:YES];
8978 @synchronized (self) {
8983 - (void) clearPackage:(Package *)package {
8984 @synchronized (self) {
8991 - (void) installPackages:(NSArray *)packages {
8992 @synchronized (self) {
8993 for (Package *package in packages)
9000 - (void) installPackage:(Package *)package {
9001 @synchronized (self) {
9008 - (void) removePackage:(Package *)package {
9009 @synchronized (self) {
9016 - (void) distUpgrade {
9017 @synchronized (self) {
9018 if (![database_ upgrade])
9025 @synchronized (self) {
9026 [self _reloadDataWithInvocation:nil];
9030 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9033 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
9035 if (navigation != nil) {
9036 [navigation pushViewController:progress animated:YES];
9038 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
9040 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9041 [tabbar_ presentModalViewController:navigation animated:YES];
9045 detachNewThreadSelector:@selector(perform)
9048 title:UCLocalize("RUNNING")
9054 - (void) progressControllerIsComplete:(ProgressController *)progress {
9059 - (void) showSettings {
9060 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9061 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9063 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9064 [tabbar_ presentModalViewController:nav animated:YES];
9067 - (void) retainNetworkActivityIndicator {
9068 if (activity_++ == 0)
9069 [self setNetworkActivityIndicatorVisible:YES];
9072 - (void) releaseNetworkActivityIndicator {
9073 if (--activity_ == 0)
9074 [self setNetworkActivityIndicatorVisible:NO];
9077 - (void) cancelAndClear:(bool)clear {
9078 @synchronized (self) {
9090 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9091 NSString *context([alert context]);
9093 if ([context isEqualToString:@"fixhalf"]) {
9094 if (button == [alert cancelButtonIndex]) {
9095 @synchronized (self) {
9096 for (Package *broken in broken_) {
9099 NSString *id = [broken id];
9100 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9101 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9102 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9103 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9109 } else if (button == [alert firstOtherButtonIndex]) {
9110 [broken_ removeAllObjects];
9114 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9115 } else if ([context isEqualToString:@"upgrade"]) {
9116 if (button == [alert firstOtherButtonIndex]) {
9117 @synchronized (self) {
9118 for (Package *essential in essential_)
9119 [essential install];
9124 } else if (button == [alert firstOtherButtonIndex] + 1) {
9126 } else if (button == [alert cancelButtonIndex]) {
9130 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9134 - (void) system:(NSString *)command { _pooled
9136 system([command UTF8String]);
9140 - (void) applicationWillSuspend {
9142 [super applicationWillSuspend];
9145 - (BOOL) isSafeToSuspend {
9146 // Use external process status API internally.
9147 // This is probably a really bad idea.
9148 // XXX: what is the point of this? does this solve anything at all?
9149 uint64_t status = 0;
9151 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9152 notify_get_state(notify_token, &status);
9153 notify_cancel(notify_token);
9156 return locked_ == 0 && status == 0;
9159 - (void) applicationSuspend:(__GSEvent *)event {
9160 if ([self isSafeToSuspend])
9161 [super applicationSuspend:event];
9164 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9165 if ([self isSafeToSuspend])
9166 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9169 - (void) _setSuspended:(BOOL)value {
9170 if ([self isSafeToSuspend])
9171 [super _setSuspended:value];
9174 - (UIProgressHUD *) addProgressHUD {
9175 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9176 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9178 [window_ setUserInteractionEnabled:NO];
9181 UIViewController *target = tabbar_;
9182 while ([target modalViewController] != nil) target = [target modalViewController];
9183 [[target view] addSubview:hud];
9189 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9191 [hud removeFromSuperview];
9192 [window_ setUserInteractionEnabled:YES];
9196 - (CYViewController *) pageForPackage:(NSString *)name {
9197 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9200 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9201 NSString *scheme([[url scheme] lowercaseString]);
9202 if ([[url absoluteString] length] <= [scheme length] + 3)
9204 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9205 NSArray *components([path pathComponents]);
9207 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9208 return [self pageForPackage:[components objectAtIndex:1]];
9210 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9213 NSString *base([components objectAtIndex:0]);
9215 CYViewController *controller = nil;
9217 if ([base isEqualToString:@"url"]) {
9218 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9219 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9220 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9221 } else if (!external && [components count] == 1) {
9222 if ([base isEqualToString:@"manage"]) {
9223 controller = [[[ManageController alloc] init] autorelease];
9226 if ([base isEqualToString:@"sources"]) {
9227 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9230 if ([base isEqualToString:@"home"]) {
9231 controller = [[[HomeController alloc] init] autorelease];
9234 if ([base isEqualToString:@"sections"]) {
9235 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9238 if ([base isEqualToString:@"search"]) {
9239 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9242 if ([base isEqualToString:@"changes"]) {
9243 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9246 if ([base isEqualToString:@"installed"]) {
9247 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9249 } else if ([components count] == 2) {
9250 NSString *argument = [components objectAtIndex:1];
9252 if ([base isEqualToString:@"package"]) {
9253 controller = [self pageForPackage:argument];
9256 if (!external && [base isEqualToString:@"search"]) {
9257 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9258 [(SearchController *)controller setSearchTerm:argument];
9261 if (!external && [base isEqualToString:@"sections"]) {
9262 if ([argument isEqualToString:@"all"])
9264 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9267 if (!external && [base isEqualToString:@"sources"]) {
9268 if ([argument isEqualToString:@"add"]) {
9269 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9270 [(SourcesController *)controller showAddSourcePrompt];
9272 Source *source = [database_ sourceWithKey:argument];
9273 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9277 if (!external && [base isEqualToString:@"launch"]) {
9278 [self launchApplicationWithIdentifier:argument suspended:NO];
9281 } else if (!external && [components count] == 3) {
9282 NSString *arg1 = [components objectAtIndex:1];
9283 NSString *arg2 = [components objectAtIndex:2];
9285 if ([base isEqualToString:@"package"]) {
9286 if ([arg2 isEqualToString:@"settings"]) {
9287 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9288 } else if ([arg2 isEqualToString:@"files"]) {
9289 if (Package *package = [database_ packageWithName:arg1]) {
9290 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9291 [(FileTable *)controller setPackage:package];
9297 [controller setDelegate:self];
9301 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9302 CYViewController *page([self pageForURL:url forExternal:external]);
9305 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9306 [nav setViewControllers:[NSArray arrayWithObject:page]];
9307 [tabbar_ setUnselectedViewController:nav];
9313 - (void) applicationOpenURL:(NSURL *)url {
9314 [super applicationOpenURL:url];
9316 if (!loaded_) starturl_ = [url retain];
9317 else [self openCydiaURL:url forExternal:YES];
9320 - (void) applicationWillResignActive:(UIApplication *)application {
9321 // Stop refreshing if you get a phone call or lock the device.
9322 if ([tabbar_ updating])
9323 [tabbar_ cancelUpdate];
9325 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9326 [super applicationWillResignActive:application];
9329 - (void) applicationWillTerminate:(UIApplication *)application {
9331 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9332 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9333 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9338 - (void) addStashController {
9340 stash_ = [[StashController alloc] init];
9341 [window_ addSubview:[stash_ view]];
9344 - (void) removeStashController {
9345 [[stash_ view] removeFromSuperview];
9351 [self setIdleTimerDisabled:YES];
9353 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9354 [self setStatusBarShowsProgress:YES];
9355 UpdateExternalStatus(1);
9357 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9359 UpdateExternalStatus(0);
9360 [self setStatusBarShowsProgress:NO];
9362 [self removeStashController];
9364 if (ExecFork() == 0) {
9365 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9366 perror("launchctl stop");
9370 - (void) setupViewControllers {
9371 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9373 NSMutableArray *items([NSMutableArray arrayWithObjects:
9374 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9375 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9376 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9377 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9381 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9382 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9384 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9387 NSMutableArray *controllers([NSMutableArray array]);
9388 for (UITabBarItem *item in items) {
9389 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9390 [controller setTabBarItem:item];
9391 [controllers addObject:controller];
9393 [tabbar_ setViewControllers:controllers];
9395 [tabbar_ setUpdateDelegate:self];
9398 - (CYEmulatedLoadingController *) showEmulatedLoadingControllerInView:(UIView *)view {
9399 static CYEmulatedLoadingController *fake = nil;
9403 fake = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9404 [view addSubview:[fake view]];
9406 [[fake view] removeFromSuperview];
9414 - (void) applicationDidFinishLaunching:(id)unused {
9418 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9419 [self setApplicationSupportsShakeToEdit:NO];
9421 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9422 initWithMemoryCapacity:524288
9423 diskCapacity:10485760
9424 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9427 [CYBrowserController _initialize];
9429 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9431 Font12_ = [[UIFont systemFontOfSize:12] retain];
9432 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9433 Font14_ = [[UIFont systemFontOfSize:14] retain];
9434 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9435 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9437 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9438 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9440 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9441 [window_ orderFront:self];
9442 [window_ makeKey:self];
9443 [window_ setHidden:NO];
9446 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9447 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9448 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9449 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9450 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9451 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9452 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9453 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9454 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9457 [self addStashController];
9458 // XXX: this would be much cleaner as a yieldToSelector:
9459 // that way the removeStashController could happen right here inline
9460 // we also could no longer require the useless stash_ field anymore
9461 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9465 database_ = [Database sharedInstance];
9467 [window_ setUserInteractionEnabled:NO];
9468 [self setupViewControllers];
9469 [self showEmulatedLoadingControllerInView:window_];
9471 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9478 [window_ setUserInteractionEnabled:YES];
9480 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9481 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9483 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9484 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9488 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9489 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9490 [window_ setUserInteractionEnabled:NO];
9496 [window_ addSubview:[tabbar_ view]];
9497 [self showEmulatedLoadingControllerInView:nil];
9498 [window_ setUserInteractionEnabled:YES];
9500 int selectedIndex = 0;
9501 NSMutableArray *items = nil;
9503 bool recently = false;
9504 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9505 if (closed != nil) {
9506 NSTimeInterval interval([closed timeIntervalSinceNow]);
9507 // XXX: Is 15 minutes the optimal time here?
9508 if (interval <= 0 && interval > -(15*60))
9512 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9513 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9516 for (NSArray *entry in items)
9517 if ([entry count] <= 0)
9520 if (!recently || !items || !enough) {
9522 items = [NSMutableArray array];
9523 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9524 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9525 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9527 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9529 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9530 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9532 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9535 [tabbar_ setSelectedIndex:selectedIndex];
9536 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9537 NSArray *stack = [items objectAtIndex:tab];
9538 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9539 NSMutableArray *current = [NSMutableArray array];
9541 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9542 NSString *addr = [stack objectAtIndex:nav];
9543 NSURL *url = [NSURL URLWithString:addr];
9544 CYViewController *page = [self pageForURL:url forExternal:NO];
9546 [current addObject:page];
9549 [navigation setViewControllers:current];
9552 // (Try to) show the startup URL.
9553 if (starturl_ != nil) {
9554 [self openCydiaURL:starturl_ forExternal:NO];
9555 [starturl_ release];
9560 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9561 if (item != nil && IsWildcat_) {
9562 [sheet showFromBarButtonItem:item animated:YES];
9564 [sheet showInView:window_];
9571 id Alloc_(id self, SEL selector) {
9572 id object = alloc_(self, selector);
9573 lprintf("[%s]A-%p\n", self->isa->name, object);
9578 id Dealloc_(id self, SEL selector) {
9579 id object = dealloc_(self, selector);
9580 lprintf("[%s]D-%p\n", self->isa->name, object);
9584 Class $WebDefaultUIKitDelegate;
9586 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9587 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9588 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9589 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9592 static NSNumber *shouldPlayKeyboardSounds;
9596 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9598 case 1104: // Keyboard Button Clicked
9599 case 1105: // Keyboard Delete Repeated
9600 if (shouldPlayKeyboardSounds == nil) {
9601 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9602 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9605 if (![shouldPlayKeyboardSounds boolValue])
9609 _UIHardware$_playSystemSound$(self, _cmd, sound);
9613 Class $UIApplication;
9615 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9616 static BOOL initialized = NO;
9617 static BOOL started = NO;
9619 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9620 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9622 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9623 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9624 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9625 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9627 if (initialized && !enabled) {
9629 [bundle performSelector:@selector(_accessibilityStopServer)];
9630 } else if (enabled) {
9634 [bundle performSelector:@selector(_accessibilityStartServer)];
9640 int main(int argc, char *argv[]) { _pooled
9643 if (Class $UIDevice = objc_getClass("UIDevice")) {
9644 UIDevice *device([$UIDevice currentDevice]);
9645 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9649 UIScreen *screen([UIScreen mainScreen]);
9650 if ([screen respondsToSelector:@selector(scale)])
9651 ScreenScale_ = [screen scale];
9655 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9656 if (ScreenScale_ > 1)
9657 [parts addObject:@"@2x"];
9658 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9659 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9661 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9663 /* Library Hacks {{{ */
9664 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9666 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9667 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9668 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9669 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9670 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9673 $UIHardware = objc_getClass("UIHardware");
9674 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9675 if (UIHardware$_playSystemSound$ != NULL) {
9676 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9677 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9680 $UIApplication = objc_getClass("UIApplication");
9681 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9682 if (UIApplication$_updateApplicationAccessibility != NULL) {
9683 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9684 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9687 /* Set Locale {{{ */
9688 Locale_ = CFLocaleCopyCurrent();
9689 Languages_ = [NSLocale preferredLanguages];
9690 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9691 //NSLog(@"%@", [Languages_ description]);
9694 if (Languages_ == nil || [Languages_ count] == 0)
9695 // XXX: consider just setting to C and then falling through?
9698 lang = [[Languages_ objectAtIndex:0] UTF8String];
9699 setenv("LANG", lang, true);
9702 //std::setlocale(LC_ALL, lang);
9703 NSLog(@"Setting Language: %s", lang);
9706 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9708 /* Parse Arguments {{{ */
9709 bool substrate(false);
9715 for (int argi(1); argi != argc; ++argi)
9716 if (strcmp(argv[argi], "--") == 0) {
9718 argv[argi] = argv[0];
9724 for (int argi(1); argi != arge; ++argi)
9725 if (strcmp(args[argi], "--substrate") == 0)
9728 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9732 App_ = [[NSBundle mainBundle] bundlePath];
9733 Home_ = NSHomeDirectory();
9739 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9740 alloc_ = alloc->method_imp;
9741 alloc->method_imp = (IMP) &Alloc_;*/
9743 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9744 dealloc_ = dealloc->method_imp;
9745 dealloc->method_imp = (IMP) &Dealloc_;*/
9747 /* System Information {{{ */
9751 size = sizeof(maxproc);
9752 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9753 perror("sysctlbyname(\"kern.maxproc\", ?)");
9754 else if (maxproc < 64) {
9756 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9757 perror("sysctlbyname(\"kern.maxproc\", #)");
9760 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9761 char *osversion = new char[size];
9762 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9763 perror("sysctlbyname(\"kern.osversion\", ?)");
9765 System_ = [NSString stringWithUTF8String:osversion];
9767 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9768 char *machine = new char[size];
9769 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9770 perror("sysctlbyname(\"hw.machine\", ?)");
9774 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9775 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9776 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9777 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9781 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9782 NSData *data((NSData *) ecid);
9783 size_t length([data length]);
9784 uint8_t bytes[length];
9785 [data getBytes:bytes];
9786 char string[length * 2 + 1];
9787 for (size_t i(0); i != length; ++i)
9788 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9789 ChipID_ = [NSString stringWithUTF8String:string];
9793 IOObjectRelease(service);
9797 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9799 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9800 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9801 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9803 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9804 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9805 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9807 if (mcc != NULL && mnc != NULL)
9808 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9815 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9816 Build_ = [system objectForKey:@"ProductBuildVersion"];
9817 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9818 Product_ = [info objectForKey:@"SafariProductVersion"];
9819 Safari_ = [info objectForKey:@"CFBundleVersion"];
9822 /* Load Database {{{ */
9824 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9826 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9828 if (Metadata_ == NULL)
9829 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9831 Settings_ = [Metadata_ objectForKey:@"Settings"];
9833 Packages_ = [Metadata_ objectForKey:@"Packages"];
9834 Sections_ = [Metadata_ objectForKey:@"Sections"];
9835 Sources_ = [Metadata_ objectForKey:@"Sources"];
9837 Token_ = [Metadata_ objectForKey:@"Token"];
9840 if (Settings_ != nil)
9841 Role_ = [Settings_ objectForKey:@"Role"];
9843 if (Sections_ == nil) {
9844 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9845 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9848 if (Sources_ == nil) {
9849 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9850 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9855 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9858 if (Packages_ != nil) {
9860 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9864 [Metadata_ removeObjectForKey:@"Packages"];
9870 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9872 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9873 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9874 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9875 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9876 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9877 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9879 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9881 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9882 unlink("/tmp/.cydia.fw");
9884 } else if (access("/User", F_OK) != 0 || version < 2) {
9887 system("/usr/libexec/cydia/firmware.sh");
9891 _assert([[NSFileManager defaultManager]
9892 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9893 withIntermediateDirectories:YES
9898 if (access("/tmp/cydia.chk", F_OK) == 0) {
9899 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9900 _assert(errno == ENOENT);
9901 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9902 _assert(errno == ENOENT);
9905 /* APT Initialization {{{ */
9906 _assert(pkgInitConfig(*_config));
9907 _assert(pkgInitSystem(*_config, _system));
9910 _config->Set("APT::Acquire::Translation", lang);
9912 // XXX: this timeout might be important :(
9913 //_config->Set("Acquire::http::Timeout", 15);
9915 _config->Set("Acquire::http::MaxParallel", 3);
9917 /* Color Choices {{{ */
9918 space_ = CGColorSpaceCreateDeviceRGB();
9920 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9921 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9922 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9923 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9924 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9925 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9926 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9927 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9928 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9930 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9931 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9933 /* UIKit Configuration {{{ */
9934 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9935 if ($GSFontSetUseLegacyFontMetrics != NULL)
9936 $GSFontSetUseLegacyFontMetrics(YES);
9938 // XXX: I have a feeling this was important
9939 //UIKeyboardDisableAutomaticAppearance();
9942 Colon_ = UCLocalize("COLON_DELIMITED");
9943 Elision_ = UCLocalize("ELISION");
9944 Error_ = UCLocalize("ERROR");
9945 Warning_ = UCLocalize("WARNING");
9948 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9950 CGColorSpaceRelease(space_);