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;
312 @implementation CYAlertView
314 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
315 if ((self = [super init])) {
316 [self setTitle:title];
317 [self setDelegate:self];
318 for (NSString *button in buttons) [self addButtonWithTitle:button];
319 [self setCancelButtonIndex:index];
323 - (void) _updateFrameForDisplay {
324 [super _updateFrameForDisplay];
325 if ([self cancelButtonIndex] == -1) {
326 NSArray *buttons = [self buttons];
327 if ([buttons count]) {
328 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
329 for (UIThreePartButton *button in buttons)
330 [button setBackground:background forState:0];
335 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
336 button_ = buttonIndex + 1;
340 [self dismissWithClickedButtonIndex:-1 animated:YES];
343 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
344 [self setRunsModal:YES];
353 /* NSForcedOrderingSearch doesn't work on the iPhone */
354 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
355 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
356 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
358 #define lprintf(args...) fprintf(stderr, args)
361 #define TraceLogging (1 && !ForRelease)
362 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
363 #define ProfileTimes (0 && !ForRelease)
364 #define ForSaurik (0 && !ForRelease)
365 #define LogBrowser (0 && !ForRelease)
366 #define TrackResize (0 && !ForRelease)
367 #define ManualRefresh (1 && !ForRelease)
368 #define ShowInternals (0 && !ForRelease)
369 #define IgnoreInstall (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;
877 @implementation Address
886 - (NSString *) name {
890 - (NSString *) address {
894 - (void) setAddress:(NSString *)address {
896 [address_ autorelease];
900 address_ = [address retain];
903 + (Address *) addressWithString:(NSString *)string {
904 return [[[Address alloc] initWithString:string] autorelease];
907 + (NSArray *) _attributeKeys {
908 return [NSArray arrayWithObjects:@"address", @"name", nil];
911 - (NSArray *) attributeKeys {
912 return [[self class] _attributeKeys];
915 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
916 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
919 - (Address *) initWithString:(NSString *)string {
920 if ((self = [super init]) != nil) {
921 const char *data = [string UTF8String];
922 size_t size = [string length];
924 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
926 if (address_r(data, size)) {
927 name_ = [address_r[1] retain];
928 address_ = [address_r[2] retain];
930 name_ = [string retain];
938 /* CoreGraphics Primitives {{{ */
943 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
944 CGFloat color[] = {red, green, blue, alpha};
945 return CGColorCreate(space, color);
954 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
955 color_(Create_(space, red, green, blue, alpha))
957 Set(space, red, green, blue, alpha);
962 CGColorRelease(color_);
969 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
971 color_ = Create_(space, red, green, blue, alpha);
974 operator CGColorRef() {
980 /* Random Global Variables {{{ */
981 static const int PulseInterval_ = 50000;
983 static const NSString *UI_;
986 static NSArray *Finishes_;
988 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
989 #define NotifyConfig_ "/etc/notify.conf"
991 static bool Queuing_;
993 static CYColor Blue_;
994 static CYColor Blueish_;
995 static CYColor Black_;
997 static CYColor White_;
998 static CYColor Gray_;
999 static CYColor Green_;
1000 static CYColor Purple_;
1001 static CYColor Purplish_;
1003 static UIColor *InstallingColor_;
1004 static UIColor *RemovingColor_;
1006 static NSString *App_;
1007 static NSString *Home_;
1009 static BOOL Advanced_;
1010 static BOOL Ignored_;
1012 static UIFont *Font12_;
1013 static UIFont *Font12Bold_;
1014 static UIFont *Font14_;
1015 static UIFont *Font18Bold_;
1016 static UIFont *Font22Bold_;
1018 static const char *Machine_ = NULL;
1019 static NSString *System_ = nil;
1020 static NSString *SerialNumber_ = nil;
1021 static NSString *ChipID_ = nil;
1022 static NSString *Token_ = nil;
1023 static NSString *UniqueID_ = nil;
1024 static NSString *PLMN_ = nil;
1025 static NSString *Build_ = nil;
1026 static NSString *Product_ = nil;
1027 static NSString *Safari_ = nil;
1029 static CFLocaleRef Locale_;
1030 static NSArray *Languages_;
1031 static CGColorSpaceRef space_;
1033 static NSDictionary *SectionMap_;
1034 static NSMutableDictionary *Metadata_;
1035 static _transient NSMutableDictionary *Settings_;
1036 static _transient NSString *Role_;
1037 static _transient NSMutableDictionary *Packages_;
1038 static _transient NSMutableDictionary *Sections_;
1039 static _transient NSMutableDictionary *Sources_;
1040 static bool Changed_;
1044 static CGFloat ScreenScale_;
1047 /* Display Helpers {{{ */
1048 inline float Interpolate(float begin, float end, float fraction) {
1049 return (end - begin) * fraction + begin;
1052 /* XXX: localize this! */
1053 NSString *SizeString(double size) {
1054 bool negative = size < 0;
1059 while (size > 1024) {
1064 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1066 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1069 static _finline const char *StripVersion_(const char *version) {
1070 const char *colon(strchr(version, ':'));
1071 return colon == NULL ? version : colon + 1;
1074 NSString *LocalizeSection(NSString *section) {
1075 static Pcre title_r("^(.*?) \\((.*)\\)$");
1076 if (title_r(section)) {
1077 NSString *parent(title_r[1]);
1078 NSString *child(title_r[2]);
1080 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1081 LocalizeSection(parent),
1082 LocalizeSection(child)
1086 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1089 NSString *Simplify(NSString *title) {
1090 const char *data = [title UTF8String];
1091 size_t size = [title length];
1093 static Pcre square_r("^\\[(.*)\\]$");
1094 if (square_r(data, size))
1095 return Simplify(square_r[1]);
1097 static Pcre paren_r("^\\((.*)\\)$");
1098 if (paren_r(data, size))
1099 return Simplify(paren_r[1]);
1101 static Pcre title_r("^(.*?) \\((.*)\\)$");
1102 if (title_r(data, size))
1103 return Simplify(title_r[1]);
1109 NSString *GetLastUpdate() {
1110 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1113 return UCLocalize("NEVER_OR_UNKNOWN");
1115 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1116 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1118 CFRelease(formatter);
1120 return [(NSString *) formatted autorelease];
1123 bool isSectionVisible(NSString *section) {
1124 NSDictionary *metadata([Sections_ objectForKey:section]);
1125 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1126 return hidden == nil || ![hidden boolValue];
1131 /* Delegate Prototypes {{{ */
1135 @interface NSObject (ProgressDelegate)
1138 @protocol ProgressDelegate
1139 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1140 - (void) setProgressTitle:(NSString *)title;
1141 - (void) setProgressPercent:(float)percent;
1142 - (void) startProgress;
1143 - (void) addProgressOutput:(NSString *)output;
1144 - (bool) isCancelling:(size_t)received;
1147 @protocol ConfigurationDelegate
1148 - (void) repairWithSelector:(SEL)selector;
1149 - (void) setConfigurationData:(NSString *)data;
1152 @class CYPackageController;
1154 @protocol CydiaDelegate
1155 - (void) retainNetworkActivityIndicator;
1156 - (void) releaseNetworkActivityIndicator;
1157 - (void) clearPackage:(Package *)package;
1158 - (void) installPackage:(Package *)package;
1159 - (void) installPackages:(NSArray *)packages;
1160 - (void) removePackage:(Package *)package;
1161 - (void) beginUpdate;
1163 - (void) distUpgrade;
1165 - (void) updateData;
1167 - (void) showSettings;
1168 - (UIProgressHUD *) addProgressHUD;
1169 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1170 - (CYViewController *) pageForPackage:(NSString *)name;
1171 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1174 static id<CydiaDelegate> CydiaApp;
1177 /* Status Delegation {{{ */
1179 public pkgAcquireStatus
1182 _transient NSObject<ProgressDelegate> *delegate_;
1190 void setDelegate(id delegate) {
1191 delegate_ = delegate;
1194 NSObject<ProgressDelegate> *getDelegate() const {
1198 virtual bool MediaChange(std::string media, std::string drive) {
1202 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1205 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1206 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1207 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1210 virtual void Done(pkgAcquire::ItemDesc &item) {
1213 virtual void Fail(pkgAcquire::ItemDesc &item) {
1215 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1216 item.Owner->Status == pkgAcquire::Item::StatDone
1220 std::string &error(item.Owner->ErrorText);
1224 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1225 NSArray *fields([description componentsSeparatedByString:@" "]);
1226 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1228 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1229 withObject:[NSArray arrayWithObjects:
1230 [NSString stringWithUTF8String:error.c_str()],
1237 virtual bool Pulse(pkgAcquire *Owner) {
1238 bool value = pkgAcquireStatus::Pulse(Owner);
1241 double(CurrentBytes + CurrentItems) /
1242 double(TotalBytes + TotalItems)
1245 [delegate_ setProgressPercent:percent];
1246 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1249 virtual void Start() {
1250 [delegate_ startProgress];
1253 virtual void Stop() {
1257 /* Progress Delegation {{{ */
1262 _transient id<ProgressDelegate> delegate_;
1266 virtual void Update() {
1267 /*if (abs(Percent - percent_) > 2)
1268 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1272 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1273 [delegate_ setProgressPercent:(Percent / 100)];*/
1283 void setDelegate(id delegate) {
1284 delegate_ = delegate;
1287 id getDelegate() const {
1291 virtual void Done() {
1293 //[delegate_ setProgressPercent:1];
1298 /* Database Interface {{{ */
1299 typedef std::map< unsigned long, _H<Source> > SourceMap;
1301 @interface Database : NSObject {
1307 pkgCacheFile cache_;
1308 pkgDepCache::Policy *policy_;
1309 pkgRecords *records_;
1310 pkgProblemResolver *resolver_;
1311 pkgAcquire *fetcher_;
1313 SPtr<pkgPackageManager> manager_;
1314 pkgSourceList *list_;
1317 CFMutableArrayRef deadSources_;
1318 CFMutableArrayRef packages_;
1320 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1328 std::map<const char *, _H<NSString> > sections_;
1331 + (Database *) sharedInstance;
1334 - (void) _readCydia:(NSNumber *)fd;
1335 - (void) _readStatus:(NSNumber *)fd;
1336 - (void) _readOutput:(NSNumber *)fd;
1340 - (Package *) packageWithName:(NSString *)name;
1342 - (pkgCacheFile &) cache;
1343 - (pkgDepCache::Policy *) policy;
1344 - (pkgRecords *) records;
1345 - (pkgProblemResolver *) resolver;
1346 - (pkgAcquire &) fetcher;
1347 - (pkgSourceList &) list;
1348 - (NSArray *) packages;
1349 - (NSArray *) sources;
1350 - (void) reloadData;
1358 - (void) updateWithStatus:(Status &)status;
1360 - (void) setDelegate:(id)delegate;
1361 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1363 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1367 /* Delegate Helpers {{{ */
1368 @implementation NSObject (ProgressDelegate)
1370 - (void) _setProgressErrorPackage:(NSArray *)args {
1371 [self performSelector:@selector(setProgressError:forPackage:)
1372 withObject:[args objectAtIndex:0]
1373 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1377 - (void) _setProgressErrorTitle:(NSArray *)args {
1378 [self performSelector:@selector(setProgressError:withTitle:)
1379 withObject:[args objectAtIndex:0]
1380 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1384 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1385 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1386 withObject:[NSArray arrayWithObjects:error, title, nil]
1391 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1392 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1394 [self performSelector:@selector(setProgressError:withTitle:)
1396 withObject:(package == nil ? id : [package name])
1403 // Cytore Definitions {{{
1404 struct PackageValue :
1407 Cytore::Offset<PackageValue> next_;
1409 uint32_t index_ : 23;
1410 uint32_t subscribed_ : 1;
1427 Cytore::Offset<PackageValue> packages_[1 << 16];
1430 static Cytore::File<MetaValue> MetaFile_;
1432 // Cytore Helper Functions {{{
1433 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1434 SplitHash nhash = { hashlittle(name, length) };
1436 PackageValue *metadata;
1438 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1439 offset: if (offset->IsNull()) {
1440 *offset = MetaFile_.New<PackageValue>(length + 1);
1441 metadata = &MetaFile_.Get(*offset);
1443 if (metadata == NULL) {
1447 metadata = new PackageValue();
1448 memset(metadata, 0, sizeof(*metadata));
1451 memcpy(metadata->name_, name, length + 1);
1452 metadata->nhash_ = nhash.u16[1];
1454 metadata = &MetaFile_.Get(*offset);
1456 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1457 offset = &metadata->next_;
1465 static void PackageImport(const void *key, const void *value, void *context) {
1466 bool &fail(*reinterpret_cast<bool *>(context));
1469 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1470 NSLog(@"failed to import package %@", key);
1474 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1475 NSDictionary *package((NSDictionary *) value);
1477 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1478 if ([subscribed boolValue] && !metadata->subscribed_)
1479 metadata->subscribed_ = true;
1481 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1482 time_t time([date timeIntervalSince1970]);
1483 if (metadata->first_ > time || metadata->first_ == 0)
1484 metadata->first_ = time;
1487 NSDate *date([package objectForKey:@"LastSeen"]);
1488 NSString *version([package objectForKey:@"LastVersion"]);
1490 if (date != nil && version != nil) {
1491 time_t time([date timeIntervalSince1970]);
1492 if (metadata->last_ < time || metadata->last_ == 0)
1493 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1494 size_t length(strlen(buffer));
1495 uint16_t vhash(hashlittle(buffer, length));
1497 size_t capped(std::min<size_t>(8, length));
1498 char *latest(buffer + length - capped);
1500 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1501 metadata->vhash_ = vhash;
1503 metadata->last_ = time;
1509 /* Source Class {{{ */
1510 @interface Source : NSObject {
1511 CYString depiction_;
1512 CYString description_;
1518 CYString distribution_;
1523 NSString *authority_;
1525 CYString defaultIcon_;
1527 NSDictionary *record_;
1531 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1533 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1535 - (NSString *) depictionForPackage:(NSString *)package;
1536 - (NSString *) supportForPackage:(NSString *)package;
1538 - (NSDictionary *) record;
1542 - (NSString *) distribution;
1543 - (NSString *) type;
1545 - (NSString *) host;
1547 - (NSString *) name;
1548 - (NSString *) description;
1549 - (NSString *) label;
1550 - (NSString *) origin;
1551 - (NSString *) version;
1553 - (NSString *) defaultIcon;
1557 @implementation Source
1561 distribution_.clear();
1564 description_.clear();
1570 defaultIcon_.clear();
1572 if (record_ != nil) {
1582 if (authority_ != nil) {
1583 [authority_ release];
1589 // XXX: this is a very inefficient way to call these deconstructors
1594 + (NSArray *) _attributeKeys {
1595 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1598 - (NSArray *) attributeKeys {
1599 return [[self class] _attributeKeys];
1602 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1603 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1606 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1609 trusted_ = index->IsTrusted();
1611 uri_.set(pool, index->GetURI());
1612 distribution_.set(pool, index->GetDist());
1613 type_.set(pool, index->GetType());
1615 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1616 if (dindex != NULL) {
1618 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1621 pkgTagFile tags(&fd);
1623 pkgTagSection section;
1630 {"default-icon", &defaultIcon_},
1631 {"depiction", &depiction_},
1632 {"description", &description_},
1634 {"origin", &origin_},
1635 {"support", &support_},
1636 {"version", &version_},
1639 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1640 const char *start, *end;
1642 if (section.Find(names[i].name_, start, end)) {
1643 CYString &value(*names[i].value_);
1644 value.set(pool, start, end - start);
1650 record_ = [Sources_ objectForKey:[self key]];
1652 record_ = [record_ retain];
1654 NSURL *url([NSURL URLWithString:uri_]);
1658 host_ = [[host_ lowercaseString] retain];
1663 authority_ = [url path];
1665 if (authority_ != nil)
1666 authority_ = [authority_ retain];
1669 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1670 if ((self = [super init]) != nil) {
1671 [self setMetaIndex:index inPool:pool];
1675 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1676 NSDictionary *lhr = [self record];
1677 NSDictionary *rhr = [source record];
1680 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1682 NSString *lhs = [self name];
1683 NSString *rhs = [source name];
1685 if ([lhs length] != 0 && [rhs length] != 0) {
1686 unichar lhc = [lhs characterAtIndex:0];
1687 unichar rhc = [rhs characterAtIndex:0];
1689 if (isalpha(lhc) && !isalpha(rhc))
1690 return NSOrderedAscending;
1691 else if (!isalpha(lhc) && isalpha(rhc))
1692 return NSOrderedDescending;
1695 return [lhs compare:rhs options:LaxCompareOptions_];
1698 - (NSString *) depictionForPackage:(NSString *)package {
1699 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1702 - (NSString *) supportForPackage:(NSString *)package {
1703 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1706 - (NSDictionary *) record {
1714 - (NSString *) uri {
1718 - (NSString *) distribution {
1719 return distribution_;
1722 - (NSString *) type {
1726 - (NSString *) key {
1727 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1730 - (NSString *) host {
1734 - (NSString *) name {
1735 return origin_.empty() ? authority_ : origin_;
1738 - (NSString *) description {
1739 return description_;
1742 - (NSString *) label {
1743 return label_.empty() ? authority_ : label_;
1746 - (NSString *) origin {
1750 - (NSString *) version {
1754 - (NSString *) defaultIcon {
1755 return defaultIcon_;
1760 /* Relationship Class {{{ */
1761 @interface Relationship : NSObject {
1766 - (NSString *) type;
1768 - (NSString *) name;
1772 @implementation Relationship
1780 - (NSString *) type {
1788 - (NSString *) name {
1795 /* Package Class {{{ */
1796 struct ParsedPackage {
1801 CYString depiction_;
1811 @interface Package : NSObject {
1814 uint32_t essential_ : 1;
1815 uint32_t obsolete_ : 1;
1816 uint32_t ignored_ : 1;
1820 _transient Database *database_;
1822 pkgCache::VerIterator version_;
1823 pkgCache::PkgIterator iterator_;
1824 pkgCache::VerFileIterator file_;
1830 CYString installed_;
1832 const char *section_;
1833 _transient NSString *section$_;
1837 PackageValue *metadata_;
1838 ParsedPackage *parsed_;
1840 NSMutableArray *tags_;
1843 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1844 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1846 - (pkgCache::PkgIterator) iterator;
1849 - (NSString *) section;
1850 - (NSString *) simpleSection;
1852 - (NSString *) longSection;
1853 - (NSString *) shortSection;
1857 - (Address *) maintainer;
1859 - (NSString *) longDescription;
1860 - (NSString *) shortDescription;
1863 - (PackageValue *) metadata;
1866 - (bool) subscribed;
1867 - (bool) setSubscribed:(bool)subscribed;
1871 - (NSString *) latest;
1872 - (NSString *) installed;
1873 - (BOOL) uninstalled;
1876 - (BOOL) upgradableAndEssential:(BOOL)essential;
1879 - (BOOL) unfiltered;
1883 - (BOOL) halfConfigured;
1884 - (BOOL) halfInstalled;
1886 - (NSString *) mode;
1889 - (NSString *) name;
1891 - (NSString *) homepage;
1892 - (NSString *) depiction;
1893 - (Address *) author;
1895 - (NSString *) support;
1897 - (NSArray *) files;
1898 - (NSArray *) warnings;
1899 - (NSArray *) applications;
1901 - (Source *) source;
1903 - (BOOL) matches:(NSString *)text;
1905 - (bool) hasSupportingRole;
1906 - (BOOL) hasTag:(NSString *)tag;
1907 - (NSString *) primaryPurpose;
1908 - (NSArray *) purposes;
1909 - (bool) isCommercial;
1911 - (void) setIndex:(size_t)index;
1913 - (CYString &) cyname;
1915 - (uint32_t) compareBySection:(NSArray *)sections;
1920 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1921 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1922 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1923 - (bool) isVisibleInSection:(NSString *)section;
1924 - (bool) isVisibleInSource:(Source *)source;
1928 uint32_t PackageChangesRadix(Package *self, void *) {
1933 uint32_t timestamp : 30;
1934 uint32_t ignored : 1;
1935 uint32_t upgradable : 1;
1939 bool upgradable([self upgradableAndEssential:YES]);
1940 value.bits.upgradable = upgradable ? 1 : 0;
1943 value.bits.timestamp = 0;
1944 value.bits.ignored = [self ignored] ? 0 : 1;
1945 value.bits.upgradable = 1;
1947 value.bits.timestamp = [self seen] >> 2;
1948 value.bits.ignored = 0;
1949 value.bits.upgradable = 0;
1952 return _not(uint32_t) - value.key;
1955 uint32_t PackagePrefixRadix(Package *self, void *context) {
1956 size_t offset(reinterpret_cast<size_t>(context));
1957 CYString &name([self cyname]);
1959 size_t size(name.size());
1962 char *text(name.data());
1965 if (!isdigit(text[0]))
1969 while (size != digits && isdigit(text[digits]))
1977 if (offset == 0 && zeros != 0) {
1978 memset(data, '0', zeros);
1979 memcpy(data + zeros, text, 4 - zeros);
1981 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1982 if (size <= offset - zeros)
1985 text += offset - zeros;
1986 size -= offset - zeros;
1989 memcpy(data, text, 4);
1991 memcpy(data, text, size);
1992 memset(data + size, 0, 4 - size);
1995 for (size_t i(0); i != 4; ++i)
1996 if (isalpha(data[i]))
2004 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2006 /* XXX: ntohl may be more honest */
2007 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2010 CYString &(*PackageName)(Package *self, SEL sel);
2012 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2013 _profile(PackageNameCompare)
2014 CYString &lhi(PackageName(lhs, @selector(cyname)));
2015 CYString &rhi(PackageName(rhs, @selector(cyname)));
2016 CFStringRef lhn(lhi), rhn(rhi);
2019 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2020 else if (rhn == NULL)
2021 return NSOrderedDescending;
2023 _profile(PackageNameCompare$NumbersLast)
2024 if (!lhi.empty() && !rhi.empty()) {
2025 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2026 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2027 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2028 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2029 return lha ? NSOrderedAscending : NSOrderedDescending;
2033 CFIndex length = CFStringGetLength(lhn);
2035 _profile(PackageNameCompare$Compare)
2036 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2041 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2042 return PackageNameCompare(*lhs, *rhs, context);
2045 struct PackageNameOrdering :
2046 std::binary_function<Package *, Package *, bool>
2048 _finline bool operator ()(Package *lhs, Package *rhs) const {
2049 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2053 @implementation Package
2055 - (NSString *) description {
2056 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2060 if (parsed_ != NULL)
2069 + (NSString *) webScriptNameForSelector:(SEL)selector {
2070 if (selector == @selector(hasTag:))
2076 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2077 return [self webScriptNameForSelector:selector] == nil;
2080 + (NSArray *) _attributeKeys {
2081 return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"longDescription", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"longSection", @"maintainer", @"mode", @"name", @"purposes", @"section", @"shortDescription", @"shortSection", @"simpleSection", @"size", @"source", @"sponsor", @"support", @"warnings", nil];
2084 - (NSArray *) attributeKeys {
2085 return [[self class] _attributeKeys];
2088 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2089 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2093 if (parsed_ != NULL)
2095 @synchronized (database_) {
2096 if ([database_ era] != era_ || file_.end())
2099 ParsedPackage *parsed(new ParsedPackage);
2102 _profile(Package$parse)
2103 pkgRecords::Parser *parser;
2105 _profile(Package$parse$Lookup)
2106 parser = &[database_ records]->Lookup(file_);
2111 _profile(Package$parse$Find)
2116 {"icon", &parsed->icon_},
2117 {"depiction", &parsed->depiction_},
2118 {"homepage", &parsed->homepage_},
2119 {"website", &website},
2120 {"bugs", &parsed->bugs_},
2121 {"support", &parsed->support_},
2122 {"sponsor", &parsed->sponsor_},
2123 {"author", &parsed->author_},
2126 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2127 const char *start, *end;
2129 if (parser->Find(names[i].name_, start, end)) {
2130 CYString &value(*names[i].value_);
2131 _profile(Package$parse$Value)
2132 value.set(pool_, start, end - start);
2138 _profile(Package$parse$Tagline)
2139 const char *start, *end;
2140 if (parser->ShortDesc(start, end)) {
2141 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2144 while (stop != start && stop[-1] == '\r')
2146 parsed->tagline_.set(pool_, start, stop - start);
2150 _profile(Package$parse$Retain)
2151 if (parsed->homepage_.empty())
2152 parsed->homepage_ = website;
2153 if (parsed->homepage_ == parsed->depiction_)
2154 parsed->homepage_.clear();
2159 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2160 if ((self = [super init]) != nil) {
2161 _profile(Package$initWithVersion)
2164 database_ = database;
2165 era_ = [database era];
2169 pkgCache::PkgIterator iterator(version.ParentPkg());
2170 iterator_ = iterator;
2172 _profile(Package$initWithVersion$Version)
2173 if (!version_.end())
2174 file_ = version_.FileList();
2176 pkgCache &cache([database_ cache]);
2177 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2181 _profile(Package$initWithVersion$Cache)
2182 name_.set(NULL, iterator.Display());
2184 latest_.set(NULL, StripVersion_(version_.VerStr()));
2186 pkgCache::VerIterator current(iterator.CurrentVer());
2188 installed_.set(NULL, StripVersion_(current.VerStr()));
2191 _profile(Package$initWithVersion$Tags)
2192 pkgCache::TagIterator tag(iterator.TagList());
2194 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2196 const char *name(tag.Name());
2197 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2199 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2200 if (strcmp(name + 6, "enduser") == 0)
2202 else if (strcmp(name + 6, "hacker") == 0)
2204 else if (strcmp(name + 6, "developer") == 0)
2206 else if (strcmp(name + 6, "cydia") == 0)
2212 if (strncmp(name, "cydia::", 7) == 0) {
2213 if (strcmp(name + 7, "essential") == 0)
2215 else if (strcmp(name + 7, "obsolete") == 0)
2220 } while (!tag.end());
2224 _profile(Package$initWithVersion$Metadata)
2225 const char *mixed(iterator.Name());
2226 size_t size(strlen(mixed));
2227 char lower[size + 1];
2229 for (size_t i(0); i != size; ++i)
2230 lower[i] = mixed[i] | 0x20;
2233 PackageValue *metadata(PackageFind(lower, size));
2234 metadata_ = metadata;
2236 id_.set(NULL, metadata->name_, size);
2238 const char *latest(version_.VerStr());
2239 size_t length(strlen(latest));
2241 uint16_t vhash(hashlittle(latest, length));
2243 size_t capped(std::min<size_t>(8, length));
2244 latest = latest + length - capped;
2246 if (metadata->first_ == 0)
2247 metadata->first_ = now_;
2249 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2250 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2251 metadata->vhash_ = vhash;
2252 metadata->last_ = now_;
2253 } else if (metadata->last_ == 0)
2254 metadata->last_ = metadata->first_;
2257 _profile(Package$initWithVersion$Section)
2258 section_ = iterator.Section();
2261 _profile(Package$initWithVersion$Flags)
2262 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2263 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2268 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2269 pkgCache::VerIterator version;
2271 _profile(Package$packageWithIterator$GetCandidateVer)
2272 version = [database policy]->GetCandidateVer(iterator);
2280 _profile(Package$packageWithIterator$Allocate)
2281 package = [Package allocWithZone:zone];
2284 _profile(Package$packageWithIterator$Initialize)
2286 initWithVersion:version
2293 _profile(Package$packageWithIterator$Autorelease)
2294 package = [package autorelease];
2300 - (pkgCache::PkgIterator) iterator {
2304 - (NSString *) section {
2305 if (section$_ == nil) {
2306 if (section_ == NULL)
2309 _profile(Package$section$mappedSectionForPointer)
2310 section$_ = [database_ mappedSectionForPointer:section_];
2315 - (NSString *) simpleSection {
2316 if (NSString *section = [self section])
2317 return Simplify(section);
2322 - (NSString *) longSection {
2323 return LocalizeSection([self section]);
2326 - (NSString *) shortSection {
2327 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2330 - (NSString *) uri {
2333 pkgIndexFile *index;
2334 pkgCache::PkgFileIterator file(file_.File());
2335 if (![database_ list].FindIndex(file, index))
2337 return [NSString stringWithUTF8String:iterator_->Path];
2338 //return [NSString stringWithUTF8String:file.Site()];
2339 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2343 - (Address *) maintainer {
2344 @synchronized (database_) {
2345 if ([database_ era] != era_ || file_.end())
2348 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2349 const std::string &maintainer(parser->Maintainer());
2350 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2354 @synchronized (database_) {
2355 if ([database_ era] != era_ || version_.end())
2358 return version_->InstalledSize;
2361 - (NSString *) longDescription {
2362 @synchronized (database_) {
2363 if ([database_ era] != era_ || file_.end())
2366 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2367 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2369 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2370 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2371 if ([lines count] < 2)
2374 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2375 for (size_t i(1), e([lines count]); i != e; ++i) {
2376 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2377 [trimmed addObject:trim];
2380 return [trimmed componentsJoinedByString:@"\n"];
2383 - (NSString *) shortDescription {
2384 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2388 _profile(Package$index)
2389 CFStringRef name((CFStringRef) [self name]);
2390 if (CFStringGetLength(name) == 0)
2392 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2393 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2395 return toupper(character);
2399 - (PackageValue *) metadata {
2404 PackageValue *metadata([self metadata]);
2405 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2408 - (bool) subscribed {
2409 return [self metadata]->subscribed_;
2412 - (bool) setSubscribed:(bool)subscribed {
2413 PackageValue *metadata([self metadata]);
2414 if (metadata->subscribed_ == subscribed)
2416 metadata->subscribed_ = subscribed;
2424 - (NSString *) latest {
2428 - (NSString *) installed {
2432 - (BOOL) uninstalled {
2433 return installed_.empty();
2437 return !version_.end();
2440 - (BOOL) upgradableAndEssential:(BOOL)essential {
2441 _profile(Package$upgradableAndEssential)
2442 pkgCache::VerIterator current(iterator_.CurrentVer());
2444 return essential && essential_;
2446 return !version_.end() && version_ != current;
2450 - (BOOL) essential {
2455 return [database_ cache][iterator_].InstBroken();
2458 - (BOOL) unfiltered {
2459 _profile(Package$unfiltered$obsolete)
2460 if (_unlikely(obsolete_))
2464 _profile(Package$unfiltered$hasSupportingRole)
2465 if (_unlikely(![self hasSupportingRole]))
2473 if (![self unfiltered])
2478 _profile(Package$visible$section)
2479 section = [self section];
2482 _profile(Package$visible$isSectionVisible)
2483 if (section != nil && !isSectionVisible(section))
2491 unsigned char current(iterator_->CurrentState);
2492 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2495 - (BOOL) halfConfigured {
2496 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2499 - (BOOL) halfInstalled {
2500 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2504 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2505 return state.Mode != pkgDepCache::ModeKeep;
2508 - (NSString *) mode {
2509 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2511 switch (state.Mode) {
2512 case pkgDepCache::ModeDelete:
2513 if ((state.iFlags & pkgDepCache::Purge) != 0)
2517 case pkgDepCache::ModeKeep:
2518 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2519 return @"REINSTALL";
2520 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2524 case pkgDepCache::ModeInstall:
2525 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2526 return @"REINSTALL";
2527 else*/ switch (state.Status) {
2529 return @"DOWNGRADE";
2535 return @"NEW_INSTALL";
2546 - (NSString *) name {
2547 return name_.empty() ? id_ : name_;
2550 - (UIImage *) icon {
2551 NSString *section = [self simpleSection];
2554 if (parsed_ != NULL)
2555 if (NSString *href = parsed_->icon_)
2556 if ([href hasPrefix:@"file:///"])
2557 // XXX: correct escaping
2558 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2559 if (icon == nil) if (section != nil)
2560 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2561 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2562 if ([dicon hasPrefix:@"file:///"])
2563 // XXX: correct escaping
2564 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2566 icon = [UIImage applicationImageNamed:@"unknown.png"];
2570 - (NSString *) homepage {
2571 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2574 - (NSString *) depiction {
2575 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2578 - (Address *) sponsor {
2579 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2582 - (Address *) author {
2583 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2586 - (NSString *) support {
2587 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2590 - (NSArray *) files {
2591 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2592 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2595 fin.open([path UTF8String]);
2600 while (std::getline(fin, line))
2601 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2606 - (NSArray *) warnings {
2607 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2608 const char *name(iterator_.Name());
2610 size_t length(strlen(name));
2611 if (length < 2) invalid:
2612 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2613 else for (size_t i(0); i != length; ++i)
2615 /* XXX: technically this is not allowed */
2616 (name[i] < 'A' || name[i] > 'Z') &&
2617 (name[i] < 'a' || name[i] > 'z') &&
2618 (name[i] < '0' || name[i] > '9') &&
2619 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2622 if (strcmp(name, "cydia") != 0) {
2625 bool _private = false;
2628 bool repository = [[self section] isEqualToString:@"Repositories"];
2630 if (NSArray *files = [self files])
2631 for (NSString *file in files)
2632 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2634 else if (!user && [file isEqualToString:@"/User"])
2636 else if (!_private && [file isEqualToString:@"/private"])
2638 else if (!stash && [file isEqualToString:@"/var/stash"])
2641 /* XXX: this is not sensitive enough. only some folders are valid. */
2642 if (cydia && !repository)
2643 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2645 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2647 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2649 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2652 return [warnings count] == 0 ? nil : warnings;
2655 - (NSArray *) applications {
2656 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2658 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2660 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2661 if (NSArray *files = [self files])
2662 for (NSString *file in files)
2663 if (application_r(file)) {
2664 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2665 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2666 if ([id isEqualToString:me])
2669 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2671 display = application_r[1];
2673 NSString *bundle([file stringByDeletingLastPathComponent]);
2674 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2675 if (icon == nil || [icon length] == 0)
2677 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2679 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2680 [applications addObject:application];
2682 [application addObject:id];
2683 [application addObject:display];
2684 [application addObject:url];
2687 return [applications count] == 0 ? nil : applications;
2690 - (Source *) source {
2691 if (source_ == nil) {
2692 @synchronized (database_) {
2693 if ([database_ era] != era_ || file_.end())
2694 source_ = (Source *) [NSNull null];
2696 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2700 return source_ == (Source *) [NSNull null] ? nil : source_;
2703 - (BOOL) matches:(NSString *)text {
2709 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2710 if (range.location != NSNotFound)
2713 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2714 if (range.location != NSNotFound)
2719 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2720 if (range.location != NSNotFound)
2726 - (bool) hasSupportingRole {
2731 if ([Role_ isEqualToString:@"User"])
2735 if ([Role_ isEqualToString:@"Hacker"])
2739 if ([Role_ isEqualToString:@"Developer"])
2744 - (BOOL) hasTag:(NSString *)tag {
2745 return tags_ == nil ? NO : [tags_ containsObject:tag];
2748 - (NSString *) primaryPurpose {
2749 for (NSString *tag in tags_)
2750 if ([tag hasPrefix:@"purpose::"])
2751 return [tag substringFromIndex:9];
2755 - (NSArray *) purposes {
2756 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2757 for (NSString *tag in tags_)
2758 if ([tag hasPrefix:@"purpose::"])
2759 [purposes addObject:[tag substringFromIndex:9]];
2760 return [purposes count] == 0 ? nil : purposes;
2763 - (bool) isCommercial {
2764 return [self hasTag:@"cydia::commercial"];
2767 - (void) setIndex:(size_t)index {
2768 if (metadata_->index_ != index)
2769 metadata_->index_ = index;
2772 - (CYString &) cyname {
2773 return name_.empty() ? id_ : name_;
2776 - (uint32_t) compareBySection:(NSArray *)sections {
2777 NSString *section([self section]);
2778 for (size_t i(0), e([sections count]); i != e; ++i) {
2779 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2783 return _not(uint32_t);
2787 @synchronized (database_) {
2788 pkgProblemResolver *resolver = [database_ resolver];
2789 resolver->Clear(iterator_);
2791 pkgCacheFile &cache([database_ cache]);
2792 cache->SetReInstall(iterator_, false);
2793 cache->MarkKeep(iterator_, false);
2797 @synchronized (database_) {
2798 pkgProblemResolver *resolver = [database_ resolver];
2799 resolver->Clear(iterator_);
2800 resolver->Protect(iterator_);
2802 pkgCacheFile &cache([database_ cache]);
2803 cache->SetReInstall(iterator_, false);
2804 cache->MarkInstall(iterator_, false);
2806 pkgDepCache::StateCache &state((*cache)[iterator_]);
2807 if (!state.Install())
2808 cache->SetReInstall(iterator_, true);
2812 @synchronized (database_) {
2813 pkgProblemResolver *resolver = [database_ resolver];
2814 resolver->Clear(iterator_);
2815 resolver->Remove(iterator_);
2816 resolver->Protect(iterator_);
2818 pkgCacheFile &cache([database_ cache]);
2819 cache->SetReInstall(iterator_, false);
2820 cache->MarkDelete(iterator_, true);
2823 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2824 _profile(Package$isUnfilteredAndSearchedForBy)
2827 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2828 value &= [self unfiltered];
2831 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2832 value &= [self matches:search];
2839 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2840 if ([search length] == 0)
2843 _profile(Package$isUnfilteredAndSelectedForBy)
2846 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2847 value &= [self unfiltered];
2850 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2851 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2858 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2859 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2862 - (bool) isVisibleInSection:(NSString *)name {
2863 NSString *section([self section]);
2867 section == nil && [name length] == 0 ||
2868 [name isEqualToString:section]
2869 ) && [self visible];
2872 - (bool) isVisibleInSource:(Source *)source {
2873 return [self source] == source && [self visible];
2878 /* Section Class {{{ */
2879 @interface Section : NSObject {
2884 NSString *localized_;
2887 - (NSComparisonResult) compareByLocalized:(Section *)section;
2888 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2889 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2890 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2891 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2892 - (NSString *) name;
2899 - (void) addToCount;
2901 - (void) setCount:(size_t)count;
2902 - (NSString *) localized;
2906 @implementation Section
2910 if (localized_ != nil)
2911 [localized_ release];
2915 - (NSComparisonResult) compareByLocalized:(Section *)section {
2916 NSString *lhs(localized_);
2917 NSString *rhs([section localized]);
2919 /*if ([lhs length] != 0 && [rhs length] != 0) {
2920 unichar lhc = [lhs characterAtIndex:0];
2921 unichar rhc = [rhs characterAtIndex:0];
2923 if (isalpha(lhc) && !isalpha(rhc))
2924 return NSOrderedAscending;
2925 else if (!isalpha(lhc) && isalpha(rhc))
2926 return NSOrderedDescending;
2929 return [lhs compare:rhs options:LaxCompareOptions_];
2932 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2933 if ((self = [self initWithName:name localize:NO]) != nil) {
2934 if (localized != nil)
2935 localized_ = [localized retain];
2939 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2940 return [self initWithName:name row:0 localize:localize];
2943 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2944 if ((self = [super init]) != nil) {
2945 name_ = [name retain];
2949 localized_ = [LocalizeSection(name_) retain];
2953 /* XXX: localize the index thingees */
2954 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2955 if ((self = [super init]) != nil) {
2956 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2962 - (NSString *) name {
2982 - (void) addToCount {
2986 - (void) setCount:(size_t)count {
2990 - (NSString *) localized {
2997 static NSString *Colon_;
2998 static NSString *Elision_;
2999 static NSString *Error_;
3000 static NSString *Warning_;
3002 /* Database Implementation {{{ */
3003 @implementation Database
3005 + (Database *) sharedInstance {
3006 static Database *instance;
3007 if (instance == nil)
3008 instance = [[Database alloc] init];
3016 - (void) releasePackages {
3017 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3018 CFArrayRemoveAllValues(packages_);
3022 // XXX: actually implement this thing
3025 CFRelease(deadSources_);
3026 [self releasePackages];
3027 apr_pool_destroy(pool_);
3028 NSRecycleZone(zone_);
3032 - (void) _readCydia:(NSNumber *)fd { _pooled
3033 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3034 std::istream is(&ib);
3037 static Pcre finish_r("^finish:([^:]*)$");
3039 while (std::getline(is, line)) {
3040 const char *data(line.c_str());
3041 size_t size = line.size();
3042 lprintf("C:%s\n", data);
3044 if (finish_r(data, size)) {
3045 NSString *finish = finish_r[1];
3046 int index = [Finishes_ indexOfObject:finish];
3047 if (index != INT_MAX && index > Finish_)
3055 - (void) _readStatus:(NSNumber *)fd { _pooled
3056 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3057 std::istream is(&ib);
3060 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3061 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3063 while (std::getline(is, line)) {
3064 const char *data(line.c_str());
3065 size_t size(line.size());
3066 lprintf("S:%s\n", data);
3068 if (conffile_r(data, size)) {
3069 [delegate_ setConfigurationData:conffile_r[1]];
3070 } else if (strncmp(data, "status: ", 8) == 0) {
3071 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3072 [delegate_ setProgressTitle:string];
3073 } else if (pmstatus_r(data, size)) {
3074 std::string type([pmstatus_r[1] UTF8String]);
3075 NSString *id = pmstatus_r[2];
3077 float percent([pmstatus_r[3] floatValue]);
3078 [delegate_ setProgressPercent:(percent / 100)];
3080 NSString *string = pmstatus_r[4];
3082 if (type == "pmerror")
3083 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3084 withObject:[NSArray arrayWithObjects:string, id, nil]
3087 else if (type == "pmstatus") {
3088 [delegate_ setProgressTitle:string];
3089 } else if (type == "pmconffile")
3090 [delegate_ setConfigurationData:string];
3092 lprintf("E:unknown pmstatus\n");
3094 lprintf("E:unknown status\n");
3100 - (void) _readOutput:(NSNumber *)fd { _pooled
3101 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3102 std::istream is(&ib);
3105 while (std::getline(is, line)) {
3106 lprintf("O:%s\n", line.c_str());
3107 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3117 - (Package *) packageWithName:(NSString *)name {
3118 @synchronized (self) {
3119 if (static_cast<pkgDepCache *>(cache_) == NULL)
3121 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3122 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3126 if ((self = [super init]) != nil) {
3133 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3134 apr_pool_create(&pool_, NULL);
3136 size_t capacity(MetaFile_->active_);
3142 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3143 deadSources_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
3147 _assert(pipe(fds) != -1);
3150 _config->Set("APT::Keep-Fds::", cydiafd_);
3151 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3154 detachNewThreadSelector:@selector(_readCydia:)
3156 withObject:[NSNumber numberWithInt:fds[0]]
3159 _assert(pipe(fds) != -1);
3163 detachNewThreadSelector:@selector(_readStatus:)
3165 withObject:[NSNumber numberWithInt:fds[0]]
3168 _assert(pipe(fds) != -1);
3169 _assert(dup2(fds[0], 0) != -1);
3170 _assert(close(fds[0]) != -1);
3172 input_ = fdopen(fds[1], "a");
3174 _assert(pipe(fds) != -1);
3175 _assert(dup2(fds[1], 1) != -1);
3176 _assert(close(fds[1]) != -1);
3179 detachNewThreadSelector:@selector(_readOutput:)
3181 withObject:[NSNumber numberWithInt:fds[0]]
3186 - (pkgCacheFile &) cache {
3190 - (pkgDepCache::Policy *) policy {
3194 - (pkgRecords *) records {
3198 - (pkgProblemResolver *) resolver {
3202 - (pkgAcquire &) fetcher {
3206 - (pkgSourceList &) list {
3210 - (NSArray *) packages {
3211 return (NSArray *) packages_;
3214 - (NSArray *) sources {
3215 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3216 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3217 [sources addObject:i->second];
3218 [sources addObjectsFromArray:(NSArray *)deadSources_];
3222 - (NSArray *) issues {
3223 if (cache_->BrokenCount() == 0)
3226 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3228 for (Package *package in [self packages]) {
3229 if (![package broken])
3231 pkgCache::PkgIterator pkg([package iterator]);
3233 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3234 [entry addObject:[package name]];
3235 [issues addObject:entry];
3237 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3241 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3242 pkgCache::DepIterator start;
3243 pkgCache::DepIterator end;
3244 dep.GlobOr(start, end); // ++dep
3246 if (!cache_->IsImportantDep(end))
3248 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3251 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3252 [entry addObject:failure];
3253 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3255 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3256 if (Package *package = [self packageWithName:name])
3257 name = [package name];
3258 [failure addObject:name];
3260 pkgCache::PkgIterator target(start.TargetPkg());
3261 if (target->ProvidesList != 0)
3262 [failure addObject:@"?"];
3264 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3266 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3267 else if (!cache_[target].CandidateVerIter(cache_).end())
3268 [failure addObject:@"-"];
3269 else if (target->ProvidesList == 0)
3270 [failure addObject:@"!"];
3272 [failure addObject:@"%"];
3276 if (start.TargetVer() != 0)
3277 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3288 - (bool) popErrorWithTitle:(NSString *)title {
3290 std::string message;
3292 while (!_error->empty()) {
3294 bool warning(!_error->PopMessage(error));
3298 size_t size(error.size());
3299 if (size == 0 || error[size - 1] != '\n')
3301 error.resize(size - 1);
3303 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3305 if (!message.empty())
3310 if (fatal && !message.empty())
3311 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3316 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3317 return [self popErrorWithTitle:title] || !success;
3320 - (void) reloadData { CYPoolStart() {
3321 @synchronized (self) {
3324 [self releasePackages];
3327 CFArrayRemoveAllValues(deadSources_);
3347 apr_pool_clear(pool_);
3349 NSRecycleZone(zone_);
3350 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3352 int chk(creat("/tmp/cydia.chk", 0644));
3356 NSString *title(UCLocalize("DATABASE"));
3359 while (!cache_.Open(progress_, true)) { pop:
3361 bool warning(!_error->PopMessage(error));
3362 lprintf("cache_.Open():[%s]\n", error.c_str());
3364 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3365 [delegate_ repairWithSelector:@selector(configure)];
3366 else if (error == "The package lists or status file could not be parsed or opened.")
3367 [delegate_ repairWithSelector:@selector(update)];
3368 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3369 else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3370 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, Error_, title]];
3371 // else if (error == "The list of sources could not be read.")
3373 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3383 unlink("/tmp/cydia.chk");
3385 now_ = [[NSDate date] timeIntervalSince1970];
3387 policy_ = new pkgDepCache::Policy();
3388 records_ = new pkgRecords(cache_);
3389 resolver_ = new pkgProblemResolver(cache_);
3390 fetcher_ = new pkgAcquire(&status_);
3393 list_ = new pkgSourceList();
3394 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3397 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3398 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3402 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3405 if (cache_->BrokenCount() != 0) {
3406 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3409 if (cache_->BrokenCount() != 0) {
3410 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3414 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3418 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3420 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3421 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3422 // XXX: this could be more intelligent
3423 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3424 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3425 if (!cached.end()) {
3426 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3431 CFArrayAppendValue(deadSources_, [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3435 /*std::vector<Package *> packages;
3436 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3437 [packages_ release];
3442 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3443 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3444 //packages.push_back(package);
3445 CFArrayAppendValue(packages_, [package retain]);
3449 /*if (packages.empty())
3450 packages_ = [[NSArray alloc] init];
3452 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3455 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3456 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3457 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3465 /*if (!packages.empty())
3466 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3467 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3469 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3471 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3473 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3477 size_t count(CFArrayGetCount(packages_));
3478 MetaFile_->active_ = count;
3480 for (size_t index(0); index != count; ++index)
3481 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3485 } } CYPoolEnd() _trace(); }
3488 @synchronized (self) {
3490 resolver_ = new pkgProblemResolver(cache_);
3492 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3493 if (!cache_[iterator].Keep()) {
3494 cache_->MarkKeep(iterator, false);
3495 cache_->SetReInstall(iterator, false);
3500 - (void) configure {
3501 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3503 system([dpkg UTF8String]);
3508 // XXX: I don't remember this condition
3513 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3515 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3517 if ([self popErrorWithTitle:title])
3521 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3524 public pkgArchiveCleaner
3527 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3532 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3539 fetcher_->Shutdown();
3541 pkgRecords records(cache_);
3543 lock_ = new FileFd();
3544 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3546 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3548 if ([self popErrorWithTitle:title])
3552 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3555 manager_ = (_system->CreatePM(cache_));
3556 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3563 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3565 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3567 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3569 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3570 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3573 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3578 [CydiaApp retainNetworkActivityIndicator];
3580 bool failed = false;
3581 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3582 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3584 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3587 std::string uri = (*item)->DescURI();
3588 std::string error = (*item)->ErrorText;
3590 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3593 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3594 withObject:[NSArray arrayWithObjects:
3595 [NSString stringWithUTF8String:error.c_str()],
3601 [CydiaApp releaseNetworkActivityIndicator];
3609 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3611 if (_error->PendingError()) {
3616 if (result == pkgPackageManager::Failed) {
3621 if (result != pkgPackageManager::Completed) {
3626 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3628 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3630 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3631 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3634 if (![before isEqualToArray:after])
3639 NSString *title(UCLocalize("UPGRADE"));
3640 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3646 [self updateWithStatus:status_];
3649 - (void) updateWithStatus:(Status &)status {
3650 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3651 NSString *title(UCLocalize("REFRESHING_DATA"));
3654 if (!list.ReadMainList())
3655 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3658 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3659 if ([self popErrorWithTitle:title])
3662 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3663 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3664 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3666 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3670 - (void) setDelegate:(id)delegate {
3671 delegate_ = delegate;
3672 status_.setDelegate(delegate);
3673 progress_.setDelegate(delegate);
3676 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3677 SourceMap::const_iterator i(sources_.find(file->ID));
3678 return i == sources_.end() ? nil : i->second;
3681 - (NSString *) mappedSectionForPointer:(const char *)section {
3682 _H<NSString> *mapped;
3684 _profile(Database$mappedSectionForPointer$Cache)
3685 mapped = §ions_[section];
3688 if (*mapped == NULL) {
3689 size_t length(strlen(section));
3690 char spaced[length + 1];
3692 _profile(Database$mappedSectionForPointer$Replace)
3693 for (size_t index(0); index != length; ++index)
3694 spaced[index] = section[index] == '_' ? ' ' : section[index];
3695 spaced[length] = '\0';
3700 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3701 string = [NSString stringWithUTF8String:spaced];
3704 _profile(Database$mappedSectionForPointer$Map)
3705 string = [SectionMap_ objectForKey:string] ?: string;
3715 /* Web Scripting {{{ */
3716 @interface CydiaObject : NSObject {
3718 _transient id delegate_;
3721 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3724 @implementation CydiaObject
3727 [indirect_ release];
3731 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3732 if ((self = [super init]) != nil) {
3733 indirect_ = [indirect retain];
3737 - (void) setDelegate:(id)delegate {
3738 delegate_ = delegate;
3741 + (NSArray *) _attributeKeys {
3742 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3745 - (NSArray *) attributeKeys {
3746 return [[self class] _attributeKeys];
3749 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3750 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3753 - (NSString *) device {
3754 return [[UIDevice currentDevice] uniqueIdentifier];
3757 #if 0 // XXX: implement!
3758 - (NSString *) mac {
3759 if (![indirect_ promptForSensitive:@"Mac Address"])
3763 - (NSString *) serial {
3764 if (![indirect_ promptForSensitive:@"Serial #"])
3768 - (NSString *) firewire {
3769 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3773 - (NSString *) imei {
3774 if (![indirect_ promptForSensitive:@"IMEI"])
3779 + (NSString *) webScriptNameForSelector:(SEL)selector {
3780 if (selector == @selector(close))
3782 else if (selector == @selector(getInstalledPackages))
3783 return @"getInstalledPackages";
3784 else if (selector == @selector(getPackageById:))
3785 return @"getPackageById";
3786 else if (selector == @selector(installPackages:))
3787 return @"installPackages";
3788 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3789 return @"setButtonImage";
3790 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3791 return @"setButtonTitle";
3792 else if (selector == @selector(setPopupHook:))
3793 return @"setPopupHook";
3794 else if (selector == @selector(setSpecial:))
3795 return @"setSpecial";
3796 else if (selector == @selector(setToken:))
3798 else if (selector == @selector(setViewportWidth:))
3799 return @"setViewportWidth";
3800 else if (selector == @selector(supports:))
3802 else if (selector == @selector(stringWithFormat:arguments:))
3804 else if (selector == @selector(localizedStringForKey:value:table:))
3806 else if (selector == @selector(du:))
3808 else if (selector == @selector(statfs:))
3814 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3815 return [self webScriptNameForSelector:selector] == nil;
3818 - (BOOL) supports:(NSString *)feature {
3819 return [feature isEqualToString:@"window.open"];
3822 - (NSArray *) getInstalledPackages {
3823 NSArray *packages([[Database sharedInstance] packages]);
3824 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3825 for (Package *package in packages)
3826 if ([package installed] != nil)
3827 [installed addObject:package];
3831 - (Package *) getPackageById:(NSString *)id {
3832 Package *package([[Database sharedInstance] packageWithName:id]);
3837 - (NSArray *) statfs:(NSString *)path {
3840 if (path == nil || statfs([path UTF8String], &stat) == -1)
3843 return [NSArray arrayWithObjects:
3844 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3845 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3846 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3850 - (NSNumber *) du:(NSString *)path {
3851 NSNumber *value(nil);
3854 _assert(pipe(fds) != -1);
3856 pid_t pid(ExecFork());
3858 _assert(dup2(fds[1], 1) != -1);
3859 _assert(close(fds[0]) != -1);
3860 _assert(close(fds[1]) != -1);
3861 /* XXX: this should probably not use du */
3862 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3867 _assert(close(fds[1]) != -1);
3869 if (FILE *du = fdopen(fds[0], "r")) {
3871 while (fgets(line, sizeof(line), du) != NULL) {
3872 size_t length(strlen(line));
3873 while (length != 0 && line[length - 1] == '\n')
3874 line[--length] = '\0';
3875 if (char *tab = strchr(line, '\t')) {
3877 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3882 } else _assert(close(fds[0]));
3886 if (waitpid(pid, &status, 0) == -1)
3889 else _assert(false);
3898 - (void) installPackages:(NSArray *)packages {
3899 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3902 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3903 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3906 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3907 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3910 - (void) setSpecial:(id)function {
3911 [indirect_ setSpecial:function];
3914 - (void) setToken:(NSString *)token {
3917 Token_ = [token retain];
3919 [Metadata_ setObject:Token_ forKey:@"Token"];
3923 - (void) setPopupHook:(id)function {
3924 [indirect_ setPopupHook:function];
3927 - (void) setViewportWidth:(float)width {
3928 [indirect_ setViewportWidth:width];
3931 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3932 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3933 unsigned count([arguments count]);
3935 for (unsigned i(0); i != count; ++i)
3936 values[i] = [arguments objectAtIndex:i];
3937 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3940 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3941 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3943 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3945 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3951 /* @ Loading... Indicator {{{ */
3952 @interface CYLoadingIndicator : UIView {
3953 UIActivityIndicatorView *spinner_;
3958 @property (readonly, nonatomic) UILabel *label;
3959 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
3963 @implementation CYLoadingIndicator
3965 - (id)initWithFrame:(CGRect)frame {
3966 if ((self = [super initWithFrame:frame])) {
3967 container_ = [[[UIView alloc] init] autorelease];
3968 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
3970 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
3971 [spinner_ startAnimating];
3972 [container_ addSubview:spinner_];
3974 label_ = [[[UILabel alloc] init] autorelease];
3975 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
3976 [label_ setBackgroundColor:[UIColor clearColor]];
3977 [label_ setTextColor:[UIColor blackColor]];
3978 [label_ setShadowColor:[UIColor whiteColor]];
3979 [label_ setShadowOffset:CGSizeMake(0, 1)];
3980 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
3981 [container_ addSubview:label_];
3983 CGSize viewsize = frame.size;
3984 CGSize spinnersize = [spinner_ bounds].size;
3985 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
3986 float bothwidth = spinnersize.width + textsize.width + 5.0f;
3988 CGRect containrect = {
3989 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
3990 CGSizeMake(bothwidth, spinnersize.height)
3993 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4001 [container_ setFrame:containrect];
4002 [spinner_ setFrame:spinrect];
4003 [label_ setFrame:textrect];
4004 [self addSubview:container_];
4010 - (UILabel *)label { return label_; }
4011 - (UIActivityIndicatorView *)activityIndicatorView { return spinner_; }
4015 /* Emulated Loading Controller {{{ */
4016 @interface CYEmulatedLoadingController : CYViewController <
4018 ConfigurationDelegate
4020 _transient Database *database_;
4021 CYLoadingIndicator *indicator_;
4023 UINavigationBar *navbar_;
4027 @implementation CYEmulatedLoadingController
4030 [self releaseSubviews];
4031 [database_ setDelegate:nil];
4036 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4037 CYAlertView *sheet([[[CYAlertView alloc]
4039 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4040 defaultButtonIndex:0
4043 [sheet setMessage:error];
4044 [sheet yieldToPopupAlertAnimated:YES];
4048 - (void) setProgressTitle:(NSString *)title { }
4049 - (void) setProgressPercent:(float)percent { }
4050 - (void) startProgress { }
4051 - (void) addProgressOutput:(NSString *)output { }
4052 - (bool) isCancelling:(size_t)received { return NO; }
4053 - (void) setConfigurationData:(NSString *)data { }
4055 - (void) repairWithSelector:(SEL)selector {
4056 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("REPAIRING"), nil] waitUntilDone:YES];
4057 [database_ performSelector:selector];
4059 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil] waitUntilDone:YES];
4062 - (id) initWithDatabase:(Database *)database {
4063 if ((self = [super init])) {
4064 database_ = database;
4065 [database_ setDelegate:self];
4070 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4071 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4073 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4074 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4075 [[self view] addSubview:indicator_];
4077 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4078 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4079 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4080 [[self view] addSubview:tabbar_];
4082 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4083 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4084 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4085 [[self view] addSubview:navbar_];
4088 - (void) releaseSubviews {
4089 [indicator_ release];
4102 /* Cydia Browser Controller {{{ */
4103 @interface CYBrowserController : BrowserController {
4104 CydiaObject *cydia_;
4109 @implementation CYBrowserController
4116 - (NSURL *) navigationURL {
4117 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4120 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4123 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4124 [super webView:view didClearWindowObject:window forFrame:frame];
4126 WebDataSource *source([frame dataSource]);
4127 NSURLResponse *response([source response]);
4129 NSURL *url([response URL]);
4130 NSString *scheme([url scheme]);
4131 NSString *host([url host]);
4133 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4134 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4135 NSDictionary *headers([http allHeaderFields]);
4136 [self setHeaders:headers forHost:host];
4140 [host isEqualToString:@"cydia.saurik.com"] ||
4141 [host hasSuffix:@".cydia.saurik.com"] ||
4142 [scheme isEqualToString:@"file"]
4144 [window setValue:cydia_ forKey:@"cydia"];
4147 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4148 if (System_ != NULL)
4149 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4150 if (Machine_ != NULL)
4151 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4153 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4155 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4158 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4159 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4160 [self _setMoreHeaders:copy];
4164 - (void) setDelegate:(id)delegate {
4165 [super setDelegate:delegate];
4166 [cydia_ setDelegate:delegate];
4170 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4171 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4173 WebView *webview([[webview_ _documentView] webView]);
4175 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4177 NSString *application = package == nil ? @"Cydia" : [NSString
4178 stringWithFormat:@"Cydia/%@",
4183 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4185 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4186 if (Product_ != nil)
4187 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4189 [webview setApplicationNameForUserAgent:application];
4196 /* Confirmation Controller {{{ */
4197 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4198 if (!iterator.end())
4199 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4200 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4202 pkgCache::PkgIterator package(dep.TargetPkg());
4205 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4212 @protocol ConfirmationControllerDelegate
4213 - (void) cancelAndClear:(bool)clear;
4214 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4218 @interface ConfirmationController : CYBrowserController {
4219 _transient Database *database_;
4220 UIAlertView *essential_;
4227 - (id) initWithDatabase:(Database *)database;
4231 @implementation ConfirmationController
4238 if (essential_ != nil)
4239 [essential_ release];
4243 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4244 NSString *context([alert context]);
4246 if ([context isEqualToString:@"remove"]) {
4247 if (button == [alert cancelButtonIndex]) {
4248 [self dismissModalViewControllerAnimated:YES];
4249 } else if (button == [alert firstOtherButtonIndex]) {
4252 [delegate_ confirmWithNavigationController:[self navigationController]];
4255 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4256 } else if ([context isEqualToString:@"unable"]) {
4257 [self dismissModalViewControllerAnimated:YES];
4258 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4260 [super alertView:alert clickedButtonAtIndex:button];
4264 - (void) _doContinue {
4265 [self dismissModalViewControllerAnimated:YES];
4266 [delegate_ cancelAndClear:NO];
4269 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4270 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4274 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4275 [super webView:view didClearWindowObject:window forFrame:frame];
4276 [window setValue:changes_ forKey:@"changes"];
4277 [window setValue:issues_ forKey:@"issues"];
4278 [window setValue:sizes_ forKey:@"sizes"];
4279 [window setValue:self forKey:@"queue"];
4282 - (id) initWithDatabase:(Database *)database {
4283 if ((self = [super init]) != nil) {
4284 database_ = database;
4286 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4288 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4289 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4290 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4291 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4292 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4296 pkgDepCache::Policy *policy([database_ policy]);
4298 pkgCacheFile &cache([database_ cache]);
4299 NSArray *packages = [database_ packages];
4300 for (Package *package in packages) {
4301 pkgCache::PkgIterator iterator = [package iterator];
4302 pkgDepCache::StateCache &state(cache[iterator]);
4304 NSString *name([package name]);
4306 if (state.NewInstall())
4307 [installing addObject:name];
4308 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4309 [reinstalling addObject:name];
4310 else if (state.Upgrade())
4311 [upgrading addObject:name];
4312 else if (state.Downgrade())
4313 [downgrading addObject:name];
4314 else if (state.Delete()) {
4315 if ([package essential])
4317 [removing addObject:name];
4320 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4321 substrate_ |= DepSubstrate(iterator.CurrentVer());
4326 else if (Advanced_) {
4327 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4329 essential_ = [[UIAlertView alloc]
4330 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4331 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4333 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4334 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4337 [essential_ setContext:@"remove"];
4339 essential_ = [[UIAlertView alloc]
4340 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4341 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4343 cancelButtonTitle:UCLocalize("OKAY")
4344 otherButtonTitles:nil
4347 [essential_ setContext:@"unable"];
4350 changes_ = [[NSArray alloc] initWithObjects:
4358 issues_ = [database_ issues];
4360 issues_ = [issues_ retain];
4362 sizes_ = [[NSArray alloc] initWithObjects:
4363 SizeString([database_ fetcher].FetchNeeded()),
4364 SizeString([database_ fetcher].PartialPresent()),
4367 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4369 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4370 initWithTitle:UCLocalize("CANCEL")
4371 style:UIBarButtonItemStylePlain
4373 action:@selector(cancelButtonClicked)
4378 - (void) applyRightButton {
4379 #if !AlwaysReload && !IgnoreInstall
4380 if (issues_ == nil && ![self isLoading])
4381 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4382 initWithTitle:UCLocalize("CONFIRM")
4383 style:UIBarButtonItemStyleDone
4385 action:@selector(confirmButtonClicked)
4388 [super applyRightButton];
4390 [[self navigationItem] setRightBarButtonItem:nil];
4394 - (void) cancelButtonClicked {
4395 [self dismissModalViewControllerAnimated:YES];
4396 [delegate_ cancelAndClear:YES];
4400 - (void) confirmButtonClicked {
4404 if (essential_ != nil)
4409 [delegate_ confirmWithNavigationController:[self navigationController]];
4417 /* Progress Data {{{ */
4418 @interface ProgressData : NSObject {
4420 // XXX: should these really both be _transient?
4421 _transient id target_;
4422 _transient id object_;
4425 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4432 @implementation ProgressData
4434 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4435 if ((self = [super init]) != nil) {
4436 selector_ = selector;
4456 /* Progress Controller {{{ */
4457 @interface ProgressController : CYViewController <
4458 ConfigurationDelegate,
4461 _transient Database *database_;
4462 UIProgressBar *progress_;
4463 UITextView *output_;
4464 UITextLabel *status_;
4465 UIPushButton *close_;
4467 SHA1SumValue springlist_;
4468 SHA1SumValue notifyconf_;
4472 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4474 - (void) _retachThread;
4475 - (void) _detachNewThreadData:(ProgressData *)data;
4476 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4482 @protocol ProgressControllerDelegate
4483 - (void) progressControllerIsComplete:(ProgressController *)sender;
4486 @implementation ProgressController
4489 [database_ setDelegate:nil];
4490 [progress_ release];
4499 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4500 if ((self = [super init]) != nil) {
4501 database_ = database;
4502 [database_ setDelegate:self];
4503 delegate_ = delegate;
4505 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4507 progress_ = [[UIProgressBar alloc] init];
4508 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4509 [progress_ setStyle:0];
4511 status_ = [[UITextLabel alloc] init];
4512 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4513 [status_ setColor:[UIColor whiteColor]];
4514 [status_ setBackgroundColor:[UIColor clearColor]];
4515 [status_ setCentersHorizontally:YES];
4516 //[status_ setFont:font];
4518 output_ = [[UITextView alloc] init];
4519 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4520 //[output_ setTextFont:@"Courier New"];
4521 [output_ setFont:[[output_ font] fontWithSize:12]];
4522 [output_ setTextColor:[UIColor whiteColor]];
4523 [output_ setBackgroundColor:[UIColor clearColor]];
4524 [output_ setMarginTop:0];
4525 [output_ setAllowsRubberBanding:YES];
4526 [output_ setEditable:NO];
4527 [[self view] addSubview:output_];
4529 close_ = [[UIPushButton alloc] init];
4530 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4531 [close_ setAutosizesToFit:NO];
4532 [close_ setDrawsShadow:YES];
4533 [close_ setStretchBackground:YES];
4534 [close_ setEnabled:YES];
4535 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4536 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4537 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4538 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4542 - (void) positionViews {
4543 CGRect bounds = [[self view] bounds];
4544 CGSize prgsize = [UIProgressBar defaultSize];
4547 (bounds.size.width - prgsize.width) / 2,
4548 bounds.size.height - prgsize.height - 20
4551 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4553 [progress_ setFrame:prgrect];
4554 [status_ setFrame:CGRectMake(
4556 bounds.size.height - prgsize.height - 50,
4557 bounds.size.width - 20,
4560 [output_ setFrame:CGRectMake(
4563 bounds.size.width - 20,
4564 bounds.size.height - 96
4566 [close_ setFrame:CGRectMake(
4567 (bounds.size.width - closewidth) / 2,
4568 bounds.size.height - prgsize.height - 50,
4574 - (void) viewWillAppear:(BOOL)animated {
4575 [super viewDidAppear:animated];
4576 [[self navigationItem] setHidesBackButton:YES];
4577 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4579 [self positionViews];
4582 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4583 [self positionViews];
4586 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4587 NSString *context([alert context]);
4589 if ([context isEqualToString:@"conffile"]) {
4590 FILE *input = [database_ input];
4591 if (button == [alert cancelButtonIndex])
4592 fprintf(input, "N\n");
4593 else if (button == [alert firstOtherButtonIndex])
4594 fprintf(input, "Y\n");
4599 - (void) closeButtonPushed {
4602 UpdateExternalStatus(0);
4606 [self dismissModalViewControllerAnimated:YES];
4610 [delegate_ terminateWithSuccess];
4611 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4612 [delegate_ suspendWithAnimation:YES];
4614 [delegate_ suspend];*/
4626 system("/usr/bin/sbreload");
4632 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4633 SBReboot(SBSSpringBoardServerPort());
4635 reboot2(RB_AUTOBOOT);
4640 - (void) _retachThread {
4641 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4643 [[self view] addSubview:close_];
4644 [progress_ removeFromSuperview];
4645 [status_ removeFromSuperview];
4647 [database_ popErrorWithTitle:title_];
4648 [delegate_ progressControllerIsComplete:self];
4652 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4655 MMap mmap(file, MMap::ReadOnly);
4657 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4658 if (!(notifyconf_ == sha1.Result()))
4665 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4668 MMap mmap(file, MMap::ReadOnly);
4670 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4671 if (!(springlist_ == sha1.Result()))
4677 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4678 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4679 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4680 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4681 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4685 system("su -c /usr/bin/uicache mobile");
4688 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4690 [delegate_ setStatusBarShowsProgress:NO];
4693 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4694 [[data target] performSelector:[data selector] withObject:[data object]];
4695 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4698 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4699 UpdateExternalStatus(1);
4706 title_ = [title retain];
4708 [[self navigationItem] setTitle:title_];
4710 [status_ setText:nil];
4711 [output_ setText:@""];
4712 [progress_ setProgress:0];
4714 [close_ removeFromSuperview];
4715 [[self view] addSubview:progress_];
4716 [[self view] addSubview:status_];
4718 [delegate_ setStatusBarShowsProgress:YES];
4723 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4726 MMap mmap(file, MMap::ReadOnly);
4728 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4729 notifyconf_ = sha1.Result();
4735 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4738 MMap mmap(file, MMap::ReadOnly);
4740 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4741 springlist_ = sha1.Result();
4746 detachNewThreadSelector:@selector(_detachNewThreadData:)
4748 withObject:[[[ProgressData alloc]
4749 initWithSelector:selector
4756 - (void) repairWithSelector:(SEL)selector {
4758 detachNewThreadSelector:selector
4761 title:UCLocalize("REPAIRING")
4765 - (void) setConfigurationData:(NSString *)data {
4767 performSelectorOnMainThread:@selector(_setConfigurationData:)
4773 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4774 CYAlertView *sheet([[[CYAlertView alloc]
4776 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4777 defaultButtonIndex:0
4780 [sheet setMessage:error];
4781 [sheet yieldToPopupAlertAnimated:YES];
4785 - (void) setProgressTitle:(NSString *)title {
4787 performSelectorOnMainThread:@selector(_setProgressTitle:)
4793 - (void) setProgressPercent:(float)percent {
4795 performSelectorOnMainThread:@selector(_setProgressPercent:)
4796 withObject:[NSNumber numberWithFloat:percent]
4801 - (void) startProgress {
4804 - (void) addProgressOutput:(NSString *)output {
4806 performSelectorOnMainThread:@selector(_addProgressOutput:)
4812 - (bool) isCancelling:(size_t)received {
4816 - (void) _setConfigurationData:(NSString *)data {
4817 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4819 if (!conffile_r(data)) {
4820 lprintf("E:invalid conffile\n");
4824 NSString *ofile = conffile_r[1];
4825 //NSString *nfile = conffile_r[2];
4827 UIAlertView *alert = [[[UIAlertView alloc]
4828 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4829 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4831 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4832 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4833 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4837 [alert setContext:@"conffile"];
4841 - (void) _setProgressTitle:(NSString *)title {
4842 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4843 for (size_t i(0), e([words count]); i != e; ++i) {
4844 NSString *word([words objectAtIndex:i]);
4845 if (Package *package = [database_ packageWithName:word])
4846 [words replaceObjectAtIndex:i withObject:[package name]];
4849 [status_ setText:[words componentsJoinedByString:@" "]];
4852 - (void) _setProgressPercent:(NSNumber *)percent {
4853 [progress_ setProgress:[percent floatValue]];
4856 - (void) _addProgressOutput:(NSString *)output {
4857 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4858 CGSize size = [output_ contentSize];
4859 CGPoint offset = [output_ contentOffset];
4860 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4861 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4862 [output_ scrollRectToVisible:rect animated:YES];
4866 - (BOOL) isRunning {
4873 /* Cell Content View {{{ */
4874 @protocol ContentDelegate
4875 - (void) drawContentRect:(CGRect)rect;
4878 @interface ContentView : UIView {
4879 _transient id<ContentDelegate> delegate_;
4884 @implementation ContentView
4886 - (id) initWithFrame:(CGRect)frame {
4887 if ((self = [super initWithFrame:frame]) != nil) {
4888 [self setNeedsDisplayOnBoundsChange:YES];
4892 - (void) setDelegate:(id<ContentDelegate>)delegate {
4893 delegate_ = delegate;
4896 - (void) drawRect:(CGRect)rect {
4897 [super drawRect:rect];
4898 [delegate_ drawContentRect:rect];
4903 /* Cydia TableView Cell {{{ */
4904 @interface CYTableViewCell : UITableViewCell {
4905 ContentView *content_;
4911 @implementation CYTableViewCell
4918 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4919 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4921 if (view == content_) {
4922 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4923 highlighted_ = highlighted;
4926 [super _updateHighlightColorsForView:view highlighted:highlighted];
4929 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4930 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4931 highlighted_ = selected;
4933 [super setSelected:selected animated:animated];
4934 [content_ setNeedsDisplay];
4940 /* Package Cell {{{ */
4941 @interface PackageCell : CYTableViewCell <
4946 NSString *description_;
4954 - (PackageCell *) init;
4955 - (void) setPackage:(Package *)package;
4957 - (void) drawContentRect:(CGRect)rect;
4961 @implementation PackageCell
4963 - (void) clearPackage {
4974 if (description_ != nil) {
4975 [description_ release];
4979 if (source_ != nil) {
4984 if (badge_ != nil) {
4989 if (placard_ != nil) {
4999 [self clearPackage];
5003 - (PackageCell *) init {
5004 CGRect frame(CGRectMake(0, 0, 320, 74));
5005 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5006 UIView *content([self contentView]);
5007 CGRect bounds([content bounds]);
5009 content_ = [[ContentView alloc] initWithFrame:bounds];
5010 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5011 [content addSubview:content_];
5013 [content_ setDelegate:self];
5014 [content_ setOpaque:YES];
5018 - (NSString *) accessibilityLabel {
5019 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5022 - (void) setPackage:(Package *)package {
5023 [self clearPackage];
5026 Source *source = [package source];
5028 icon_ = [[package icon] retain];
5029 name_ = [[package name] retain];
5032 description_ = [package longDescription];
5033 if (description_ == nil)
5034 description_ = [package shortDescription];
5035 if (description_ != nil)
5036 description_ = [description_ retain];
5038 commercial_ = [package isCommercial];
5040 package_ = [package retain];
5042 NSString *label = nil;
5043 bool trusted = false;
5045 if (source != nil) {
5046 label = [source label];
5047 trusted = [source trusted];
5048 } else if ([[package id] isEqualToString:@"firmware"])
5049 label = UCLocalize("APPLE");
5051 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5053 NSString *from(label);
5055 NSString *section = [package simpleSection];
5056 if (section != nil && ![section isEqualToString:label]) {
5057 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5058 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5061 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5062 source_ = [from retain];
5064 if (NSString *purpose = [package primaryPurpose])
5065 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5066 badge_ = [badge_ retain];
5071 if (NSString *mode = [package_ mode]) {
5072 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5073 color = RemovingColor_;
5074 //placard = @"removing";
5076 color = InstallingColor_;
5077 //placard = @"installing";
5080 // XXX: the removing/installing placards are not @2x
5083 color = [UIColor whiteColor];
5085 if ([package installed] != nil)
5086 placard = @"installed";
5091 [content_ setBackgroundColor:color];
5094 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5095 placard_ = [placard_ retain];
5097 [self setNeedsDisplay];
5098 [content_ setNeedsDisplay];
5101 - (void) drawContentRect:(CGRect)rect {
5102 bool highlighted(highlighted_);
5103 float width([self bounds].size.width);
5106 CGContextRef context(UIGraphicsGetCurrentContext());
5107 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5108 CGContextFillRect(context, rect);
5113 rect.size = [icon_ size];
5115 rect.size.width /= 2;
5116 rect.size.height /= 2;
5118 rect.origin.x = 25 - rect.size.width / 2;
5119 rect.origin.y = 25 - rect.size.height / 2;
5121 [icon_ drawInRect:rect];
5124 if (badge_ != nil) {
5126 rect.size = [badge_ size];
5128 rect.size.width /= 2;
5129 rect.size.height /= 2;
5131 rect.origin.x = 36 - rect.size.width / 2;
5132 rect.origin.y = 36 - rect.size.height / 2;
5134 [badge_ drawInRect:rect];
5141 UISetColor(commercial_ ? Purple_ : Black_);
5142 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5143 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5146 UISetColor(commercial_ ? Purplish_ : Gray_);
5147 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5149 if (placard_ != nil)
5150 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5155 /* Section Cell {{{ */
5156 @interface SectionCell : CYTableViewCell <
5168 - (void) setSection:(Section *)section editing:(BOOL)editing;
5172 @implementation SectionCell
5174 - (void) clearSection {
5175 if (basic_ != nil) {
5180 if (section_ != nil) {
5190 if (count_ != nil) {
5197 [self clearSection];
5203 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5204 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5205 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5206 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5207 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5209 UIView *content([self contentView]);
5210 CGRect bounds([content bounds]);
5212 content_ = [[ContentView alloc] initWithFrame:bounds];
5213 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5214 [content addSubview:content_];
5215 [content_ setBackgroundColor:[UIColor whiteColor]];
5217 [content_ setDelegate:self];
5221 - (void) onSwitch:(id)sender {
5222 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5223 if (metadata == nil) {
5224 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5225 [Sections_ setObject:metadata forKey:basic_];
5228 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5232 - (void) setSection:(Section *)section editing:(BOOL)editing {
5233 if (editing != editing_) {
5235 [switch_ removeFromSuperview];
5237 [self addSubview:switch_];
5241 [self clearSection];
5243 if (section == nil) {
5244 name_ = [UCLocalize("ALL_PACKAGES") retain];
5247 basic_ = [section name];
5249 basic_ = [basic_ retain];
5251 section_ = [section localized];
5252 if (section_ != nil)
5253 section_ = [section_ retain];
5255 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5256 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5259 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5262 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5263 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5265 [content_ setNeedsDisplay];
5268 - (void) setFrame:(CGRect)frame {
5269 [super setFrame:frame];
5271 CGRect rect([switch_ frame]);
5272 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5275 - (NSString *) accessibilityLabel {
5279 - (void) drawContentRect:(CGRect)rect {
5280 bool highlighted(highlighted_ && !editing_);
5282 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5287 float width(rect.size.width);
5293 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5295 CGSize size = [count_ sizeWithFont:Font14_];
5299 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5305 /* File Table {{{ */
5306 @interface FileTable : CYViewController <
5307 UITableViewDataSource,
5310 _transient Database *database_;
5313 NSMutableArray *files_;
5317 - (id) initWithDatabase:(Database *)database;
5318 - (void) setPackage:(Package *)package;
5322 @implementation FileTable
5325 [self releaseSubviews];
5334 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5335 return files_ == nil ? 0 : [files_ count];
5338 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5342 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5343 static NSString *reuseIdentifier = @"Cell";
5345 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5347 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5348 [cell setFont:[UIFont systemFontOfSize:16]];
5350 [cell setText:[files_ objectAtIndex:indexPath.row]];
5351 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5356 - (NSURL *) navigationURL {
5357 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5361 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5363 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5364 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5365 [list_ setRowHeight:24.0f];
5366 [list_ setDataSource:self];
5367 [list_ setDelegate:self];
5368 [[self view] addSubview:list_];
5371 - (void) viewDidLoad {
5372 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5375 - (void) releaseSubviews {
5380 - (id) initWithDatabase:(Database *)database {
5381 if ((self = [super init]) != nil) {
5382 database_ = database;
5384 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5388 - (void) setPackage:(Package *)package {
5389 if (package_ != nil) {
5390 [package_ autorelease];
5399 [files_ removeAllObjects];
5401 if (package != nil) {
5402 package_ = [package retain];
5403 name_ = [[package id] retain];
5405 if (NSArray *files = [package files])
5406 [files_ addObjectsFromArray:files];
5408 if ([files_ count] != 0) {
5409 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5410 [files_ removeObjectAtIndex:0];
5411 [files_ sortUsingSelector:@selector(compareByPath:)];
5413 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5414 [stack addObject:@"/"];
5416 for (int i(0), e([files_ count]); i != e; ++i) {
5417 NSString *file = [files_ objectAtIndex:i];
5418 while (![file hasPrefix:[stack lastObject]])
5419 [stack removeLastObject];
5420 NSString *directory = [stack lastObject];
5421 [stack addObject:[file stringByAppendingString:@"/"]];
5422 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5423 ([stack count] - 2) * 3, "",
5424 [file substringFromIndex:[directory length]]
5433 - (void) reloadData {
5436 [self setPackage:[database_ packageWithName:name_]];
5441 /* Package Controller {{{ */
5442 @interface CYPackageController : CYBrowserController <
5443 UIActionSheetDelegate
5445 _transient Database *database_;
5449 NSMutableArray *buttons_;
5450 UIBarButtonItem *button_;
5453 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5457 @implementation CYPackageController
5460 if (package_ != nil)
5473 - (NSURL *) navigationURL {
5474 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", [package_ id]]];
5477 /* XXX: this is not safe at all... localization of /fail/ */
5478 - (void) _clickButtonWithName:(NSString *)name {
5479 if ([name isEqualToString:UCLocalize("CLEAR")])
5480 [delegate_ clearPackage:package_];
5481 else if ([name isEqualToString:UCLocalize("INSTALL")])
5482 [delegate_ installPackage:package_];
5483 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5484 [delegate_ installPackage:package_];
5485 else if ([name isEqualToString:UCLocalize("REMOVE")])
5486 [delegate_ removePackage:package_];
5487 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5488 [delegate_ installPackage:package_];
5489 else _assert(false);
5492 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5493 NSString *context([sheet context]);
5495 if ([context isEqualToString:@"modify"]) {
5496 if (button != [sheet cancelButtonIndex]) {
5497 NSString *buttonName = [buttons_ objectAtIndex:button];
5498 [self _clickButtonWithName:buttonName];
5501 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5505 - (bool) _allowJavaScriptPanel {
5510 - (void) _customButtonClicked {
5511 int count([buttons_ count]);
5516 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5518 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5519 [buttons addObjectsFromArray:buttons_];
5521 UIActionSheet *sheet = [[[UIActionSheet alloc]
5524 cancelButtonTitle:nil
5525 destructiveButtonTitle:nil
5526 otherButtonTitles:nil
5529 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5531 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5532 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5534 [sheet setContext:@"modify"];
5536 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5540 // We don't want to allow non-commercial packages to do custom things to the install button,
5541 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5542 - (void) customButtonClicked {
5544 [super customButtonClicked];
5546 [self _customButtonClicked];
5549 - (void) reloadButtonClicked {
5550 // Don't reload a commerical package by tapping the loading button,
5551 // but if it's not an Install button, we should forward it on.
5552 if (![package_ uninstalled])
5553 [self _customButtonClicked];
5556 - (void) applyLoadingTitle {
5557 // Don't show "Loading" as the title. Ever.
5560 - (UIBarButtonItem *) rightButton {
5565 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5566 if ((self = [super init]) != nil) {
5567 database_ = database;
5568 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5569 name_ = [[NSString alloc] initWithString:name];
5573 - (void) reloadData {
5576 if (package_ != nil)
5577 [package_ autorelease];
5578 package_ = [database_ packageWithName:name_];
5580 [buttons_ removeAllObjects];
5582 if (package_ != nil) {
5585 package_ = [package_ retain];
5586 commercial_ = [package_ isCommercial];
5588 if ([package_ mode] != nil)
5589 [buttons_ addObject:UCLocalize("CLEAR")];
5590 if ([package_ source] == nil);
5591 else if ([package_ upgradableAndEssential:NO])
5592 [buttons_ addObject:UCLocalize("UPGRADE")];
5593 else if ([package_ uninstalled])
5594 [buttons_ addObject:UCLocalize("INSTALL")];
5596 [buttons_ addObject:UCLocalize("REINSTALL")];
5597 if (![package_ uninstalled])
5598 [buttons_ addObject:UCLocalize("REMOVE")];
5605 switch ([buttons_ count]) {
5606 case 0: title = nil; break;
5607 case 1: title = [buttons_ objectAtIndex:0]; break;
5608 default: title = UCLocalize("MODIFY"); break;
5611 button_ = [[UIBarButtonItem alloc]
5613 style:UIBarButtonItemStylePlain
5615 action:@selector(customButtonClicked)
5618 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5621 - (bool) isLoading {
5622 return commercial_ ? [super isLoading] : false;
5628 /* Package List Controller {{{ */
5629 @interface PackageListController : CYViewController <
5630 UITableViewDataSource,
5633 _transient Database *database_;
5635 NSMutableArray *packages_;
5636 NSMutableArray *sections_;
5638 NSMutableArray *index_;
5639 NSMutableDictionary *indices_;
5643 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5644 - (void) setDelegate:(id)delegate;
5645 - (void) resetCursor;
5649 @implementation PackageListController
5652 [packages_ release];
5653 [sections_ release];
5662 - (void) deselectWithAnimation:(BOOL)animated {
5663 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5666 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5667 CGRect base = [[self view] bounds];
5668 base.size.height -= bounds.size.height;
5669 base.origin = [list_ frame].origin;
5671 [UIView beginAnimations:nil context:NULL];
5672 [UIView setAnimationBeginsFromCurrentState:YES];
5673 [UIView setAnimationCurve:curve];
5674 [UIView setAnimationDuration:duration];
5675 [list_ setFrame:base];
5676 [UIView commitAnimations];
5679 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5680 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5683 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5684 [self resizeForKeyboardBounds:bounds duration:0];
5687 - (void) keyboardWillShow:(NSNotification *)notification {
5690 NSTimeInterval duration;
5691 UIViewAnimationCurve curve;
5692 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5693 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5694 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5695 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5697 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);
5698 UIViewController *base = self;
5699 while ([base parentViewController] != nil)
5700 base = [base parentViewController];
5701 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5702 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5704 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5707 - (void) keyboardWillHide:(NSNotification *)notification {
5708 NSTimeInterval duration;
5709 UIViewAnimationCurve curve;
5710 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5711 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5713 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5716 - (void) viewWillAppear:(BOOL)animated {
5717 [super viewWillAppear:animated];
5719 [self resizeForKeyboardBounds:CGRectZero];
5720 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5721 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5724 - (void) viewWillDisappear:(BOOL)animated {
5725 [super viewWillDisappear:animated];
5727 [self resizeForKeyboardBounds:CGRectZero];
5728 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5729 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5732 - (void) viewDidAppear:(BOOL)animated {
5733 [super viewDidAppear:animated];
5734 [self deselectWithAnimation:animated];
5737 - (void) didSelectPackage:(Package *)package {
5738 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5739 [view setDelegate:delegate_];
5740 [[self navigationController] pushViewController:view animated:YES];
5743 #if TryIndexedCollation
5744 + (BOOL) hasIndexedCollation {
5745 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5749 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5750 NSInteger count([sections_ count]);
5751 return count == 0 ? 1 : count;
5754 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5755 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5757 return [[sections_ objectAtIndex:section] name];
5760 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5761 if ([sections_ count] == 0)
5763 return [[sections_ objectAtIndex:section] count];
5766 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5767 @synchronized (database_) {
5768 if ([database_ era] != era_)
5771 Section *section([sections_ objectAtIndex:[path section]]);
5772 NSInteger row([path row]);
5773 Package *package([packages_ objectAtIndex:([section row] + row)]);
5774 return [[package retain] autorelease];
5777 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5778 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5780 cell = [[[PackageCell alloc] init] autorelease];
5781 [cell setPackage:[self packageAtIndexPath:path]];
5785 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5786 Package *package([self packageAtIndexPath:path]);
5787 package = [database_ packageWithName:[package id]];
5788 [self didSelectPackage:package];
5791 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5792 // XXX: is 20 the most optimal number here?
5793 return [packages_ count] > 20 ? index_ : nil;
5796 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5797 #if TryIndexedCollation
5798 if ([[self class] hasIndexedCollation]) {
5799 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5806 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5807 if ((self = [super init]) != nil) {
5808 database_ = database;
5809 title_ = [title copy];
5810 [[self navigationItem] setTitle:title_];
5812 #if TryIndexedCollation
5813 if ([[self class] hasIndexedCollation])
5814 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
5817 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5819 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5821 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5822 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5824 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
5825 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5826 [list_ setRowHeight:73];
5827 [[self view] addSubview:list_];
5829 [list_ setDataSource:self];
5830 [list_ setDelegate:self];
5834 - (void) setDelegate:(id)delegate {
5835 delegate_ = delegate;
5838 - (bool) hasPackage:(Package *)package {
5842 - (void) reloadData {
5845 era_ = [database_ era];
5846 NSArray *packages = [database_ packages];
5848 [packages_ removeAllObjects];
5849 [sections_ removeAllObjects];
5851 _profile(PackageTable$reloadData$Filter)
5852 for (Package *package in packages)
5853 if ([self hasPackage:package])
5854 [packages_ addObject:package];
5857 [indices_ removeAllObjects];
5859 Section *section = nil;
5861 #if TryIndexedCollation
5862 if ([[self class] hasIndexedCollation]) {
5863 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5864 NSArray *titles = [collation sectionIndexTitles];
5867 _profile(PackageTable$reloadData$Section)
5868 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5872 _profile(PackageTable$reloadData$Section$Package)
5873 package = [packages_ objectAtIndex:offset];
5874 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5877 while (secidx < index) {
5880 _profile(PackageTable$reloadData$Section$Allocate)
5881 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5884 _profile(PackageTable$reloadData$Section$Add)
5885 [sections_ addObject:section];
5889 [section addToCount];
5895 [index_ removeAllObjects];
5897 _profile(PackageTable$reloadData$Section)
5898 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5902 _profile(PackageTable$reloadData$Section$Package)
5903 package = [packages_ objectAtIndex:offset];
5904 index = [package index];
5907 if (section == nil || [section index] != index) {
5908 _profile(PackageTable$reloadData$Section$Allocate)
5909 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5912 [index_ addObject:[section name]];
5913 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5915 _profile(PackageTable$reloadData$Section$Add)
5916 [sections_ addObject:section];
5920 [section addToCount];
5925 _profile(PackageTable$reloadData$List)
5930 - (void) resetCursor {
5931 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5936 /* Filtered Package List Controller {{{ */
5937 @interface FilteredPackageListController : PackageListController {
5943 - (void) setObject:(id)object;
5944 - (void) setObject:(id)object forFilter:(SEL)filter;
5946 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5950 @implementation FilteredPackageListController
5958 - (void) setFilter:(SEL)filter {
5961 /* XXX: this is an unsafe optimization of doomy hell */
5962 Method method(class_getInstanceMethod([Package class], filter));
5963 _assert(method != NULL);
5964 imp_ = method_getImplementation(method);
5965 _assert(imp_ != NULL);
5968 - (void) setObject:(id)object {
5974 object_ = [object retain];
5977 - (void) setObject:(id)object forFilter:(SEL)filter {
5978 [self setFilter:filter];
5979 [self setObject:object];
5982 - (bool) hasPackage:(Package *)package {
5983 _profile(FilteredPackageTable$hasPackage)
5984 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5988 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5989 if ((self = [super initWithDatabase:database title:title]) != nil) {
5990 [self setFilter:filter];
5991 [self setObject:object];
5999 /* Home Controller {{{ */
6000 @interface HomeController : CYBrowserController {
6004 @implementation HomeController
6006 + (BOOL) shouldHideNavigationBar {
6010 - (NSURL *) navigationURL {
6011 return [NSURL URLWithString:@"cydia://home"];
6014 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6015 [super _setMoreHeaders:request];
6018 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6019 if (UniqueID_ != nil)
6020 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6022 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6025 - (void) aboutButtonClicked {
6026 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6028 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6029 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6030 [alert setCancelButtonIndex:0];
6033 @"Copyright (C) 2008-2011\n"
6034 "Jay Freeman (saurik)\n"
6035 "saurik@saurik.com\n"
6036 "http://www.saurik.com/"
6042 - (void) viewWillDisappear:(BOOL)animated {
6043 [super viewWillDisappear:animated];
6045 if ([[self class] shouldHideNavigationBar])
6046 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6049 - (void) viewWillAppear:(BOOL)animated {
6050 if (![self hasLoaded])
6051 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6053 [super viewWillAppear:animated];
6055 if ([[self class] shouldHideNavigationBar])
6056 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6059 - (void) viewDidLoad {
6060 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6061 initWithTitle:UCLocalize("ABOUT")
6062 style:UIBarButtonItemStylePlain
6064 action:@selector(aboutButtonClicked)
6070 /* Manage Controller {{{ */
6071 @interface ManageController : CYBrowserController {
6074 - (void) queueStatusDidChange;
6077 @implementation ManageController
6079 - (NSURL *) navigationURL {
6080 return [NSURL URLWithString:@"cydia://manage"];
6083 - (void) viewWillAppear:(BOOL)animated {
6084 if (![self hasLoaded])
6085 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6087 [super viewWillAppear:animated];
6090 - (void) viewDidLoad {
6091 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6093 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6094 initWithTitle:UCLocalize("SETTINGS")
6095 style:UIBarButtonItemStylePlain
6097 action:@selector(settingsButtonClicked)
6100 [self queueStatusDidChange];
6103 - (void) settingsButtonClicked {
6104 [delegate_ showSettings];
6108 - (void) queueButtonClicked {
6112 - (void) applyLoadingTitle {
6113 // Disable "Loading" title.
6116 - (void) applyRightButton {
6117 // Disable right button.
6121 - (void) queueStatusDidChange {
6123 if (!IsWildcat_ && Queuing_) {
6124 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6125 initWithTitle:UCLocalize("QUEUE")
6126 style:UIBarButtonItemStyleDone
6128 action:@selector(queueButtonClicked)
6131 [[self navigationItem] setRightBarButtonItem:nil];
6136 - (bool) isLoading {
6137 // Never show as loading.
6144 /* Refresh Bar {{{ */
6145 @interface RefreshBar : UINavigationBar {
6146 UIProgressIndicator *indicator_;
6147 UITextLabel *prompt_;
6148 UIProgressBar *progress_;
6149 UINavigationButton *cancel_;
6154 @implementation RefreshBar
6157 [indicator_ release];
6159 [progress_ release];
6164 - (void) positionViews {
6165 CGRect frame = [cancel_ frame];
6166 frame.size = [cancel_ sizeThatFits:frame.size];
6167 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6168 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6169 [cancel_ setFrame:frame];
6171 CGSize prgsize = {75, 100};
6173 [self frame].size.width - prgsize.width - 10,
6174 ([self frame].size.height - prgsize.height) / 2
6176 [progress_ setFrame:prgrect];
6178 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6179 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6180 CGRect indrect = {{indoffset, indoffset}, indsize};
6181 [indicator_ setFrame:indrect];
6183 CGSize prmsize = {215, indsize.height + 4};
6185 indoffset * 2 + indsize.width,
6186 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6188 [prompt_ setFrame:prmrect];
6191 - (void)setFrame:(CGRect)frame {
6192 [super setFrame:frame];
6194 [self positionViews];
6197 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6198 if ((self = [super initWithFrame:frame])) {
6199 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6201 [self setBarStyle:UIBarStyleBlack];
6203 UIBarStyle barstyle([self _barStyle:NO]);
6204 bool ugly(barstyle == UIBarStyleDefault);
6206 UIProgressIndicatorStyle style = ugly ?
6207 UIProgressIndicatorStyleMediumBrown :
6208 UIProgressIndicatorStyleMediumWhite;
6210 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6211 [indicator_ setStyle:style];
6212 [indicator_ startAnimation];
6213 [self addSubview:indicator_];
6215 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6216 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6217 [prompt_ setBackgroundColor:[UIColor clearColor]];
6218 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6219 [self addSubview:prompt_];
6221 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6222 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6223 [progress_ setStyle:0];
6224 [self addSubview:progress_];
6226 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6227 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6228 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6229 [cancel_ setBarStyle:barstyle];
6231 [self positionViews];
6236 [cancel_ removeFromSuperview];
6240 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6241 [progress_ setProgress:0];
6242 [self addSubview:cancel_];
6246 [cancel_ removeFromSuperview];
6249 - (void) setPrompt:(NSString *)prompt {
6250 [prompt_ setText:prompt];
6253 - (void) setProgress:(float)progress {
6254 [progress_ setProgress:progress];
6260 @class CYNavigationController;
6262 /* Cydia Tab Bar Controller {{{ */
6263 @interface CYTabBarController : UITabBarController <
6264 UITabBarControllerDelegate,
6267 _transient Database *database_;
6268 RefreshBar *refreshbar_;
6272 // XXX: ok, "updatedelegate_"?...
6273 _transient NSObject<CydiaDelegate> *updatedelegate_;
6276 UIViewController *remembered_;
6277 _transient UIViewController *transient_;
6280 - (NSArray *) navigationURLCollection;
6281 - (void) dropBar:(BOOL)animated;
6282 - (void) beginUpdate;
6283 - (void) raiseBar:(BOOL)animated;
6288 @implementation CYTabBarController
6290 - (void) setUnselectedViewController:(UIViewController *)transient {
6291 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6292 if (transient != nil) {
6293 if (transient_ == nil)
6294 remembered_ = [[controllers objectAtIndex:0] retain];
6295 transient_ = transient;
6296 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6297 [controllers replaceObjectAtIndex:0 withObject:transient_];
6298 [self setSelectedIndex:0];
6299 [self setViewControllers:controllers];
6300 [self concealTabBarSelection];
6301 } else if (remembered_ != nil) {
6302 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6303 transient_ = transient;
6304 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6305 [remembered_ release];
6307 [self setViewControllers:controllers];
6308 [self revealTabBarSelection];
6312 - (UIViewController *) unselectedViewController {
6316 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6317 if ([self unselectedViewController])
6318 [self setUnselectedViewController:nil];
6321 - (NSArray *) navigationURLCollection {
6322 NSMutableArray *items([NSMutableArray array]);
6324 // XXX: Should this deal with transient view controllers?
6325 for (id navigation in [self viewControllers]) {
6326 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6328 [items addObject:stack];
6334 - (void) reloadData {
6335 for (CYViewController *controller in [self viewControllers])
6336 [controller reloadData];
6338 [(CYNavigationController *)[self unselectedViewController] reloadData];
6342 [refreshbar_ release];
6343 [[NSNotificationCenter defaultCenter] removeObserver:self];
6348 - (id) initWithDatabase:(Database *)database {
6349 if ((self = [super init]) != nil) {
6350 database_ = database;
6351 [self setDelegate:self];
6353 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6354 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6356 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6360 - (void) setUpdate:(NSDate *)date {
6364 - (void) beginUpdate {
6365 [refreshbar_ start];
6368 [updatedelegate_ retainNetworkActivityIndicator];
6372 detachNewThreadSelector:@selector(performUpdate)
6378 - (void) performUpdate { _pooled
6380 status.setDelegate(self);
6381 [database_ updateWithStatus:status];
6384 performSelectorOnMainThread:@selector(completeUpdate)
6390 - (void) stopUpdateWithSelector:(SEL)selector {
6392 [updatedelegate_ releaseNetworkActivityIndicator];
6394 [self raiseBar:YES];
6397 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6400 - (void) completeUpdate {
6403 [self stopUpdateWithSelector:@selector(reloadData)];
6406 - (void) cancelUpdate {
6407 [self stopUpdateWithSelector:@selector(updateData)];
6410 - (void) cancelPressed {
6411 [self cancelUpdate];
6418 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6419 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6422 - (void) startProgress {
6425 - (void) setProgressTitle:(NSString *)title {
6427 performSelectorOnMainThread:@selector(_setProgressTitle:)
6433 - (bool) isCancelling:(size_t)received {
6437 - (void) setProgressPercent:(float)percent {
6439 performSelectorOnMainThread:@selector(_setProgressPercent:)
6440 withObject:[NSNumber numberWithFloat:percent]
6445 - (void) addProgressOutput:(NSString *)output {
6447 performSelectorOnMainThread:@selector(_addProgressOutput:)
6453 - (void) _setProgressTitle:(NSString *)title {
6454 [refreshbar_ setPrompt:title];
6457 - (void) _setProgressPercent:(NSNumber *)percent {
6458 [refreshbar_ setProgress:[percent floatValue]];
6461 - (void) _addProgressOutput:(NSString *)output {
6464 - (void) setUpdateDelegate:(id)delegate {
6465 updatedelegate_ = delegate;
6468 - (CGFloat) statusBarHeight {
6469 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6470 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6472 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6476 - (UIView *) transitionView {
6477 if ([self respondsToSelector:@selector(_transitionView)])
6478 return [self _transitionView];
6480 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6483 - (void) dropBar:(BOOL)animated {
6488 UIView *transition([self transitionView]);
6489 [[self view] addSubview:refreshbar_];
6491 CGRect barframe([refreshbar_ frame]);
6493 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6494 barframe.origin.y = [self statusBarHeight];
6496 barframe.origin.y = 0;
6498 [refreshbar_ setFrame:barframe];
6501 [UIView beginAnimations:nil context:NULL];
6503 CGRect viewframe = [transition frame];
6504 viewframe.origin.y += barframe.size.height;
6505 viewframe.size.height -= barframe.size.height;
6506 [transition setFrame:viewframe];
6509 [UIView commitAnimations];
6511 // Ensure bar has the proper width for our view, it might have changed
6512 barframe.size.width = viewframe.size.width;
6513 [refreshbar_ setFrame:barframe];
6515 // XXX: fix Apple's layout bug
6516 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6519 - (void) raiseBar:(BOOL)animated {
6524 UIView *transition([self transitionView]);
6525 [refreshbar_ removeFromSuperview];
6527 CGRect barframe([refreshbar_ frame]);
6530 [UIView beginAnimations:nil context:NULL];
6532 CGRect viewframe = [transition frame];
6533 viewframe.origin.y -= barframe.size.height;
6534 viewframe.size.height += barframe.size.height;
6535 [transition setFrame:viewframe];
6538 [UIView commitAnimations];
6540 // XXX: fix Apple's layout bug
6541 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6545 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6546 // XXX: fix Apple's layout bug
6547 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6551 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6552 bool dropped(dropped_);
6557 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6562 // XXX: fix Apple's layout bug
6563 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6566 - (void) statusBarFrameChanged:(NSNotification *)notification {
6575 /* Cydia Navigation Controller {{{ */
6576 @interface CYNavigationController : UINavigationController {
6577 _transient Database *database_;
6578 _transient id<UINavigationControllerDelegate> delegate_;
6581 - (NSArray *) navigationURLCollection;
6582 - (id) initWithDatabase:(Database *)database;
6583 - (void) reloadData;
6588 @implementation CYNavigationController
6590 - (NSArray *) navigationURLCollection {
6591 NSMutableArray *stack([NSMutableArray array]);
6593 for (CYViewController *controller in [self viewControllers]) {
6594 NSString *url = [[controller navigationURL] absoluteString];
6596 [stack addObject:url];
6602 - (void) reloadData {
6603 for (CYViewController *page in [self viewControllers]) {
6604 // Only reload controllers that have already loaded.
6605 // This prevents a page from accidentally loading too
6606 // early if it hasn't been shown on the screen yet.
6607 if ([page hasLoaded])
6612 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6613 delegate_ = delegate;
6616 - (id) initWithDatabase:(Database *)database {
6617 if ((self = [super init]) != nil) {
6618 database_ = database;
6625 /* Cydia:// Protocol {{{ */
6626 @interface CydiaURLProtocol : NSURLProtocol {
6631 @implementation CydiaURLProtocol
6633 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6634 NSURL *url([request URL]);
6637 NSString *scheme([[url scheme] lowercaseString]);
6638 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6643 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6647 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6648 id<NSURLProtocolClient> client([self client]);
6650 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6652 NSData *data(UIImagePNGRepresentation(icon));
6654 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6655 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6656 [client URLProtocol:self didLoadData:data];
6657 [client URLProtocolDidFinishLoading:self];
6661 - (void) startLoading {
6662 id<NSURLProtocolClient> client([self client]);
6663 NSURLRequest *request([self request]);
6665 NSURL *url([request URL]);
6666 NSString *href([url absoluteString]);
6668 NSString *path([href substringFromIndex:8]);
6669 NSRange slash([path rangeOfString:@"/"]);
6672 if (slash.location == NSNotFound) {
6676 command = [path substringToIndex:slash.location];
6677 path = [path substringFromIndex:(slash.location + 1)];
6680 Database *database([Database sharedInstance]);
6682 if ([command isEqualToString:@"package-icon"]) {
6685 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6686 Package *package([database packageWithName:path]);
6689 UIImage *icon([package icon]);
6690 [self _returnPNGWithImage:icon forRequest:request];
6691 } else if ([command isEqualToString:@"source-icon"]) {
6694 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6695 NSString *source(Simplify(path));
6696 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6698 icon = [UIImage applicationImageNamed:@"unknown.png"];
6699 [self _returnPNGWithImage:icon forRequest:request];
6700 } else if ([command isEqualToString:@"uikit-image"]) {
6703 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6704 UIImage *icon(_UIImageWithName(path));
6705 [self _returnPNGWithImage:icon forRequest:request];
6706 } else if ([command isEqualToString:@"section-icon"]) {
6709 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6710 NSString *section(Simplify(path));
6711 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6713 icon = [UIImage applicationImageNamed:@"unknown.png"];
6714 [self _returnPNGWithImage:icon forRequest:request];
6716 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6720 - (void) stopLoading {
6726 /* Section Controller {{{ */
6727 @interface SectionController : FilteredPackageListController {
6731 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6735 @implementation SectionController
6737 - (NSURL *) navigationURL {
6738 NSString *name = section_;
6742 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6745 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6748 title = UCLocalize("ALL_PACKAGES");
6749 else if (![name isEqual:@""])
6750 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6752 title = UCLocalize("NO_SECTION");
6754 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6761 /* Sections Controller {{{ */
6762 @interface SectionsController : CYViewController <
6763 UITableViewDataSource,
6766 _transient Database *database_;
6767 NSMutableArray *sections_;
6768 NSMutableArray *filtered_;
6773 - (id) initWithDatabase:(Database *)database;
6774 - (void) editButtonClicked;
6778 @implementation SectionsController
6781 [self releaseSubviews];
6782 [sections_ release];
6783 [filtered_ release];
6788 - (NSURL *) navigationURL {
6789 return [NSURL URLWithString:@"cydia://sections"];
6792 - (void) updateNavigationItem {
6793 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6794 if ([sections_ count] == 0) {
6795 [[self navigationItem] setRightBarButtonItem:nil];
6797 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6798 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6800 action:@selector(editButtonClicked)
6801 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6805 - (BOOL) isEditing {
6809 - (void) setEditing:(BOOL)editing {
6810 if ((editing_ = editing))
6813 [delegate_ updateData];
6815 [self updateNavigationItem];
6818 - (void) viewDidAppear:(BOOL)animated {
6819 [super viewDidAppear:animated];
6820 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6823 - (void) viewWillDisappear:(BOOL)animated {
6824 [super viewWillDisappear:animated];
6825 if (editing_) [self setEditing:NO];
6828 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6829 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6833 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6834 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6837 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6841 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6842 static NSString *reuseIdentifier = @"SectionCell";
6844 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6846 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6848 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6853 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6857 Section *section = [self sectionAtIndexPath:indexPath];
6859 SectionController *controller = [[[SectionController alloc]
6860 initWithDatabase:database_
6861 section:[section name]
6863 [controller setDelegate:delegate_];
6865 [[self navigationController] pushViewController:controller animated:YES];
6869 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6871 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6872 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6873 [list_ setRowHeight:45.0f];
6874 [list_ setDataSource:self];
6875 [list_ setDelegate:self];
6876 [[self view] addSubview:list_];
6879 - (void) viewDidLoad {
6880 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6883 - (void) releaseSubviews {
6888 - (id) initWithDatabase:(Database *)database {
6889 if ((self = [super init]) != nil) {
6890 database_ = database;
6892 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6893 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6897 - (void) reloadData {
6900 NSArray *packages = [database_ packages];
6902 [sections_ removeAllObjects];
6903 [filtered_ removeAllObjects];
6905 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6908 for (Package *package in packages) {
6909 NSString *name([package section]);
6910 NSString *key(name == nil ? @"" : name);
6914 _profile(SectionsView$reloadData$Section)
6915 section = [sections objectForKey:key];
6916 if (section == nil) {
6917 _profile(SectionsView$reloadData$Section$Allocate)
6918 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
6919 [sections setObject:section forKey:key];
6924 [section addToCount];
6926 _profile(SectionsView$reloadData$Filter)
6927 if (![package valid] || ![package visible])
6935 [sections_ addObjectsFromArray:[sections allValues]];
6937 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6939 for (Section *section in sections_) {
6940 size_t count([section row]);
6944 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6945 [section setCount:count];
6946 [filtered_ addObject:section];
6949 [self updateNavigationItem];
6954 - (void)editButtonClicked {
6955 [self setEditing:!editing_];
6961 /* Changes Controller {{{ */
6962 @interface ChangesController : CYViewController <
6963 UITableViewDataSource,
6966 _transient Database *database_;
6968 CFMutableArrayRef packages_;
6969 NSMutableArray *sections_;
6972 BOOL hasSentFirstLoad_;
6975 - (id) initWithDatabase:(Database *)database;
6979 @implementation ChangesController
6982 [self releaseSubviews];
6983 CFRelease(packages_);
6984 [sections_ release];
6989 - (NSURL *) navigationURL {
6990 return [NSURL URLWithString:@"cydia://changes"];
6993 - (void) viewWillAppear:(BOOL)animated {
6994 // Loads after it appears, so don't load beforehand.
6996 [super viewWillAppear:animated];
6999 - (void) viewDidAppear:(BOOL)animated {
7000 [super viewDidAppear:animated];
7002 if (!hasSentFirstLoad_) {
7003 hasSentFirstLoad_ = YES;
7004 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7006 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7010 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7011 NSInteger count([sections_ count]);
7012 return count == 0 ? 1 : count;
7015 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7016 if ([sections_ count] == 0)
7018 return [[sections_ objectAtIndex:section] name];
7021 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7022 if ([sections_ count] == 0)
7024 return [[sections_ objectAtIndex:section] count];
7027 - (Package *) packageAtIndex:(NSUInteger)index {
7028 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7031 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7032 @synchronized (database_) {
7033 if ([database_ era] != era_)
7036 NSUInteger sectionIndex([path section]);
7037 if (sectionIndex >= [sections_ count])
7039 Section *section([sections_ objectAtIndex:sectionIndex]);
7040 NSInteger row([path row]);
7041 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7044 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7045 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7047 cell = [[[PackageCell alloc] init] autorelease];
7048 [cell setPackage:[self packageAtIndexPath:path]];
7052 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7053 Package *package([self packageAtIndexPath:path]);
7054 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7055 [view setDelegate:delegate_];
7056 [[self navigationController] pushViewController:view animated:YES];
7060 - (void) refreshButtonClicked {
7061 [delegate_ beginUpdate];
7062 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7065 - (void) upgradeButtonClicked {
7066 [delegate_ distUpgrade];
7070 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7072 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7073 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7074 [list_ setRowHeight:73];
7075 [list_ setDataSource:self];
7076 [list_ setDelegate:self];
7077 [[self view] addSubview:list_];
7080 - (void) viewDidLoad {
7081 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7084 - (void) releaseSubviews {
7089 - (id) initWithDatabase:(Database *)database {
7090 if ((self = [super init]) != nil) {
7091 database_ = database;
7093 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7094 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7098 - (void) _reloadPackages:(NSArray *)packages {
7099 CFRelease(packages_);
7100 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7103 _profile(ChangesController$_reloadPackages$Filter)
7104 for (Package *package in packages)
7105 if ([package upgradableAndEssential:YES] || [package visible])
7106 CFArrayAppendValue(packages_, package);
7109 _profile(ChangesController$_reloadPackages$radixSort)
7110 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7115 - (void) reloadData {
7116 @synchronized (database_) {
7117 era_ = [database_ era];
7118 NSArray *packages = [database_ packages];
7120 [sections_ removeAllObjects];
7123 UIProgressHUD *hud([delegate_ addProgressHUD]);
7124 [hud setText:UCLocalize("LOADING")];
7125 //NSLog(@"HUD:%@::%@", delegate_, hud);
7126 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7127 [delegate_ removeProgressHUD:hud];
7129 [self _reloadPackages:packages];
7132 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7133 Section *ignored = nil;
7134 Section *section = nil;
7138 bool unseens = false;
7140 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7142 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7143 Package *package = [self packageAtIndex:offset];
7145 BOOL uae = [package upgradableAndEssential:YES];
7149 time_t seen([package seen]);
7151 if (section == nil || last != seen) {
7155 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7158 _profile(ChangesController$reloadData$Allocate)
7159 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7160 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7161 [sections_ addObject:section];
7165 [section addToCount];
7166 } else if ([package ignored]) {
7167 if (ignored == nil) {
7168 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7170 [ignored addToCount];
7173 [upgradable addToCount];
7178 CFRelease(formatter);
7181 Section *last = [sections_ lastObject];
7182 size_t count = [last count];
7183 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7184 [sections_ removeLastObject];
7187 if ([ignored count] != 0)
7188 [sections_ insertObject:ignored atIndex:0];
7190 [sections_ insertObject:upgradable atIndex:0];
7195 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7196 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7197 style:UIBarButtonItemStylePlain
7199 action:@selector(upgradeButtonClicked)
7202 if (![delegate_ updating])
7203 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7204 initWithTitle:UCLocalize("REFRESH")
7205 style:UIBarButtonItemStylePlain
7207 action:@selector(refreshButtonClicked)
7215 /* Search Controller {{{ */
7216 @interface SearchController : FilteredPackageListController <
7219 UISearchBar *search_;
7223 - (id) initWithDatabase:(Database *)database;
7224 - (void) setSearchTerm:(NSString *)term;
7225 - (void) reloadData;
7229 @implementation SearchController
7236 - (NSURL *) navigationURL {
7237 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7238 return [NSURL URLWithString:@"cydia://search"];
7240 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7243 - (void) setSearchTerm:(NSString *)searchTerm {
7244 [search_ setText:searchTerm];
7248 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7249 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7250 [search_ resignFirstResponder];
7254 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7255 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7259 - (id) initWithDatabase:(Database *)database {
7260 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7261 search_ = [[UISearchBar alloc] init];
7265 - (void)viewDidAppear:(BOOL)animated {
7266 [super viewDidAppear:animated];
7268 if (!searchloaded_) {
7269 searchloaded_ = YES;
7270 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7271 [search_ layoutSubviews];
7272 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7274 UITextField *textField;
7275 if ([search_ respondsToSelector:@selector(searchField)])
7276 textField = [search_ searchField];
7278 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7280 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7281 [search_ setDelegate:self];
7282 [textField setEnablesReturnKeyAutomatically:NO];
7283 [[self navigationItem] setTitleView:textField];
7287 - (void) reloadData {
7288 [self setObject:[search_ text]];
7293 - (void) didSelectPackage:(Package *)package {
7294 [search_ resignFirstResponder];
7295 [super didSelectPackage:package];
7300 /* Package Settings Controller {{{ */
7301 @interface PackageSettingsController : CYViewController <
7302 UITableViewDataSource,
7305 _transient Database *database_;
7308 UITableView *table_;
7309 UISwitch *subscribedSwitch_;
7310 UISwitch *ignoredSwitch_;
7311 UITableViewCell *subscribedCell_;
7312 UITableViewCell *ignoredCell_;
7315 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7319 @implementation PackageSettingsController
7322 [self releaseSubviews];
7329 - (NSURL *) navigationURL {
7330 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7333 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7334 if (package_ == nil)
7340 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7341 if (package_ == nil)
7347 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7348 return UCLocalize("CHANGE_PACKAGE_SETTINGS");
7351 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7352 return UCLocalize("SHOW_ALL_CHANGES_EX");
7355 - (void) onSubscribed:(id)control {
7356 bool value([control isOn]);
7357 if (package_ == nil)
7359 if ([package_ setSubscribed:value])
7360 [delegate_ updateData];
7363 - (void) onIgnored:(id)control {
7364 // TODO: set Held state - possibly call out to dpkg, etc.
7367 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7368 if (package_ == nil)
7371 switch ([indexPath row]) {
7372 case 0: return subscribedCell_;
7373 case 1: return ignoredCell_;
7382 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7384 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7385 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7386 [table_ setDataSource:self];
7387 [table_ setDelegate:self];
7388 [[self view] addSubview:table_];
7390 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7391 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7392 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7394 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7395 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7396 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7397 // Disable this switch, since it only reflects (not modifies) the ignored state.
7398 [ignoredSwitch_ setUserInteractionEnabled:NO];
7400 subscribedCell_ = [[UITableViewCell alloc] init];
7401 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7402 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7403 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7405 ignoredCell_ = [[UITableViewCell alloc] init];
7406 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7407 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7408 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7409 // FIXME: Ignored state is not saved.
7410 [ignoredCell_ setUserInteractionEnabled:NO];
7413 - (void) viewDidLoad {
7414 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7417 - (void) releaseSubviews {
7418 [ignoredCell_ release];
7421 [subscribedCell_ release];
7422 subscribedCell_ = nil;
7427 [ignoredSwitch_ release];
7428 ignoredSwitch_ = nil;
7430 [subscribedSwitch_ release];
7431 subscribedSwitch_ = nil;
7434 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7435 if ((self = [super init])) {
7436 database_ = database;
7437 name_ = [package retain];
7441 - (void) reloadData {
7444 if (package_ != nil)
7445 [package_ autorelease];
7446 package_ = [database_ packageWithName:name_];
7447 if (package_ != nil) {
7449 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7450 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7453 [table_ reloadData];
7459 /* Installed Controller {{{ */
7460 @interface InstalledController : FilteredPackageListController {
7464 - (id) initWithDatabase:(Database *)database;
7466 - (void) updateRoleButton;
7467 - (void) queueStatusDidChange;
7471 @implementation InstalledController
7477 - (NSURL *) navigationURL {
7478 return [NSURL URLWithString:@"cydia://installed"];
7481 - (id) initWithDatabase:(Database *)database {
7482 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7483 [self updateRoleButton];
7484 [self queueStatusDidChange];
7489 - (void) queueButtonClicked {
7494 - (void) queueStatusDidChange {
7498 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7499 initWithTitle:UCLocalize("QUEUE")
7500 style:UIBarButtonItemStyleDone
7502 action:@selector(queueButtonClicked)
7505 [[self navigationItem] setLeftBarButtonItem:nil];
7511 - (void) updateRoleButton {
7512 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7513 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7514 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7515 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7517 action:@selector(roleButtonClicked)
7521 - (void) roleButtonClicked {
7522 [self setObject:[NSNumber numberWithBool:expert_]];
7526 [self updateRoleButton];
7532 /* Source Cell {{{ */
7533 @interface SourceCell : CYTableViewCell <
7541 - (void) setSource:(Source *)source;
7545 @implementation SourceCell
7547 - (void) clearSource {
7557 - (void) setSource:(Source *)source {
7561 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7563 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7564 icon_ = [icon_ retain];
7566 origin_ = [[source name] retain];
7567 label_ = [[source uri] retain];
7569 [content_ setNeedsDisplay];
7577 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7578 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7579 UIView *content([self contentView]);
7580 CGRect bounds([content bounds]);
7582 content_ = [[ContentView alloc] initWithFrame:bounds];
7583 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7584 [content_ setBackgroundColor:[UIColor whiteColor]];
7585 [content addSubview:content_];
7587 [content_ setDelegate:self];
7588 [content_ setOpaque:YES];
7592 - (NSString *) accessibilityLabel {
7596 - (void) drawContentRect:(CGRect)rect {
7597 bool highlighted(highlighted_);
7598 float width(rect.size.width);
7601 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7608 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7612 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7617 /* Source Controller {{{ */
7618 @interface SourceController : FilteredPackageListController {
7622 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7626 @implementation SourceController
7628 - (NSURL *) navigationURL {
7629 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7632 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7635 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7641 /* Sources Controller {{{ */
7642 @interface SourcesController : CYViewController <
7643 UITableViewDataSource,
7646 _transient Database *database_;
7648 NSMutableArray *sources_;
7652 UIProgressHUD *hud_;
7655 //NSURLConnection *installer_;
7656 NSURLConnection *trivial_;
7657 NSURLConnection *trivial_bz2_;
7658 NSURLConnection *trivial_gz_;
7659 //NSURLConnection *automatic_;
7664 - (id) initWithDatabase:(Database *)database;
7665 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7669 @implementation SourcesController
7671 - (void) _releaseConnection:(NSURLConnection *)connection {
7672 if (connection != nil) {
7673 [connection cancel];
7674 //[connection setDelegate:nil];
7675 [connection release];
7680 [self releaseSubviews];
7686 //[self _releaseConnection:installer_];
7687 [self _releaseConnection:trivial_];
7688 [self _releaseConnection:trivial_gz_];
7689 [self _releaseConnection:trivial_bz2_];
7690 //[self _releaseConnection:automatic_];
7696 - (NSURL *) navigationURL {
7697 return [NSURL URLWithString:@"cydia://sources"];
7700 - (void) viewDidAppear:(BOOL)animated {
7701 [super viewDidAppear:animated];
7702 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7705 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7706 return offset_ == 0 ? 1 : 2;
7709 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7710 switch (section + (offset_ == 0 ? 1 : 0)) {
7711 case 0: return UCLocalize("ENTERED_BY_USER");
7712 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7718 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7719 int count = [sources_ count];
7721 case 0: return (offset_ == 0 ? count : offset_);
7722 case 1: return count - offset_;
7728 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7730 switch (indexPath.section) {
7731 case 0: idx = indexPath.row; break;
7732 case 1: idx = indexPath.row + offset_; break;
7736 return [sources_ objectAtIndex:idx];
7739 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7740 static NSString *cellIdentifier = @"SourceCell";
7742 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7743 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7744 [cell setSource:[self sourceAtIndexPath:indexPath]];
7745 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7750 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7751 Source *source = [self sourceAtIndexPath:indexPath];
7753 SourceController *controller = [[[SourceController alloc]
7754 initWithDatabase:database_
7758 [controller setDelegate:delegate_];
7760 [[self navigationController] pushViewController:controller animated:YES];
7763 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7764 Source *source = [self sourceAtIndexPath:indexPath];
7765 return [source record] != nil;
7768 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7769 Source *source = [self sourceAtIndexPath:indexPath];
7770 [Sources_ removeObjectForKey:[source key]];
7771 [delegate_ syncData];
7775 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
7778 @"./", @"Distribution",
7779 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
7781 [delegate_ syncData];
7784 - (NSString *) getWarning {
7785 NSString *href(href_);
7786 NSRange colon([href rangeOfString:@"://"]);
7787 if (colon.location != NSNotFound)
7788 href = [href substringFromIndex:(colon.location + 3)];
7789 href = [href stringByAddingPercentEscapes];
7790 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7791 href = [href stringByCachingURLWithCurrentCDN];
7793 NSURL *url([NSURL URLWithString:href]);
7795 NSStringEncoding encoding;
7796 NSError *error(nil);
7798 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7799 return [warning length] == 0 ? nil : warning;
7803 - (void) _endConnection:(NSURLConnection *)connection {
7804 // XXX: the memory management in this method is horribly awkward
7806 NSURLConnection **field = NULL;
7807 if (connection == trivial_)
7809 else if (connection == trivial_bz2_)
7810 field = &trivial_bz2_;
7811 else if (connection == trivial_gz_)
7812 field = &trivial_gz_;
7813 _assert(field != NULL);
7814 [connection release];
7819 trivial_bz2_ == nil &&
7825 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7828 UIAlertView *alert = [[[UIAlertView alloc]
7829 initWithTitle:UCLocalize("SOURCE_WARNING")
7832 cancelButtonTitle:UCLocalize("CANCEL")
7833 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
7836 [alert setContext:@"warning"];
7837 [alert setNumberOfRows:1];
7841 } else if (error_ != nil) {
7842 UIAlertView *alert = [[[UIAlertView alloc]
7843 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7844 message:[error_ localizedDescription]
7846 cancelButtonTitle:UCLocalize("OK")
7847 otherButtonTitles:nil
7850 [alert setContext:@"urlerror"];
7853 UIAlertView *alert = [[[UIAlertView alloc]
7854 initWithTitle:UCLocalize("NOT_REPOSITORY")
7855 message:UCLocalize("NOT_REPOSITORY_EX")
7857 cancelButtonTitle:UCLocalize("OK")
7858 otherButtonTitles:nil
7861 [alert setContext:@"trivial"];
7865 [delegate_ setStatusBarShowsProgress:NO];
7866 [delegate_ removeProgressHUD:hud_];
7876 if (error_ != nil) {
7883 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
7884 switch ([response statusCode]) {
7890 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
7891 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7893 error_ = [error retain];
7894 [self _endConnection:connection];
7897 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
7898 [self _endConnection:connection];
7901 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
7902 NSMutableURLRequest *request = [NSMutableURLRequest
7903 requestWithURL:[NSURL URLWithString:href]
7904 cachePolicy:NSURLRequestUseProtocolCachePolicy
7905 timeoutInterval:120.0
7908 [request setHTTPMethod:method];
7910 if (Machine_ != NULL)
7911 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
7912 if (UniqueID_ != nil)
7913 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
7915 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
7917 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
7920 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7921 NSString *context([alert context]);
7923 if ([context isEqualToString:@"source"]) {
7926 NSString *href = [[alert textField] text];
7928 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
7930 if (![href hasSuffix:@"/"])
7931 href_ = [href stringByAppendingString:@"/"];
7934 href_ = [href_ retain];
7936 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
7937 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
7938 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
7939 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
7943 // XXX: this is stupid
7944 hud_ = [[delegate_ addProgressHUD] retain];
7945 [hud_ setText:UCLocalize("VERIFYING_URL")];
7954 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7955 } else if ([context isEqualToString:@"trivial"])
7956 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7957 else if ([context isEqualToString:@"urlerror"])
7958 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7959 else if ([context isEqualToString:@"warning"]) {
7974 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7979 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7981 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7982 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7983 [list_ setRowHeight:56];
7984 [list_ setDataSource:self];
7985 [list_ setDelegate:self];
7986 [[self view] addSubview:list_];
7989 - (void) viewDidLoad {
7990 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
7991 [self updateButtonsForEditingStatus:NO animated:NO];
7994 - (void) releaseSubviews {
7999 - (id) initWithDatabase:(Database *)database {
8000 if ((self = [super init]) != nil) {
8001 database_ = database;
8002 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8006 - (void) reloadData {
8010 if (!list.ReadMainList())
8013 [sources_ removeAllObjects];
8014 [sources_ addObjectsFromArray:[database_ sources]];
8016 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8019 int count([sources_ count]);
8021 for (int i = 0; i != count; i++) {
8022 if ([[sources_ objectAtIndex:i] record] == nil)
8027 [list_ setEditing:NO];
8028 [self updateButtonsForEditingStatus:NO animated:NO];
8032 - (void) showAddSourcePrompt {
8033 UIAlertView *alert = [[[UIAlertView alloc]
8034 initWithTitle:UCLocalize("ENTER_APT_URL")
8037 cancelButtonTitle:UCLocalize("CANCEL")
8038 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
8041 [alert setContext:@"source"];
8042 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8044 [alert setNumberOfRows:1];
8045 [alert addTextFieldWithValue:@"http://" label:@""];
8047 UITextInputTraits *traits = [[alert textField] textInputTraits];
8048 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8049 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8050 [traits setKeyboardType:UIKeyboardTypeURL];
8051 // XXX: UIReturnKeyDone
8052 [traits setReturnKeyType:UIReturnKeyNext];
8057 - (void) addButtonClicked {
8058 [self showAddSourcePrompt];
8061 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8062 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8063 initWithTitle:UCLocalize("ADD")
8064 style:UIBarButtonItemStylePlain
8066 action:@selector(addButtonClicked)
8067 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8069 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8070 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8071 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8073 action:@selector(editButtonClicked)
8074 ] autorelease] animated:animated];
8076 if (IsWildcat_ && !editing)
8077 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8078 initWithTitle:UCLocalize("SETTINGS")
8079 style:UIBarButtonItemStylePlain
8081 action:@selector(settingsButtonClicked)
8085 - (void) settingsButtonClicked {
8086 [delegate_ showSettings];
8089 - (void) editButtonClicked {
8090 [list_ setEditing:![list_ isEditing] animated:YES];
8092 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8098 /* Settings Controller {{{ */
8099 @interface SettingsController : CYViewController <
8100 UITableViewDataSource,
8103 _transient Database *database_;
8104 // XXX: ok, "roledelegate_"?...
8105 _transient id roledelegate_;
8106 UITableView *table_;
8107 UISegmentedControl *segment_;
8111 - (void) showDoneButton;
8112 - (void) resizeSegmentedControl;
8116 @implementation SettingsController
8119 [self releaseSubviews];
8125 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8127 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8128 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8129 [table_ setDelegate:self];
8130 [table_ setDataSource:self];
8131 [[self view] addSubview:table_];
8133 NSArray *items = [NSArray arrayWithObjects:
8135 UCLocalize("HACKER"),
8136 UCLocalize("DEVELOPER"),
8138 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8139 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8140 [container_ addSubview:segment_];
8143 - (void) viewDidLoad {
8144 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8147 if ([Role_ isEqualToString:@"User"]) index = 0;
8148 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8149 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8151 [segment_ setSelectedSegmentIndex:index];
8152 [self showDoneButton];
8155 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8156 [self resizeSegmentedControl];
8159 - (void) releaseSubviews {
8166 [container_ release];
8170 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8171 if ((self = [super init])) {
8172 database_ = database;
8173 roledelegate_ = delegate;
8177 - (void) resizeSegmentedControl {
8178 CGFloat width = [[self view] frame].size.width;
8179 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8182 - (void) viewWillAppear:(BOOL)animated {
8183 [super viewWillAppear:animated];
8185 [self resizeSegmentedControl];
8188 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8189 [self resizeSegmentedControl];
8192 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8193 [self resizeSegmentedControl];
8197 NSString *role(nil);
8199 switch ([segment_ selectedSegmentIndex]) {
8200 case 0: role = @"User"; break;
8201 case 1: role = @"Hacker"; break;
8202 case 2: role = @"Developer"; break;
8207 if (![role isEqualToString:Role_]) {
8208 bool rolling(Role_ == nil);
8211 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8215 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8219 [roledelegate_ loadData];
8221 [roledelegate_ updateData];
8225 - (void) segmentChanged:(UISegmentedControl *)control {
8226 [self showDoneButton];
8229 - (void) saveAndClose {
8232 [[self navigationItem] setRightBarButtonItem:nil];
8233 [[self navigationController] dismissModalViewControllerAnimated:YES];
8236 - (void) doneButtonClicked {
8237 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8238 [spinner startAnimating];
8239 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8240 [[self navigationItem] setRightBarButtonItem:spinItem];
8242 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8245 - (void) showDoneButton {
8246 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8247 initWithTitle:UCLocalize("DONE")
8248 style:UIBarButtonItemStyleDone
8250 action:@selector(doneButtonClicked)
8251 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8254 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8255 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8259 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8263 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8264 return nil; // This method is required by the protocol.
8267 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8269 return UCLocalize("ROLE_EX");
8271 return [NSString stringWithFormat:
8272 @"%@: %@\n%@: %@\n%@: %@",
8273 UCLocalize("USER"), UCLocalize("USER_EX"),
8274 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8275 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8280 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8281 return section == 3 ? 44.0f : 0;
8284 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8285 return section == 3 ? container_ : nil;
8288 - (void) reloadData {
8290 [table_ reloadData];
8295 /* Stash Controller {{{ */
8296 @interface StashController : CYViewController {
8297 UIActivityIndicatorView *spinner_;
8303 @implementation StashController
8306 [self releaseSubviews];
8312 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8313 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8315 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8316 CGRect spinrect = [spinner_ frame];
8317 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8318 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8319 [spinner_ setFrame:spinrect];
8320 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8321 [[self view] addSubview:spinner_];
8322 [spinner_ startAnimating];
8325 captrect.size.width = [[self view] frame].size.width;
8326 captrect.size.height = 40.0f;
8327 captrect.origin.x = 0;
8328 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8329 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8330 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8331 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8332 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8333 [caption_ setTextColor:[UIColor whiteColor]];
8334 [caption_ setBackgroundColor:[UIColor clearColor]];
8335 [caption_ setShadowColor:[UIColor blackColor]];
8336 [caption_ setTextAlignment:UITextAlignmentCenter];
8337 [[self view] addSubview:caption_];
8340 statusrect.size.width = [[self view] frame].size.width;
8341 statusrect.size.height = 30.0f;
8342 statusrect.origin.x = 0;
8343 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8344 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8345 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8346 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8347 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8348 [status_ setTextColor:[UIColor whiteColor]];
8349 [status_ setBackgroundColor:[UIColor clearColor]];
8350 [status_ setShadowColor:[UIColor blackColor]];
8351 [status_ setTextAlignment:UITextAlignmentCenter];
8352 [[self view] addSubview:status_];
8355 - (void) releaseSubviews {
8369 @interface Cydia : UIApplication <
8370 ConfirmationControllerDelegate,
8371 ProgressControllerDelegate,
8373 UINavigationControllerDelegate,
8374 UITabBarControllerDelegate
8376 // XXX: evaluate all fields for _transient
8379 CYTabBarController *tabbar_;
8381 NSMutableArray *essential_;
8382 NSMutableArray *broken_;
8384 Database *database_;
8391 StashController *stash_;
8400 @implementation Cydia
8402 - (void) beginUpdate {
8403 [tabbar_ beginUpdate];
8407 return [tabbar_ updating];
8411 if ([broken_ count] != 0) {
8412 int count = [broken_ count];
8414 UIAlertView *alert = [[[UIAlertView alloc]
8415 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8416 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8418 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8419 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8422 [alert setContext:@"fixhalf"];
8424 } else if (!Ignored_ && [essential_ count] != 0) {
8425 int count = [essential_ count];
8427 UIAlertView *alert = [[[UIAlertView alloc]
8428 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8429 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8431 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8432 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8435 [alert setContext:@"upgrade"];
8440 - (void) _saveConfig {
8446 NSString *error(nil);
8448 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8450 NSError *error(nil);
8451 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8452 NSLog(@"failure to save metadata data: %@", error);
8457 NSLog(@"failure to serialize metadata: %@", error);
8462 // Navigation controller for the queuing badge.
8463 - (CYNavigationController *) queueNavigationController {
8464 NSArray *controllers = [tabbar_ viewControllers];
8465 return [controllers objectAtIndex:3];
8468 - (void) _updateData {
8471 [tabbar_ reloadData];
8473 CYNavigationController *navigation = [self queueNavigationController];
8475 id queuedelegate = nil;
8476 if ([[navigation viewControllers] count] > 0)
8477 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8479 [queuedelegate queueStatusDidChange];
8480 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8483 - (void) _refreshIfPossible {
8484 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8486 bool recently = false;
8487 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8488 if (update != nil) {
8489 NSTimeInterval interval([update timeIntervalSinceNow]);
8490 if (interval <= 0 && interval > -(15*60))
8494 // Don't automatic refresh if:
8495 // - We already refreshed recently.
8496 // - We already auto-refreshed this launch.
8497 // - Auto-refresh is disabled.
8498 if (recently || loaded_ || ManualRefresh) {
8499 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8501 // If we are cancelling, we need to make sure it knows it's already loaded.
8505 // We are going to load, so remember that.
8509 SCNetworkReachabilityFlags flags; {
8510 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8511 SCNetworkReachabilityGetFlags(reachability, &flags);
8512 CFRelease(reachability);
8515 // XXX: this elaborate mess is what Apple is using to determine this? :(
8516 // XXX: do we care if the user has to intervene? maybe that's ok?
8518 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8519 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8520 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8521 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8522 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8523 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8527 // If we can reach the server, auto-refresh!
8529 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8534 - (void) refreshIfPossible {
8535 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8538 - (void) _reloadData {
8539 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8540 [hud setText:UCLocalize("RELOADING_DATA")];
8542 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8545 [self removeProgressHUD:hud];
8549 [essential_ removeAllObjects];
8550 [broken_ removeAllObjects];
8552 NSArray *packages([database_ packages]);
8553 for (Package *package in packages) {
8555 [broken_ addObject:package];
8556 if ([package upgradableAndEssential:NO]) {
8557 if ([package essential])
8558 [essential_ addObject:package];
8563 NSLog(@"changes:#%u", changes);
8565 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8568 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8569 [changesItem setBadgeValue:badge];
8570 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8571 [self setApplicationIconBadgeNumber:changes];
8574 [changesItem setBadgeValue:nil];
8575 [changesItem setAnimatedBadge:NO];
8576 [self setApplicationIconBadgeNumber:0];
8581 [self refreshIfPossible];
8584 - (void) updateData {
8593 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8594 _assert(file != NULL);
8596 for (NSString *key in [Sources_ allKeys]) {
8597 NSDictionary *source([Sources_ objectForKey:key]);
8599 fprintf(file, "%s %s %s\n",
8600 [[source objectForKey:@"Type"] UTF8String],
8601 [[source objectForKey:@"URI"] UTF8String],
8602 [[source objectForKey:@"Distribution"] UTF8String]
8610 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8611 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8613 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8614 [tabbar_ presentModalViewController:navigation animated:YES];
8617 detachNewThreadSelector:@selector(update_)
8620 title:UCLocalize("UPDATING_SOURCES")
8624 - (void) reloadData {
8625 @synchronized (self) {
8631 pkgProblemResolver *resolver = [database_ resolver];
8633 resolver->InstallProtect();
8634 if (!resolver->Resolve(true))
8639 if (![database_ prepare])
8642 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8643 [page setDelegate:self];
8644 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8645 [confirm_ setDelegate:self];
8648 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8649 [tabbar_ presentModalViewController:confirm_ animated:YES];
8655 @synchronized (self) {
8660 - (void) clearPackage:(Package *)package {
8661 @synchronized (self) {
8668 - (void) installPackages:(NSArray *)packages {
8669 @synchronized (self) {
8670 for (Package *package in packages)
8677 - (void) installPackage:(Package *)package {
8678 @synchronized (self) {
8685 - (void) removePackage:(Package *)package {
8686 @synchronized (self) {
8693 - (void) distUpgrade {
8694 @synchronized (self) {
8695 if (![database_ upgrade])
8702 @synchronized (self) {
8707 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8710 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8712 if (navigation != nil) {
8713 [navigation pushViewController:progress animated:YES];
8715 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8717 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8718 [tabbar_ presentModalViewController:navigation animated:YES];
8722 detachNewThreadSelector:@selector(perform)
8725 title:UCLocalize("RUNNING")
8731 - (void) progressControllerIsComplete:(ProgressController *)progress {
8736 - (void) showSettings {
8737 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8738 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8740 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8741 [tabbar_ presentModalViewController:nav animated:YES];
8744 - (void) retainNetworkActivityIndicator {
8745 if (activity_++ == 0)
8746 [self setNetworkActivityIndicatorVisible:YES];
8749 - (void) releaseNetworkActivityIndicator {
8750 if (--activity_ == 0)
8751 [self setNetworkActivityIndicatorVisible:NO];
8754 - (void) cancelAndClear:(bool)clear {
8755 @synchronized (self) {
8767 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8768 NSString *context([alert context]);
8770 if ([context isEqualToString:@"fixhalf"]) {
8771 if (button == [alert cancelButtonIndex]) {
8772 @synchronized (self) {
8773 for (Package *broken in broken_) {
8776 NSString *id = [broken id];
8777 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8778 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8779 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8780 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8786 } else if (button == [alert firstOtherButtonIndex]) {
8787 [broken_ removeAllObjects];
8791 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8792 } else if ([context isEqualToString:@"upgrade"]) {
8793 if (button == [alert firstOtherButtonIndex]) {
8794 @synchronized (self) {
8795 for (Package *essential in essential_)
8796 [essential install];
8801 } else if (button == [alert firstOtherButtonIndex] + 1) {
8803 } else if (button == [alert cancelButtonIndex]) {
8807 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8811 - (void) system:(NSString *)command { _pooled
8813 system([command UTF8String]);
8817 - (void) applicationWillSuspend {
8819 [super applicationWillSuspend];
8822 - (BOOL) isSafeToSuspend {
8823 // Use external process status API internally.
8824 // This is probably a really bad idea.
8825 // XXX: what is the point of this? does this solve anything at all?
8826 uint64_t status = 0;
8828 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8829 notify_get_state(notify_token, &status);
8830 notify_cancel(notify_token);
8833 return locked_ == 0 && status == 0;
8836 - (void) applicationSuspend:(__GSEvent *)event {
8837 if ([self isSafeToSuspend])
8838 [super applicationSuspend:event];
8841 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8842 if ([self isSafeToSuspend])
8843 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8846 - (void) _setSuspended:(BOOL)value {
8847 if ([self isSafeToSuspend])
8848 [super _setSuspended:value];
8851 - (UIProgressHUD *) addProgressHUD {
8852 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8853 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8855 [window_ setUserInteractionEnabled:NO];
8858 UIViewController *target = tabbar_;
8859 while ([target modalViewController] != nil) target = [target modalViewController];
8860 [[target view] addSubview:hud];
8866 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8868 [hud removeFromSuperview];
8869 [window_ setUserInteractionEnabled:YES];
8873 - (CYViewController *) pageForPackage:(NSString *)name {
8874 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
8877 - (CYViewController *) pageForURL:(NSURL *)url {
8878 NSString *scheme([[url scheme] lowercaseString]);
8879 if ([[url absoluteString] length] <= [scheme length] + 3)
8881 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
8882 NSArray *components([path pathComponents]);
8884 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
8885 return [self pageForPackage:[components objectAtIndex:1]];
8887 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
8890 NSString *base([components objectAtIndex:0]);
8892 CYViewController *controller = nil;
8894 if ([base isEqualToString:@"url"]) {
8895 // This kind of URL can contain slashes in the argument, so we can't parse them below.
8896 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
8897 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
8898 } else if ([components count] == 1) {
8899 if ([base isEqualToString:@"manage"]) {
8900 controller = [[[ManageController alloc] init] autorelease];
8903 if ([base isEqualToString:@"sources"]) {
8904 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8907 if ([base isEqualToString:@"home"]) {
8908 controller = [[[HomeController alloc] init] autorelease];
8911 if ([base isEqualToString:@"sections"]) {
8912 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
8915 if ([base isEqualToString:@"search"]) {
8916 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8919 if ([base isEqualToString:@"changes"]) {
8920 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
8923 if ([base isEqualToString:@"installed"]) {
8924 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8926 } else if ([components count] == 2) {
8927 NSString *argument = [components objectAtIndex:1];
8929 if ([base isEqualToString:@"package"]) {
8930 controller = [self pageForPackage:argument];
8933 if ([base isEqualToString:@"search"]) {
8934 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8935 [(SearchController *)controller setSearchTerm:argument];
8938 if ([base isEqualToString:@"sections"]) {
8939 if ([argument isEqualToString:@"all"])
8941 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
8944 if ([base isEqualToString:@"sources"]) {
8945 if ([argument isEqualToString:@"add"]) {
8946 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8947 [(SourcesController *)controller showAddSourcePrompt];
8949 NSArray *sources = [database_ sources];
8950 for (Source *source in sources) {
8951 if ([[source name] caseInsensitiveCompare:argument] == NSOrderedSame) {
8952 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
8959 if ([base isEqualToString:@"launch"]) {
8960 [self launchApplicationWithIdentifier:argument suspended:NO];
8963 } else if ([components count] == 3) {
8964 NSString *arg1 = [components objectAtIndex:1];
8965 NSString *arg2 = [components objectAtIndex:2];
8967 if ([base isEqualToString:@"package"]) {
8968 if ([arg2 isEqualToString:@"settings"]) {
8969 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
8970 } else if ([arg2 isEqualToString:@"files"]) {
8971 if (Package *package = [database_ packageWithName:arg1]) {
8972 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8973 [(FileTable *)controller setPackage:package];
8979 [controller setDelegate:self];
8983 - (BOOL) openCydiaURL:(NSURL *)url {
8984 CYViewController *page([self pageForURL:url]);
8987 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
8988 [nav setViewControllers:[NSArray arrayWithObject:page]];
8989 [tabbar_ setUnselectedViewController:nav];
8995 - (void) applicationOpenURL:(NSURL *)url {
8996 [super applicationOpenURL:url];
8998 if (!loaded_) starturl_ = [url retain];
8999 else [self openCydiaURL:url];
9002 - (void) applicationWillResignActive:(UIApplication *)application {
9003 // Stop refreshing if you get a phone call or lock the device.
9004 if ([tabbar_ updating])
9005 [tabbar_ cancelUpdate];
9007 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9008 [super applicationWillResignActive:application];
9011 - (void) applicationWillTerminate:(UIApplication *)application {
9013 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9014 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9015 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9020 - (void) addStashController {
9022 stash_ = [[StashController alloc] init];
9023 [window_ addSubview:[stash_ view]];
9026 - (void) removeStashController {
9027 [[stash_ view] removeFromSuperview];
9033 [self setIdleTimerDisabled:YES];
9035 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9036 [self setStatusBarShowsProgress:YES];
9037 UpdateExternalStatus(1);
9039 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9041 UpdateExternalStatus(0);
9042 [self setStatusBarShowsProgress:NO];
9044 [self removeStashController];
9046 if (ExecFork() == 0) {
9047 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9048 perror("launchctl stop");
9052 - (void) setupViewControllers {
9053 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9055 NSMutableArray *items([NSMutableArray arrayWithObjects:
9056 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9057 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9058 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9059 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9063 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9064 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9066 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9069 NSMutableArray *controllers([NSMutableArray array]);
9070 for (UITabBarItem *item in items) {
9071 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9072 [controller setTabBarItem:item];
9073 [controllers addObject:controller];
9075 [tabbar_ setViewControllers:controllers];
9077 [tabbar_ setUpdateDelegate:self];
9080 - (CYEmulatedLoadingController *)showEmulatedLoadingControllerInView:(UIView *)view {
9081 static CYEmulatedLoadingController *fake = nil;
9085 fake = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9086 [view addSubview:[fake view]];
9088 [[fake view] removeFromSuperview];
9096 - (void) applicationDidFinishLaunching:(id)unused {
9100 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9101 [self setApplicationSupportsShakeToEdit:NO];
9103 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9104 initWithMemoryCapacity:524288
9105 diskCapacity:10485760
9106 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9109 [CYBrowserController _initialize];
9111 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9113 Font12_ = [[UIFont systemFontOfSize:12] retain];
9114 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9115 Font14_ = [[UIFont systemFontOfSize:14] retain];
9116 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9117 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9119 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9120 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9122 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9123 [window_ orderFront:self];
9124 [window_ makeKey:self];
9125 [window_ setHidden:NO];
9128 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9129 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9130 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9131 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9132 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9133 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9134 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9135 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9136 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9139 [self addStashController];
9140 // XXX: this would be much cleaner as a yieldToSelector:
9141 // that way the removeStashController could happen right here inline
9142 // we also could no longer require the useless stash_ field anymore
9143 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9147 database_ = [Database sharedInstance];
9149 [window_ setUserInteractionEnabled:NO];
9150 [self setupViewControllers];
9151 [self showEmulatedLoadingControllerInView:window_];
9153 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9160 [window_ setUserInteractionEnabled:YES];
9162 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9163 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9165 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9166 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9170 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9171 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9172 [window_ setUserInteractionEnabled:NO];
9178 [window_ addSubview:[tabbar_ view]];
9179 [self showEmulatedLoadingControllerInView:nil];
9180 [window_ setUserInteractionEnabled:YES];
9182 int selectedIndex = 0;
9183 NSMutableArray *items = nil;
9185 bool recently = false;
9186 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9187 if (closed != nil) {
9188 NSTimeInterval interval([closed timeIntervalSinceNow]);
9189 // XXX: Is 15 minutes the optimal time here?
9190 if (interval <= 0 && interval > -(15*60))
9194 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9195 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9198 for (NSArray *entry in items)
9199 if ([entry count] <= 0)
9202 if (!recently || !items || !enough) {
9203 items = [NSMutableArray array];
9204 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9205 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9206 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9208 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9210 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9211 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9213 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9216 [tabbar_ setSelectedIndex:selectedIndex];
9217 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9218 NSArray *stack = [items objectAtIndex:tab];
9219 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9220 NSMutableArray *current = [NSMutableArray array];
9222 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9223 NSString *addr = [stack objectAtIndex:nav];
9224 NSURL *url = [NSURL URLWithString:addr];
9225 CYViewController *page = [self pageForURL:url];
9227 [current addObject:page];
9230 [navigation setViewControllers:current];
9233 // (Try to) show the startup URL.
9234 if (starturl_ != nil) {
9235 [self openCydiaURL:starturl_];
9236 [starturl_ release];
9241 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9242 if (item != nil && IsWildcat_) {
9243 [sheet showFromBarButtonItem:item animated:YES];
9245 [sheet showInView:window_];
9252 id Alloc_(id self, SEL selector) {
9253 id object = alloc_(self, selector);
9254 lprintf("[%s]A-%p\n", self->isa->name, object);
9259 id Dealloc_(id self, SEL selector) {
9260 id object = dealloc_(self, selector);
9261 lprintf("[%s]D-%p\n", self->isa->name, object);
9265 Class $WebDefaultUIKitDelegate;
9267 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9268 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9269 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9270 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9273 static NSNumber *shouldPlayKeyboardSounds;
9277 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9279 case 1104: // Keyboard Button Clicked
9280 case 1105: // Keyboard Delete Repeated
9281 if (shouldPlayKeyboardSounds == nil) {
9282 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9283 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9286 if (![shouldPlayKeyboardSounds boolValue])
9290 _UIHardware$_playSystemSound$(self, _cmd, sound);
9294 Class $UIApplication;
9296 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9297 static BOOL initialized = NO;
9298 static BOOL started = NO;
9300 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9301 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9303 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9304 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9305 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9306 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9308 if (initialized && !enabled) {
9310 [bundle performSelector:@selector(_accessibilityStopServer)];
9311 } else if (enabled) {
9315 [bundle performSelector:@selector(_accessibilityStartServer)];
9321 int main(int argc, char *argv[]) { _pooled
9324 if (Class $UIDevice = objc_getClass("UIDevice")) {
9325 UIDevice *device([$UIDevice currentDevice]);
9326 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9330 UIScreen *screen([UIScreen mainScreen]);
9331 if ([screen respondsToSelector:@selector(scale)])
9332 ScreenScale_ = [screen scale];
9336 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9337 if (ScreenScale_ > 1)
9338 [parts addObject:@"@2x"];
9339 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9340 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9342 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9344 /* Library Hacks {{{ */
9345 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9347 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9348 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9349 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9350 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9351 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9354 $UIHardware = objc_getClass("UIHardware");
9355 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9356 if (UIHardware$_playSystemSound$ != NULL) {
9357 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9358 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9361 $UIApplication = objc_getClass("UIApplication");
9362 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9363 if (UIApplication$_updateApplicationAccessibility != NULL) {
9364 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9365 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9368 /* Set Locale {{{ */
9369 Locale_ = CFLocaleCopyCurrent();
9370 Languages_ = [NSLocale preferredLanguages];
9371 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9372 //NSLog(@"%@", [Languages_ description]);
9375 if (Languages_ == nil || [Languages_ count] == 0)
9376 // XXX: consider just setting to C and then falling through?
9379 lang = [[Languages_ objectAtIndex:0] UTF8String];
9380 setenv("LANG", lang, true);
9383 //std::setlocale(LC_ALL, lang);
9384 NSLog(@"Setting Language: %s", lang);
9387 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9389 /* Parse Arguments {{{ */
9390 bool substrate(false);
9396 for (int argi(1); argi != argc; ++argi)
9397 if (strcmp(argv[argi], "--") == 0) {
9399 argv[argi] = argv[0];
9405 for (int argi(1); argi != arge; ++argi)
9406 if (strcmp(args[argi], "--substrate") == 0)
9409 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9413 App_ = [[NSBundle mainBundle] bundlePath];
9414 Home_ = NSHomeDirectory();
9420 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9421 alloc_ = alloc->method_imp;
9422 alloc->method_imp = (IMP) &Alloc_;*/
9424 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9425 dealloc_ = dealloc->method_imp;
9426 dealloc->method_imp = (IMP) &Dealloc_;*/
9428 /* System Information {{{ */
9432 size = sizeof(maxproc);
9433 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9434 perror("sysctlbyname(\"kern.maxproc\", ?)");
9435 else if (maxproc < 64) {
9437 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9438 perror("sysctlbyname(\"kern.maxproc\", #)");
9441 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9442 char *osversion = new char[size];
9443 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9444 perror("sysctlbyname(\"kern.osversion\", ?)");
9446 System_ = [NSString stringWithUTF8String:osversion];
9448 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9449 char *machine = new char[size];
9450 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9451 perror("sysctlbyname(\"hw.machine\", ?)");
9455 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9456 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9457 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9458 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9462 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9463 NSData *data((NSData *) ecid);
9464 size_t length([data length]);
9465 uint8_t bytes[length];
9466 [data getBytes:bytes];
9467 char string[length * 2 + 1];
9468 for (size_t i(0); i != length; ++i)
9469 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9470 ChipID_ = [NSString stringWithUTF8String:string];
9474 IOObjectRelease(service);
9478 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9480 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9481 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9482 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9484 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9485 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9486 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9488 if (mcc != NULL && mnc != NULL)
9489 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9496 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9497 Build_ = [system objectForKey:@"ProductBuildVersion"];
9498 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9499 Product_ = [info objectForKey:@"SafariProductVersion"];
9500 Safari_ = [info objectForKey:@"CFBundleVersion"];
9503 /* Load Database {{{ */
9505 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9507 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9509 if (Metadata_ == NULL)
9510 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9512 Settings_ = [Metadata_ objectForKey:@"Settings"];
9514 Packages_ = [Metadata_ objectForKey:@"Packages"];
9515 Sections_ = [Metadata_ objectForKey:@"Sections"];
9516 Sources_ = [Metadata_ objectForKey:@"Sources"];
9518 Token_ = [Metadata_ objectForKey:@"Token"];
9521 if (Settings_ != nil)
9522 Role_ = [Settings_ objectForKey:@"Role"];
9524 if (Sections_ == nil) {
9525 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9526 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9529 if (Sources_ == nil) {
9530 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9531 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9536 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9539 if (Packages_ != nil) {
9541 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9545 [Metadata_ removeObjectForKey:@"Packages"];
9551 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9553 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9554 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9555 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9556 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9557 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9558 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9560 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9562 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9563 unlink("/tmp/.cydia.fw");
9565 } else if (access("/User", F_OK) != 0 || version < 2) {
9568 system("/usr/libexec/cydia/firmware.sh");
9572 _assert([[NSFileManager defaultManager]
9573 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9574 withIntermediateDirectories:YES
9579 if (access("/tmp/cydia.chk", F_OK) == 0) {
9580 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9581 _assert(errno == ENOENT);
9582 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9583 _assert(errno == ENOENT);
9586 /* APT Initialization {{{ */
9587 _assert(pkgInitConfig(*_config));
9588 _assert(pkgInitSystem(*_config, _system));
9591 _config->Set("APT::Acquire::Translation", lang);
9593 // XXX: this timeout might be important :(
9594 //_config->Set("Acquire::http::Timeout", 15);
9596 _config->Set("Acquire::http::MaxParallel", 3);
9598 /* Color Choices {{{ */
9599 space_ = CGColorSpaceCreateDeviceRGB();
9601 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9602 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9603 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9604 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9605 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9606 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9607 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9608 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9609 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9611 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9612 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9614 /* UIKit Configuration {{{ */
9615 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9616 if ($GSFontSetUseLegacyFontMetrics != NULL)
9617 $GSFontSetUseLegacyFontMetrics(YES);
9619 // XXX: I have a feeling this was important
9620 //UIKeyboardDisableAutomaticAppearance();
9623 Colon_ = UCLocalize("COLON_DELIMITED");
9624 Elision_ = UCLocalize("ELISION");
9625 Error_ = UCLocalize("ERROR");
9626 Warning_ = UCLocalize("WARNING");
9629 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9631 CGColorSpaceRelease(space_);