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;
984 static NSArray *Finishes_;
986 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
987 #define NotifyConfig_ "/etc/notify.conf"
989 static bool Queuing_;
991 static CYColor Blue_;
992 static CYColor Blueish_;
993 static CYColor Black_;
995 static CYColor White_;
996 static CYColor Gray_;
997 static CYColor Green_;
998 static CYColor Purple_;
999 static CYColor Purplish_;
1001 static UIColor *InstallingColor_;
1002 static UIColor *RemovingColor_;
1004 static NSString *App_;
1005 static NSString *Home_;
1007 static BOOL Advanced_;
1008 static BOOL Ignored_;
1010 static UIFont *Font12_;
1011 static UIFont *Font12Bold_;
1012 static UIFont *Font14_;
1013 static UIFont *Font18Bold_;
1014 static UIFont *Font22Bold_;
1016 static const char *Machine_ = NULL;
1017 static NSString *System_ = nil;
1018 static NSString *SerialNumber_ = nil;
1019 static NSString *ChipID_ = nil;
1020 static NSString *Token_ = nil;
1021 static NSString *UniqueID_ = nil;
1022 static NSString *PLMN_ = nil;
1023 static NSString *Build_ = nil;
1024 static NSString *Product_ = nil;
1025 static NSString *Safari_ = nil;
1027 static CFLocaleRef Locale_;
1028 static NSArray *Languages_;
1029 static CGColorSpaceRef space_;
1031 static NSDictionary *SectionMap_;
1032 static NSMutableDictionary *Metadata_;
1033 static _transient NSMutableDictionary *Settings_;
1034 static _transient NSString *Role_;
1035 static _transient NSMutableDictionary *Packages_;
1036 static _transient NSMutableDictionary *Sections_;
1037 static _transient NSMutableDictionary *Sources_;
1038 static bool Changed_;
1044 /* Display Helpers {{{ */
1045 inline float Interpolate(float begin, float end, float fraction) {
1046 return (end - begin) * fraction + begin;
1049 /* XXX: localize this! */
1050 NSString *SizeString(double size) {
1051 bool negative = size < 0;
1056 while (size > 1024) {
1061 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1063 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1066 static _finline const char *StripVersion_(const char *version) {
1067 const char *colon(strchr(version, ':'));
1068 return colon == NULL ? version : colon + 1;
1071 NSString *LocalizeSection(NSString *section) {
1072 static Pcre title_r("^(.*?) \\((.*)\\)$");
1073 if (title_r(section)) {
1074 NSString *parent(title_r[1]);
1075 NSString *child(title_r[2]);
1077 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1078 LocalizeSection(parent),
1079 LocalizeSection(child)
1083 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1086 NSString *Simplify(NSString *title) {
1087 const char *data = [title UTF8String];
1088 size_t size = [title length];
1090 static Pcre square_r("^\\[(.*)\\]$");
1091 if (square_r(data, size))
1092 return Simplify(square_r[1]);
1094 static Pcre paren_r("^\\((.*)\\)$");
1095 if (paren_r(data, size))
1096 return Simplify(paren_r[1]);
1098 static Pcre title_r("^(.*?) \\((.*)\\)$");
1099 if (title_r(data, size))
1100 return Simplify(title_r[1]);
1106 NSString *GetLastUpdate() {
1107 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1110 return UCLocalize("NEVER_OR_UNKNOWN");
1112 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1113 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1115 CFRelease(formatter);
1117 return [(NSString *) formatted autorelease];
1120 bool isSectionVisible(NSString *section) {
1121 NSDictionary *metadata([Sections_ objectForKey:section]);
1122 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1123 return hidden == nil || ![hidden boolValue];
1128 /* Delegate Prototypes {{{ */
1132 @interface NSObject (ProgressDelegate)
1135 @protocol ProgressDelegate
1136 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1137 - (void) setProgressTitle:(NSString *)title;
1138 - (void) setProgressPercent:(float)percent;
1139 - (void) startProgress;
1140 - (void) addProgressOutput:(NSString *)output;
1141 - (bool) isCancelling:(size_t)received;
1144 @protocol ConfigurationDelegate
1145 - (void) repairWithSelector:(SEL)selector;
1146 - (void) setConfigurationData:(NSString *)data;
1149 @class CYPackageController;
1151 @protocol CydiaDelegate
1152 - (void) retainNetworkActivityIndicator;
1153 - (void) releaseNetworkActivityIndicator;
1154 - (void) clearPackage:(Package *)package;
1155 - (void) installPackage:(Package *)package;
1156 - (void) installPackages:(NSArray *)packages;
1157 - (void) removePackage:(Package *)package;
1158 - (void) beginUpdate;
1160 - (void) distUpgrade;
1162 - (void) updateData;
1164 - (void) showSettings;
1165 - (UIProgressHUD *) addProgressHUD;
1166 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1167 - (CYViewController *) pageForPackage:(NSString *)name;
1168 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1171 static id<CydiaDelegate> CydiaApp;
1174 /* Status Delegation {{{ */
1176 public pkgAcquireStatus
1179 _transient NSObject<ProgressDelegate> *delegate_;
1187 void setDelegate(id delegate) {
1188 delegate_ = delegate;
1191 NSObject<ProgressDelegate> *getDelegate() const {
1195 virtual bool MediaChange(std::string media, std::string drive) {
1199 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1202 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1203 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1204 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1207 virtual void Done(pkgAcquire::ItemDesc &item) {
1210 virtual void Fail(pkgAcquire::ItemDesc &item) {
1212 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1213 item.Owner->Status == pkgAcquire::Item::StatDone
1217 std::string &error(item.Owner->ErrorText);
1221 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1222 NSArray *fields([description componentsSeparatedByString:@" "]);
1223 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1225 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1226 withObject:[NSArray arrayWithObjects:
1227 [NSString stringWithUTF8String:error.c_str()],
1234 virtual bool Pulse(pkgAcquire *Owner) {
1235 bool value = pkgAcquireStatus::Pulse(Owner);
1238 double(CurrentBytes + CurrentItems) /
1239 double(TotalBytes + TotalItems)
1242 [delegate_ setProgressPercent:percent];
1243 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1246 virtual void Start() {
1247 [delegate_ startProgress];
1250 virtual void Stop() {
1254 /* Progress Delegation {{{ */
1259 _transient id<ProgressDelegate> delegate_;
1263 virtual void Update() {
1264 /*if (abs(Percent - percent_) > 2)
1265 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1269 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1270 [delegate_ setProgressPercent:(Percent / 100)];*/
1280 void setDelegate(id delegate) {
1281 delegate_ = delegate;
1284 id getDelegate() const {
1288 virtual void Done() {
1290 //[delegate_ setProgressPercent:1];
1295 /* Database Interface {{{ */
1296 typedef std::map< unsigned long, _H<Source> > SourceMap;
1298 @interface Database : NSObject {
1304 pkgCacheFile cache_;
1305 pkgDepCache::Policy *policy_;
1306 pkgRecords *records_;
1307 pkgProblemResolver *resolver_;
1308 pkgAcquire *fetcher_;
1310 SPtr<pkgPackageManager> manager_;
1311 pkgSourceList *list_;
1314 CFMutableArrayRef deadSources_;
1315 CFMutableArrayRef packages_;
1317 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1325 std::map<const char *, _H<NSString> > sections_;
1328 + (Database *) sharedInstance;
1331 - (void) _readCydia:(NSNumber *)fd;
1332 - (void) _readStatus:(NSNumber *)fd;
1333 - (void) _readOutput:(NSNumber *)fd;
1337 - (Package *) packageWithName:(NSString *)name;
1339 - (pkgCacheFile &) cache;
1340 - (pkgDepCache::Policy *) policy;
1341 - (pkgRecords *) records;
1342 - (pkgProblemResolver *) resolver;
1343 - (pkgAcquire &) fetcher;
1344 - (pkgSourceList &) list;
1345 - (NSArray *) packages;
1346 - (NSArray *) sources;
1347 - (void) reloadData;
1355 - (void) updateWithStatus:(Status &)status;
1357 - (void) setDelegate:(id)delegate;
1358 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1360 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1364 /* Delegate Helpers {{{ */
1365 @implementation NSObject (ProgressDelegate)
1367 - (void) _setProgressErrorPackage:(NSArray *)args {
1368 [self performSelector:@selector(setProgressError:forPackage:)
1369 withObject:[args objectAtIndex:0]
1370 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1374 - (void) _setProgressErrorTitle:(NSArray *)args {
1375 [self performSelector:@selector(setProgressError:withTitle:)
1376 withObject:[args objectAtIndex:0]
1377 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1381 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1382 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1383 withObject:[NSArray arrayWithObjects:error, title, nil]
1388 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1389 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1391 [self performSelector:@selector(setProgressError:withTitle:)
1393 withObject:(package == nil ? id : [package name])
1400 // Cytore Definitions {{{
1401 struct PackageValue :
1404 Cytore::Offset<PackageValue> next_;
1406 uint32_t index_ : 23;
1407 uint32_t subscribed_ : 1;
1424 Cytore::Offset<PackageValue> packages_[1 << 16];
1427 static Cytore::File<MetaValue> MetaFile_;
1429 // Cytore Helper Functions {{{
1430 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1431 SplitHash nhash = { hashlittle(name, length) };
1433 PackageValue *metadata;
1435 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1436 offset: if (offset->IsNull()) {
1437 *offset = MetaFile_.New<PackageValue>(length + 1);
1438 metadata = &MetaFile_.Get(*offset);
1440 if (metadata == NULL) {
1444 metadata = new PackageValue();
1445 memset(metadata, 0, sizeof(*metadata));
1448 memcpy(metadata->name_, name, length + 1);
1449 metadata->nhash_ = nhash.u16[1];
1451 metadata = &MetaFile_.Get(*offset);
1453 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1454 offset = &metadata->next_;
1462 static void PackageImport(const void *key, const void *value, void *context) {
1463 bool &fail(*reinterpret_cast<bool *>(context));
1466 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1467 NSLog(@"failed to import package %@", key);
1471 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1472 NSDictionary *package((NSDictionary *) value);
1474 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1475 if ([subscribed boolValue] && !metadata->subscribed_)
1476 metadata->subscribed_ = true;
1478 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1479 time_t time([date timeIntervalSince1970]);
1480 if (metadata->first_ > time || metadata->first_ == 0)
1481 metadata->first_ = time;
1484 NSDate *date([package objectForKey:@"LastSeen"]);
1485 NSString *version([package objectForKey:@"LastVersion"]);
1487 if (date != nil && version != nil) {
1488 time_t time([date timeIntervalSince1970]);
1489 if (metadata->last_ < time || metadata->last_ == 0)
1490 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1491 size_t length(strlen(buffer));
1492 uint16_t vhash(hashlittle(buffer, length));
1494 size_t capped(std::min<size_t>(8, length));
1495 char *latest(buffer + length - capped);
1497 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1498 metadata->vhash_ = vhash;
1500 metadata->last_ = time;
1506 /* Source Class {{{ */
1507 @interface Source : NSObject {
1508 CYString depiction_;
1509 CYString description_;
1515 CYString distribution_;
1520 NSString *authority_;
1522 CYString defaultIcon_;
1524 NSDictionary *record_;
1528 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1530 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1532 - (NSString *) depictionForPackage:(NSString *)package;
1533 - (NSString *) supportForPackage:(NSString *)package;
1535 - (NSDictionary *) record;
1539 - (NSString *) distribution;
1540 - (NSString *) type;
1542 - (NSString *) host;
1544 - (NSString *) name;
1545 - (NSString *) description;
1546 - (NSString *) label;
1547 - (NSString *) origin;
1548 - (NSString *) version;
1550 - (NSString *) defaultIcon;
1554 @implementation Source
1558 distribution_.clear();
1561 description_.clear();
1567 defaultIcon_.clear();
1569 if (record_ != nil) {
1579 if (authority_ != nil) {
1580 [authority_ release];
1586 // XXX: this is a very inefficient way to call these deconstructors
1591 + (NSArray *) _attributeKeys {
1592 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1595 - (NSArray *) attributeKeys {
1596 return [[self class] _attributeKeys];
1599 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1600 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1603 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1606 trusted_ = index->IsTrusted();
1608 uri_.set(pool, index->GetURI());
1609 distribution_.set(pool, index->GetDist());
1610 type_.set(pool, index->GetType());
1612 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1613 if (dindex != NULL) {
1615 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1618 pkgTagFile tags(&fd);
1620 pkgTagSection section;
1627 {"default-icon", &defaultIcon_},
1628 {"depiction", &depiction_},
1629 {"description", &description_},
1631 {"origin", &origin_},
1632 {"support", &support_},
1633 {"version", &version_},
1636 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1637 const char *start, *end;
1639 if (section.Find(names[i].name_, start, end)) {
1640 CYString &value(*names[i].value_);
1641 value.set(pool, start, end - start);
1647 record_ = [Sources_ objectForKey:[self key]];
1649 record_ = [record_ retain];
1651 NSURL *url([NSURL URLWithString:uri_]);
1655 host_ = [[host_ lowercaseString] retain];
1660 authority_ = [url path];
1662 if (authority_ != nil)
1663 authority_ = [authority_ retain];
1666 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1667 if ((self = [super init]) != nil) {
1668 [self setMetaIndex:index inPool:pool];
1672 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1673 NSDictionary *lhr = [self record];
1674 NSDictionary *rhr = [source record];
1677 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1679 NSString *lhs = [self name];
1680 NSString *rhs = [source name];
1682 if ([lhs length] != 0 && [rhs length] != 0) {
1683 unichar lhc = [lhs characterAtIndex:0];
1684 unichar rhc = [rhs characterAtIndex:0];
1686 if (isalpha(lhc) && !isalpha(rhc))
1687 return NSOrderedAscending;
1688 else if (!isalpha(lhc) && isalpha(rhc))
1689 return NSOrderedDescending;
1692 return [lhs compare:rhs options:LaxCompareOptions_];
1695 - (NSString *) depictionForPackage:(NSString *)package {
1696 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1699 - (NSString *) supportForPackage:(NSString *)package {
1700 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1703 - (NSDictionary *) record {
1711 - (NSString *) uri {
1715 - (NSString *) distribution {
1716 return distribution_;
1719 - (NSString *) type {
1723 - (NSString *) key {
1724 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1727 - (NSString *) host {
1731 - (NSString *) name {
1732 return origin_.empty() ? authority_ : origin_;
1735 - (NSString *) description {
1736 return description_;
1739 - (NSString *) label {
1740 return label_.empty() ? authority_ : label_;
1743 - (NSString *) origin {
1747 - (NSString *) version {
1751 - (NSString *) defaultIcon {
1752 return defaultIcon_;
1757 /* Relationship Class {{{ */
1758 @interface Relationship : NSObject {
1763 - (NSString *) type;
1765 - (NSString *) name;
1769 @implementation Relationship
1777 - (NSString *) type {
1785 - (NSString *) name {
1792 /* Package Class {{{ */
1793 struct ParsedPackage {
1798 CYString depiction_;
1808 @interface Package : NSObject {
1811 uint32_t essential_ : 1;
1812 uint32_t obsolete_ : 1;
1813 uint32_t ignored_ : 1;
1817 _transient Database *database_;
1819 pkgCache::VerIterator version_;
1820 pkgCache::PkgIterator iterator_;
1821 pkgCache::VerFileIterator file_;
1827 CYString installed_;
1829 const char *section_;
1830 _transient NSString *section$_;
1834 PackageValue *metadata_;
1835 ParsedPackage *parsed_;
1837 NSMutableArray *tags_;
1840 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1841 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1843 - (pkgCache::PkgIterator) iterator;
1846 - (NSString *) section;
1847 - (NSString *) simpleSection;
1849 - (NSString *) longSection;
1850 - (NSString *) shortSection;
1854 - (Address *) maintainer;
1856 - (NSString *) longDescription;
1857 - (NSString *) shortDescription;
1860 - (PackageValue *) metadata;
1863 - (bool) subscribed;
1864 - (bool) setSubscribed:(bool)subscribed;
1868 - (NSString *) latest;
1869 - (NSString *) installed;
1870 - (BOOL) uninstalled;
1873 - (BOOL) upgradableAndEssential:(BOOL)essential;
1876 - (BOOL) unfiltered;
1880 - (BOOL) halfConfigured;
1881 - (BOOL) halfInstalled;
1883 - (NSString *) mode;
1886 - (NSString *) name;
1888 - (NSString *) homepage;
1889 - (NSString *) depiction;
1890 - (Address *) author;
1892 - (NSString *) support;
1894 - (NSArray *) files;
1895 - (NSArray *) warnings;
1896 - (NSArray *) applications;
1898 - (Source *) source;
1900 - (BOOL) matches:(NSString *)text;
1902 - (bool) hasSupportingRole;
1903 - (BOOL) hasTag:(NSString *)tag;
1904 - (NSString *) primaryPurpose;
1905 - (NSArray *) purposes;
1906 - (bool) isCommercial;
1908 - (void) setIndex:(size_t)index;
1910 - (CYString &) cyname;
1912 - (uint32_t) compareBySection:(NSArray *)sections;
1917 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1918 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1919 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1920 - (bool) isVisibleInSection:(NSString *)section;
1921 - (bool) isVisibleInSource:(Source *)source;
1925 uint32_t PackageChangesRadix(Package *self, void *) {
1930 uint32_t timestamp : 30;
1931 uint32_t ignored : 1;
1932 uint32_t upgradable : 1;
1936 bool upgradable([self upgradableAndEssential:YES]);
1937 value.bits.upgradable = upgradable ? 1 : 0;
1940 value.bits.timestamp = 0;
1941 value.bits.ignored = [self ignored] ? 0 : 1;
1942 value.bits.upgradable = 1;
1944 value.bits.timestamp = [self seen] >> 2;
1945 value.bits.ignored = 0;
1946 value.bits.upgradable = 0;
1949 return _not(uint32_t) - value.key;
1952 uint32_t PackagePrefixRadix(Package *self, void *context) {
1953 size_t offset(reinterpret_cast<size_t>(context));
1954 CYString &name([self cyname]);
1956 size_t size(name.size());
1959 char *text(name.data());
1962 if (!isdigit(text[0]))
1966 while (size != digits && isdigit(text[digits]))
1974 if (offset == 0 && zeros != 0) {
1975 memset(data, '0', zeros);
1976 memcpy(data + zeros, text, 4 - zeros);
1978 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1979 if (size <= offset - zeros)
1982 text += offset - zeros;
1983 size -= offset - zeros;
1986 memcpy(data, text, 4);
1988 memcpy(data, text, size);
1989 memset(data + size, 0, 4 - size);
1992 for (size_t i(0); i != 4; ++i)
1993 if (isalpha(data[i]))
2001 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2003 /* XXX: ntohl may be more honest */
2004 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2007 CYString &(*PackageName)(Package *self, SEL sel);
2009 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2010 _profile(PackageNameCompare)
2011 CYString &lhi(PackageName(lhs, @selector(cyname)));
2012 CYString &rhi(PackageName(rhs, @selector(cyname)));
2013 CFStringRef lhn(lhi), rhn(rhi);
2016 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2017 else if (rhn == NULL)
2018 return NSOrderedDescending;
2020 _profile(PackageNameCompare$NumbersLast)
2021 if (!lhi.empty() && !rhi.empty()) {
2022 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2023 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2024 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2025 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2026 return lha ? NSOrderedAscending : NSOrderedDescending;
2030 CFIndex length = CFStringGetLength(lhn);
2032 _profile(PackageNameCompare$Compare)
2033 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2038 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2039 return PackageNameCompare(*lhs, *rhs, context);
2042 struct PackageNameOrdering :
2043 std::binary_function<Package *, Package *, bool>
2045 _finline bool operator ()(Package *lhs, Package *rhs) const {
2046 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2050 @implementation Package
2052 - (NSString *) description {
2053 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2057 if (parsed_ != NULL)
2066 + (NSString *) webScriptNameForSelector:(SEL)selector {
2067 if (selector == @selector(hasTag:))
2073 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2074 return [self webScriptNameForSelector:selector] == nil;
2077 + (NSArray *) _attributeKeys {
2078 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];
2081 - (NSArray *) attributeKeys {
2082 return [[self class] _attributeKeys];
2085 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2086 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2090 if (parsed_ != NULL)
2092 @synchronized (database_) {
2093 if ([database_ era] != era_ || file_.end())
2096 ParsedPackage *parsed(new ParsedPackage);
2099 _profile(Package$parse)
2100 pkgRecords::Parser *parser;
2102 _profile(Package$parse$Lookup)
2103 parser = &[database_ records]->Lookup(file_);
2108 _profile(Package$parse$Find)
2113 {"icon", &parsed->icon_},
2114 {"depiction", &parsed->depiction_},
2115 {"homepage", &parsed->homepage_},
2116 {"website", &website},
2117 {"bugs", &parsed->bugs_},
2118 {"support", &parsed->support_},
2119 {"sponsor", &parsed->sponsor_},
2120 {"author", &parsed->author_},
2123 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2124 const char *start, *end;
2126 if (parser->Find(names[i].name_, start, end)) {
2127 CYString &value(*names[i].value_);
2128 _profile(Package$parse$Value)
2129 value.set(pool_, start, end - start);
2135 _profile(Package$parse$Tagline)
2136 const char *start, *end;
2137 if (parser->ShortDesc(start, end)) {
2138 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2141 while (stop != start && stop[-1] == '\r')
2143 parsed->tagline_.set(pool_, start, stop - start);
2147 _profile(Package$parse$Retain)
2148 if (parsed->homepage_.empty())
2149 parsed->homepage_ = website;
2150 if (parsed->homepage_ == parsed->depiction_)
2151 parsed->homepage_.clear();
2156 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2157 if ((self = [super init]) != nil) {
2158 _profile(Package$initWithVersion)
2161 database_ = database;
2162 era_ = [database era];
2166 pkgCache::PkgIterator iterator(version.ParentPkg());
2167 iterator_ = iterator;
2169 _profile(Package$initWithVersion$Version)
2170 if (!version_.end())
2171 file_ = version_.FileList();
2173 pkgCache &cache([database_ cache]);
2174 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2178 _profile(Package$initWithVersion$Cache)
2179 name_.set(NULL, iterator.Display());
2181 latest_.set(NULL, StripVersion_(version_.VerStr()));
2183 pkgCache::VerIterator current(iterator.CurrentVer());
2185 installed_.set(NULL, StripVersion_(current.VerStr()));
2188 _profile(Package$initWithVersion$Tags)
2189 pkgCache::TagIterator tag(iterator.TagList());
2191 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2193 const char *name(tag.Name());
2194 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2196 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2197 if (strcmp(name + 6, "enduser") == 0)
2199 else if (strcmp(name + 6, "hacker") == 0)
2201 else if (strcmp(name + 6, "developer") == 0)
2203 else if (strcmp(name + 6, "cydia") == 0)
2209 if (strncmp(name, "cydia::", 7) == 0) {
2210 if (strcmp(name + 7, "essential") == 0)
2212 else if (strcmp(name + 7, "obsolete") == 0)
2217 } while (!tag.end());
2221 _profile(Package$initWithVersion$Metadata)
2222 const char *mixed(iterator.Name());
2223 size_t size(strlen(mixed));
2224 char lower[size + 1];
2226 for (size_t i(0); i != size; ++i)
2227 lower[i] = mixed[i] | 0x20;
2230 PackageValue *metadata(PackageFind(lower, size));
2231 metadata_ = metadata;
2233 id_.set(NULL, metadata->name_, size);
2235 const char *latest(version_.VerStr());
2236 size_t length(strlen(latest));
2238 uint16_t vhash(hashlittle(latest, length));
2240 size_t capped(std::min<size_t>(8, length));
2241 latest = latest + length - capped;
2243 if (metadata->first_ == 0)
2244 metadata->first_ = now_;
2246 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2247 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2248 metadata->vhash_ = vhash;
2249 metadata->last_ = now_;
2250 } else if (metadata->last_ == 0)
2251 metadata->last_ = metadata->first_;
2254 _profile(Package$initWithVersion$Section)
2255 section_ = iterator.Section();
2258 _profile(Package$initWithVersion$Flags)
2259 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2260 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2265 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2266 pkgCache::VerIterator version;
2268 _profile(Package$packageWithIterator$GetCandidateVer)
2269 version = [database policy]->GetCandidateVer(iterator);
2277 _profile(Package$packageWithIterator$Allocate)
2278 package = [Package allocWithZone:zone];
2281 _profile(Package$packageWithIterator$Initialize)
2283 initWithVersion:version
2290 _profile(Package$packageWithIterator$Autorelease)
2291 package = [package autorelease];
2297 - (pkgCache::PkgIterator) iterator {
2301 - (NSString *) section {
2302 if (section$_ == nil) {
2303 if (section_ == NULL)
2306 _profile(Package$section$mappedSectionForPointer)
2307 section$_ = [database_ mappedSectionForPointer:section_];
2312 - (NSString *) simpleSection {
2313 if (NSString *section = [self section])
2314 return Simplify(section);
2319 - (NSString *) longSection {
2320 return LocalizeSection([self section]);
2323 - (NSString *) shortSection {
2324 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2327 - (NSString *) uri {
2330 pkgIndexFile *index;
2331 pkgCache::PkgFileIterator file(file_.File());
2332 if (![database_ list].FindIndex(file, index))
2334 return [NSString stringWithUTF8String:iterator_->Path];
2335 //return [NSString stringWithUTF8String:file.Site()];
2336 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2340 - (Address *) maintainer {
2341 @synchronized (database_) {
2342 if ([database_ era] != era_ || file_.end())
2345 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2346 const std::string &maintainer(parser->Maintainer());
2347 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2351 @synchronized (database_) {
2352 if ([database_ era] != era_ || version_.end())
2355 return version_->InstalledSize;
2358 - (NSString *) longDescription {
2359 @synchronized (database_) {
2360 if ([database_ era] != era_ || file_.end())
2363 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2364 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2366 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2367 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2368 if ([lines count] < 2)
2371 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2372 for (size_t i(1), e([lines count]); i != e; ++i) {
2373 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2374 [trimmed addObject:trim];
2377 return [trimmed componentsJoinedByString:@"\n"];
2380 - (NSString *) shortDescription {
2381 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2385 _profile(Package$index)
2386 CFStringRef name((CFStringRef) [self name]);
2387 if (CFStringGetLength(name) == 0)
2389 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2390 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2392 return toupper(character);
2396 - (PackageValue *) metadata {
2401 PackageValue *metadata([self metadata]);
2402 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2405 - (bool) subscribed {
2406 return [self metadata]->subscribed_;
2409 - (bool) setSubscribed:(bool)subscribed {
2410 PackageValue *metadata([self metadata]);
2411 if (metadata->subscribed_ == subscribed)
2413 metadata->subscribed_ = subscribed;
2421 - (NSString *) latest {
2425 - (NSString *) installed {
2429 - (BOOL) uninstalled {
2430 return installed_.empty();
2434 return !version_.end();
2437 - (BOOL) upgradableAndEssential:(BOOL)essential {
2438 _profile(Package$upgradableAndEssential)
2439 pkgCache::VerIterator current(iterator_.CurrentVer());
2441 return essential && essential_;
2443 return !version_.end() && version_ != current;
2447 - (BOOL) essential {
2452 return [database_ cache][iterator_].InstBroken();
2455 - (BOOL) unfiltered {
2456 _profile(Package$unfiltered$obsolete)
2457 if (_unlikely(obsolete_))
2461 _profile(Package$unfiltered$hasSupportingRole)
2462 if (_unlikely(![self hasSupportingRole]))
2470 if (![self unfiltered])
2475 _profile(Package$visible$section)
2476 section = [self section];
2479 _profile(Package$visible$isSectionVisible)
2480 if (section != nil && !isSectionVisible(section))
2488 unsigned char current(iterator_->CurrentState);
2489 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2492 - (BOOL) halfConfigured {
2493 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2496 - (BOOL) halfInstalled {
2497 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2501 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2502 return state.Mode != pkgDepCache::ModeKeep;
2505 - (NSString *) mode {
2506 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2508 switch (state.Mode) {
2509 case pkgDepCache::ModeDelete:
2510 if ((state.iFlags & pkgDepCache::Purge) != 0)
2514 case pkgDepCache::ModeKeep:
2515 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2516 return @"REINSTALL";
2517 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2521 case pkgDepCache::ModeInstall:
2522 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2523 return @"REINSTALL";
2524 else*/ switch (state.Status) {
2526 return @"DOWNGRADE";
2532 return @"NEW_INSTALL";
2543 - (NSString *) name {
2544 return name_.empty() ? id_ : name_;
2547 - (UIImage *) icon {
2548 NSString *section = [self simpleSection];
2551 if (parsed_ != NULL)
2552 if (NSString *href = parsed_->icon_)
2553 if ([href hasPrefix:@"file:///"])
2554 // XXX: correct escaping
2555 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2556 if (icon == nil) if (section != nil)
2557 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2558 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2559 if ([dicon hasPrefix:@"file:///"])
2560 // XXX: correct escaping
2561 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2563 icon = [UIImage applicationImageNamed:@"unknown.png"];
2567 - (NSString *) homepage {
2568 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2571 - (NSString *) depiction {
2572 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2575 - (Address *) sponsor {
2576 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2579 - (Address *) author {
2580 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2583 - (NSString *) support {
2584 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2587 - (NSArray *) files {
2588 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2589 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2592 fin.open([path UTF8String]);
2597 while (std::getline(fin, line))
2598 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2603 - (NSArray *) warnings {
2604 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2605 const char *name(iterator_.Name());
2607 size_t length(strlen(name));
2608 if (length < 2) invalid:
2609 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2610 else for (size_t i(0); i != length; ++i)
2612 /* XXX: technically this is not allowed */
2613 (name[i] < 'A' || name[i] > 'Z') &&
2614 (name[i] < 'a' || name[i] > 'z') &&
2615 (name[i] < '0' || name[i] > '9') &&
2616 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2619 if (strcmp(name, "cydia") != 0) {
2622 bool _private = false;
2625 bool repository = [[self section] isEqualToString:@"Repositories"];
2627 if (NSArray *files = [self files])
2628 for (NSString *file in files)
2629 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2631 else if (!user && [file isEqualToString:@"/User"])
2633 else if (!_private && [file isEqualToString:@"/private"])
2635 else if (!stash && [file isEqualToString:@"/var/stash"])
2638 /* XXX: this is not sensitive enough. only some folders are valid. */
2639 if (cydia && !repository)
2640 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2642 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2644 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2646 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2649 return [warnings count] == 0 ? nil : warnings;
2652 - (NSArray *) applications {
2653 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2655 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2657 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2658 if (NSArray *files = [self files])
2659 for (NSString *file in files)
2660 if (application_r(file)) {
2661 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2662 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2663 if ([id isEqualToString:me])
2666 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2668 display = application_r[1];
2670 NSString *bundle([file stringByDeletingLastPathComponent]);
2671 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2672 if (icon == nil || [icon length] == 0)
2674 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2676 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2677 [applications addObject:application];
2679 [application addObject:id];
2680 [application addObject:display];
2681 [application addObject:url];
2684 return [applications count] == 0 ? nil : applications;
2687 - (Source *) source {
2688 if (source_ == nil) {
2689 @synchronized (database_) {
2690 if ([database_ era] != era_ || file_.end())
2691 source_ = (Source *) [NSNull null];
2693 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2697 return source_ == (Source *) [NSNull null] ? nil : source_;
2700 - (BOOL) matches:(NSString *)text {
2706 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2707 if (range.location != NSNotFound)
2710 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2711 if (range.location != NSNotFound)
2716 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2717 if (range.location != NSNotFound)
2723 - (bool) hasSupportingRole {
2728 if ([Role_ isEqualToString:@"User"])
2732 if ([Role_ isEqualToString:@"Hacker"])
2736 if ([Role_ isEqualToString:@"Developer"])
2741 - (BOOL) hasTag:(NSString *)tag {
2742 return tags_ == nil ? NO : [tags_ containsObject:tag];
2745 - (NSString *) primaryPurpose {
2746 for (NSString *tag in tags_)
2747 if ([tag hasPrefix:@"purpose::"])
2748 return [tag substringFromIndex:9];
2752 - (NSArray *) purposes {
2753 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2754 for (NSString *tag in tags_)
2755 if ([tag hasPrefix:@"purpose::"])
2756 [purposes addObject:[tag substringFromIndex:9]];
2757 return [purposes count] == 0 ? nil : purposes;
2760 - (bool) isCommercial {
2761 return [self hasTag:@"cydia::commercial"];
2764 - (void) setIndex:(size_t)index {
2765 if (metadata_->index_ != index)
2766 metadata_->index_ = index;
2769 - (CYString &) cyname {
2770 return name_.empty() ? id_ : name_;
2773 - (uint32_t) compareBySection:(NSArray *)sections {
2774 NSString *section([self section]);
2775 for (size_t i(0), e([sections count]); i != e; ++i) {
2776 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2780 return _not(uint32_t);
2784 @synchronized (database_) {
2785 pkgProblemResolver *resolver = [database_ resolver];
2786 resolver->Clear(iterator_);
2788 pkgCacheFile &cache([database_ cache]);
2789 cache->SetReInstall(iterator_, false);
2790 cache->MarkKeep(iterator_, false);
2794 @synchronized (database_) {
2795 pkgProblemResolver *resolver = [database_ resolver];
2796 resolver->Clear(iterator_);
2797 resolver->Protect(iterator_);
2799 pkgCacheFile &cache([database_ cache]);
2800 cache->SetReInstall(iterator_, false);
2801 cache->MarkInstall(iterator_, false);
2803 pkgDepCache::StateCache &state((*cache)[iterator_]);
2804 if (!state.Install())
2805 cache->SetReInstall(iterator_, true);
2809 @synchronized (database_) {
2810 pkgProblemResolver *resolver = [database_ resolver];
2811 resolver->Clear(iterator_);
2812 resolver->Remove(iterator_);
2813 resolver->Protect(iterator_);
2815 pkgCacheFile &cache([database_ cache]);
2816 cache->SetReInstall(iterator_, false);
2817 cache->MarkDelete(iterator_, true);
2820 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2821 _profile(Package$isUnfilteredAndSearchedForBy)
2824 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2825 value &= [self unfiltered];
2828 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2829 value &= [self matches:search];
2836 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2837 if ([search length] == 0)
2840 _profile(Package$isUnfilteredAndSelectedForBy)
2843 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2844 value &= [self unfiltered];
2847 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2848 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2855 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2856 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2859 - (bool) isVisibleInSection:(NSString *)name {
2860 NSString *section([self section]);
2864 section == nil && [name length] == 0 ||
2865 [name isEqualToString:section]
2866 ) && [self visible];
2869 - (bool) isVisibleInSource:(Source *)source {
2870 return [self source] == source && [self visible];
2875 /* Section Class {{{ */
2876 @interface Section : NSObject {
2881 NSString *localized_;
2884 - (NSComparisonResult) compareByLocalized:(Section *)section;
2885 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2886 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2887 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2888 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2889 - (NSString *) name;
2896 - (void) addToCount;
2898 - (void) setCount:(size_t)count;
2899 - (NSString *) localized;
2903 @implementation Section
2907 if (localized_ != nil)
2908 [localized_ release];
2912 - (NSComparisonResult) compareByLocalized:(Section *)section {
2913 NSString *lhs(localized_);
2914 NSString *rhs([section localized]);
2916 /*if ([lhs length] != 0 && [rhs length] != 0) {
2917 unichar lhc = [lhs characterAtIndex:0];
2918 unichar rhc = [rhs characterAtIndex:0];
2920 if (isalpha(lhc) && !isalpha(rhc))
2921 return NSOrderedAscending;
2922 else if (!isalpha(lhc) && isalpha(rhc))
2923 return NSOrderedDescending;
2926 return [lhs compare:rhs options:LaxCompareOptions_];
2929 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2930 if ((self = [self initWithName:name localize:NO]) != nil) {
2931 if (localized != nil)
2932 localized_ = [localized retain];
2936 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2937 return [self initWithName:name row:0 localize:localize];
2940 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2941 if ((self = [super init]) != nil) {
2942 name_ = [name retain];
2946 localized_ = [LocalizeSection(name_) retain];
2950 /* XXX: localize the index thingees */
2951 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2952 if ((self = [super init]) != nil) {
2953 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2959 - (NSString *) name {
2979 - (void) addToCount {
2983 - (void) setCount:(size_t)count {
2987 - (NSString *) localized {
2994 static NSString *Colon_;
2995 static NSString *Elision_;
2996 static NSString *Error_;
2997 static NSString *Warning_;
2999 /* Database Implementation {{{ */
3000 @implementation Database
3002 + (Database *) sharedInstance {
3003 static Database *instance;
3004 if (instance == nil)
3005 instance = [[Database alloc] init];
3013 - (void) releasePackages {
3014 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3015 CFArrayRemoveAllValues(packages_);
3019 // XXX: actually implement this thing
3022 CFRelease(deadSources_);
3023 [self releasePackages];
3024 apr_pool_destroy(pool_);
3025 NSRecycleZone(zone_);
3029 - (void) _readCydia:(NSNumber *)fd { _pooled
3030 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3031 std::istream is(&ib);
3034 static Pcre finish_r("^finish:([^:]*)$");
3036 while (std::getline(is, line)) {
3037 const char *data(line.c_str());
3038 size_t size = line.size();
3039 lprintf("C:%s\n", data);
3041 if (finish_r(data, size)) {
3042 NSString *finish = finish_r[1];
3043 int index = [Finishes_ indexOfObject:finish];
3044 if (index != INT_MAX && index > Finish_)
3052 - (void) _readStatus:(NSNumber *)fd { _pooled
3053 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3054 std::istream is(&ib);
3057 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3058 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3060 while (std::getline(is, line)) {
3061 const char *data(line.c_str());
3062 size_t size(line.size());
3063 lprintf("S:%s\n", data);
3065 if (conffile_r(data, size)) {
3066 [delegate_ setConfigurationData:conffile_r[1]];
3067 } else if (strncmp(data, "status: ", 8) == 0) {
3068 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3069 [delegate_ setProgressTitle:string];
3070 } else if (pmstatus_r(data, size)) {
3071 std::string type([pmstatus_r[1] UTF8String]);
3072 NSString *id = pmstatus_r[2];
3074 float percent([pmstatus_r[3] floatValue]);
3075 [delegate_ setProgressPercent:(percent / 100)];
3077 NSString *string = pmstatus_r[4];
3079 if (type == "pmerror")
3080 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3081 withObject:[NSArray arrayWithObjects:string, id, nil]
3084 else if (type == "pmstatus") {
3085 [delegate_ setProgressTitle:string];
3086 } else if (type == "pmconffile")
3087 [delegate_ setConfigurationData:string];
3089 lprintf("E:unknown pmstatus\n");
3091 lprintf("E:unknown status\n");
3097 - (void) _readOutput:(NSNumber *)fd { _pooled
3098 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3099 std::istream is(&ib);
3102 while (std::getline(is, line)) {
3103 lprintf("O:%s\n", line.c_str());
3104 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3114 - (Package *) packageWithName:(NSString *)name {
3115 @synchronized (self) {
3116 if (static_cast<pkgDepCache *>(cache_) == NULL)
3118 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3119 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3123 if ((self = [super init]) != nil) {
3130 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3131 apr_pool_create(&pool_, NULL);
3133 size_t capacity(MetaFile_->active_);
3139 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3140 deadSources_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
3144 _assert(pipe(fds) != -1);
3147 _config->Set("APT::Keep-Fds::", cydiafd_);
3148 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3151 detachNewThreadSelector:@selector(_readCydia:)
3153 withObject:[NSNumber numberWithInt:fds[0]]
3156 _assert(pipe(fds) != -1);
3160 detachNewThreadSelector:@selector(_readStatus:)
3162 withObject:[NSNumber numberWithInt:fds[0]]
3165 _assert(pipe(fds) != -1);
3166 _assert(dup2(fds[0], 0) != -1);
3167 _assert(close(fds[0]) != -1);
3169 input_ = fdopen(fds[1], "a");
3171 _assert(pipe(fds) != -1);
3172 _assert(dup2(fds[1], 1) != -1);
3173 _assert(close(fds[1]) != -1);
3176 detachNewThreadSelector:@selector(_readOutput:)
3178 withObject:[NSNumber numberWithInt:fds[0]]
3183 - (pkgCacheFile &) cache {
3187 - (pkgDepCache::Policy *) policy {
3191 - (pkgRecords *) records {
3195 - (pkgProblemResolver *) resolver {
3199 - (pkgAcquire &) fetcher {
3203 - (pkgSourceList &) list {
3207 - (NSArray *) packages {
3208 return (NSArray *) packages_;
3211 - (NSArray *) sources {
3212 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3213 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3214 [sources addObject:i->second];
3215 [sources addObjectsFromArray:(NSArray *)deadSources_];
3219 - (NSArray *) issues {
3220 if (cache_->BrokenCount() == 0)
3223 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3225 for (Package *package in [self packages]) {
3226 if (![package broken])
3228 pkgCache::PkgIterator pkg([package iterator]);
3230 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3231 [entry addObject:[package name]];
3232 [issues addObject:entry];
3234 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3238 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3239 pkgCache::DepIterator start;
3240 pkgCache::DepIterator end;
3241 dep.GlobOr(start, end); // ++dep
3243 if (!cache_->IsImportantDep(end))
3245 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3248 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3249 [entry addObject:failure];
3250 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3252 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3253 if (Package *package = [self packageWithName:name])
3254 name = [package name];
3255 [failure addObject:name];
3257 pkgCache::PkgIterator target(start.TargetPkg());
3258 if (target->ProvidesList != 0)
3259 [failure addObject:@"?"];
3261 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3263 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3264 else if (!cache_[target].CandidateVerIter(cache_).end())
3265 [failure addObject:@"-"];
3266 else if (target->ProvidesList == 0)
3267 [failure addObject:@"!"];
3269 [failure addObject:@"%"];
3273 if (start.TargetVer() != 0)
3274 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3285 - (bool) popErrorWithTitle:(NSString *)title {
3287 std::string message;
3289 while (!_error->empty()) {
3291 bool warning(!_error->PopMessage(error));
3295 size_t size(error.size());
3296 if (size == 0 || error[size - 1] != '\n')
3298 error.resize(size - 1);
3300 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3302 if (!message.empty())
3307 if (fatal && !message.empty())
3308 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3313 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3314 return [self popErrorWithTitle:title] || !success;
3317 - (void) reloadData { CYPoolStart() {
3318 @synchronized (self) {
3321 [self releasePackages];
3324 CFArrayRemoveAllValues(deadSources_);
3344 apr_pool_clear(pool_);
3346 NSRecycleZone(zone_);
3347 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3349 int chk(creat("/tmp/cydia.chk", 0644));
3353 NSString *title(UCLocalize("DATABASE"));
3356 if (!cache_.Open(progress_, true)) { pop:
3358 bool warning(!_error->PopMessage(error));
3359 lprintf("cache_.Open():[%s]\n", error.c_str());
3361 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3362 [delegate_ repairWithSelector:@selector(configure)];
3363 else if (error == "The package lists or status file could not be parsed or opened.")
3364 [delegate_ repairWithSelector:@selector(update)];
3365 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3366 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3367 // else if (error == "The list of sources could not be read.")
3369 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3378 unlink("/tmp/cydia.chk");
3380 now_ = [[NSDate date] timeIntervalSince1970];
3382 policy_ = new pkgDepCache::Policy();
3383 records_ = new pkgRecords(cache_);
3384 resolver_ = new pkgProblemResolver(cache_);
3385 fetcher_ = new pkgAcquire(&status_);
3388 list_ = new pkgSourceList();
3389 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3392 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3393 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3397 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3400 if (cache_->BrokenCount() != 0) {
3401 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3404 if (cache_->BrokenCount() != 0) {
3405 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3409 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3413 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3415 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3416 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3417 // XXX: this could be more intelligent
3418 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3419 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3420 if (!cached.end()) {
3421 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3426 CFArrayAppendValue(deadSources_, [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3430 /*std::vector<Package *> packages;
3431 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3432 [packages_ release];
3437 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3438 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3439 //packages.push_back(package);
3440 CFArrayAppendValue(packages_, [package retain]);
3444 /*if (packages.empty())
3445 packages_ = [[NSArray alloc] init];
3447 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3450 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3451 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3452 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3460 /*if (!packages.empty())
3461 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3462 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3464 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3466 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3468 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3472 size_t count(CFArrayGetCount(packages_));
3473 MetaFile_->active_ = count;
3475 for (size_t index(0); index != count; ++index)
3476 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3480 } } CYPoolEnd() _trace(); }
3483 @synchronized (self) {
3485 resolver_ = new pkgProblemResolver(cache_);
3487 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3488 if (!cache_[iterator].Keep()) {
3489 cache_->MarkKeep(iterator, false);
3490 cache_->SetReInstall(iterator, false);
3495 - (void) configure {
3496 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3498 system([dpkg UTF8String]);
3503 // XXX: I don't remember this condition
3508 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3510 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3512 if ([self popErrorWithTitle:title])
3516 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3519 public pkgArchiveCleaner
3522 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3527 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3534 fetcher_->Shutdown();
3536 pkgRecords records(cache_);
3538 lock_ = new FileFd();
3539 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3541 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3543 if ([self popErrorWithTitle:title])
3547 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3550 manager_ = (_system->CreatePM(cache_));
3551 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3558 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3560 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3562 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3564 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3565 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3568 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3573 [CydiaApp retainNetworkActivityIndicator];
3575 bool failed = false;
3576 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3577 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3579 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3582 std::string uri = (*item)->DescURI();
3583 std::string error = (*item)->ErrorText;
3585 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3588 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3589 withObject:[NSArray arrayWithObjects:
3590 [NSString stringWithUTF8String:error.c_str()],
3596 [CydiaApp releaseNetworkActivityIndicator];
3604 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3606 if (_error->PendingError()) {
3611 if (result == pkgPackageManager::Failed) {
3616 if (result != pkgPackageManager::Completed) {
3621 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3623 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3625 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3626 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3629 if (![before isEqualToArray:after])
3634 NSString *title(UCLocalize("UPGRADE"));
3635 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3641 [self updateWithStatus:status_];
3644 - (void) updateWithStatus:(Status &)status {
3645 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3646 NSString *title(UCLocalize("REFRESHING_DATA"));
3649 if (!list.ReadMainList())
3650 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3653 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3654 if ([self popErrorWithTitle:title])
3657 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3658 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3659 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3661 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3665 - (void) setDelegate:(id)delegate {
3666 delegate_ = delegate;
3667 status_.setDelegate(delegate);
3668 progress_.setDelegate(delegate);
3671 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3672 SourceMap::const_iterator i(sources_.find(file->ID));
3673 return i == sources_.end() ? nil : i->second;
3676 - (NSString *) mappedSectionForPointer:(const char *)section {
3677 _H<NSString> *mapped;
3679 _profile(Database$mappedSectionForPointer$Cache)
3680 mapped = §ions_[section];
3683 if (*mapped == NULL) {
3684 size_t length(strlen(section));
3685 char spaced[length + 1];
3687 _profile(Database$mappedSectionForPointer$Replace)
3688 for (size_t index(0); index != length; ++index)
3689 spaced[index] = section[index] == '_' ? ' ' : section[index];
3690 spaced[length] = '\0';
3695 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3696 string = [NSString stringWithUTF8String:spaced];
3699 _profile(Database$mappedSectionForPointer$Map)
3700 string = [SectionMap_ objectForKey:string] ?: string;
3710 /* Web Scripting {{{ */
3711 @interface CydiaObject : NSObject {
3713 _transient id delegate_;
3716 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3719 @implementation CydiaObject
3722 [indirect_ release];
3726 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3727 if ((self = [super init]) != nil) {
3728 indirect_ = [indirect retain];
3732 - (void) setDelegate:(id)delegate {
3733 delegate_ = delegate;
3736 + (NSArray *) _attributeKeys {
3737 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3740 - (NSArray *) attributeKeys {
3741 return [[self class] _attributeKeys];
3744 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3745 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3748 - (NSString *) device {
3749 return [[UIDevice currentDevice] uniqueIdentifier];
3752 #if 0 // XXX: implement!
3753 - (NSString *) mac {
3754 if (![indirect_ promptForSensitive:@"Mac Address"])
3758 - (NSString *) serial {
3759 if (![indirect_ promptForSensitive:@"Serial #"])
3763 - (NSString *) firewire {
3764 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3768 - (NSString *) imei {
3769 if (![indirect_ promptForSensitive:@"IMEI"])
3774 + (NSString *) webScriptNameForSelector:(SEL)selector {
3775 if (selector == @selector(close))
3777 else if (selector == @selector(getInstalledPackages))
3778 return @"getInstalledPackages";
3779 else if (selector == @selector(getPackageById:))
3780 return @"getPackageById";
3781 else if (selector == @selector(installPackages:))
3782 return @"installPackages";
3783 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3784 return @"setButtonImage";
3785 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3786 return @"setButtonTitle";
3787 else if (selector == @selector(setPopupHook:))
3788 return @"setPopupHook";
3789 else if (selector == @selector(setSpecial:))
3790 return @"setSpecial";
3791 else if (selector == @selector(setToken:))
3793 else if (selector == @selector(setViewportWidth:))
3794 return @"setViewportWidth";
3795 else if (selector == @selector(supports:))
3797 else if (selector == @selector(stringWithFormat:arguments:))
3799 else if (selector == @selector(localizedStringForKey:value:table:))
3801 else if (selector == @selector(du:))
3803 else if (selector == @selector(statfs:))
3809 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3810 return [self webScriptNameForSelector:selector] == nil;
3813 - (BOOL) supports:(NSString *)feature {
3814 return [feature isEqualToString:@"window.open"];
3817 - (NSArray *) getInstalledPackages {
3818 NSArray *packages([[Database sharedInstance] packages]);
3819 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3820 for (Package *package in packages)
3821 if ([package installed] != nil)
3822 [installed addObject:package];
3826 - (Package *) getPackageById:(NSString *)id {
3827 Package *package([[Database sharedInstance] packageWithName:id]);
3832 - (NSArray *) statfs:(NSString *)path {
3835 if (path == nil || statfs([path UTF8String], &stat) == -1)
3838 return [NSArray arrayWithObjects:
3839 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3840 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3841 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3845 - (NSNumber *) du:(NSString *)path {
3846 NSNumber *value(nil);
3849 _assert(pipe(fds) != -1);
3851 pid_t pid(ExecFork());
3853 _assert(dup2(fds[1], 1) != -1);
3854 _assert(close(fds[0]) != -1);
3855 _assert(close(fds[1]) != -1);
3856 /* XXX: this should probably not use du */
3857 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3862 _assert(close(fds[1]) != -1);
3864 if (FILE *du = fdopen(fds[0], "r")) {
3866 while (fgets(line, sizeof(line), du) != NULL) {
3867 size_t length(strlen(line));
3868 while (length != 0 && line[length - 1] == '\n')
3869 line[--length] = '\0';
3870 if (char *tab = strchr(line, '\t')) {
3872 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3877 } else _assert(close(fds[0]));
3881 if (waitpid(pid, &status, 0) == -1)
3884 else _assert(false);
3893 - (void) installPackages:(NSArray *)packages {
3894 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3897 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3898 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3901 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3902 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3905 - (void) setSpecial:(id)function {
3906 [indirect_ setSpecial:function];
3909 - (void) setToken:(NSString *)token {
3912 Token_ = [token retain];
3914 [Metadata_ setObject:Token_ forKey:@"Token"];
3918 - (void) setPopupHook:(id)function {
3919 [indirect_ setPopupHook:function];
3922 - (void) setViewportWidth:(float)width {
3923 [indirect_ setViewportWidth:width];
3926 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3927 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3928 unsigned count([arguments count]);
3930 for (unsigned i(0); i != count; ++i)
3931 values[i] = [arguments objectAtIndex:i];
3932 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3935 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3936 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3938 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3940 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3946 /* @ Loading... Indicator {{{ */
3947 @interface CYLoadingIndicator : UIView {
3948 UIActivityIndicatorView *spinner_;
3953 @property (readonly, nonatomic) UILabel *label;
3954 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
3958 @implementation CYLoadingIndicator
3960 - (id)initWithFrame:(CGRect)frame {
3961 if ((self = [super initWithFrame:frame])) {
3962 container_ = [[[UIView alloc] init] autorelease];
3963 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
3965 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
3966 [spinner_ startAnimating];
3967 [container_ addSubview:spinner_];
3969 label_ = [[[UILabel alloc] init] autorelease];
3970 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
3971 [label_ setBackgroundColor:[UIColor clearColor]];
3972 [label_ setTextColor:[UIColor blackColor]];
3973 [label_ setShadowColor:[UIColor whiteColor]];
3974 [label_ setShadowOffset:CGSizeMake(0, 1)];
3975 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
3976 [container_ addSubview:label_];
3978 CGSize viewsize = frame.size;
3979 CGSize spinnersize = [spinner_ bounds].size;
3980 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
3981 float bothwidth = spinnersize.width + textsize.width + 5.0f;
3983 CGRect containrect = {
3984 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
3985 CGSizeMake(bothwidth, spinnersize.height)
3988 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
3996 [container_ setFrame:containrect];
3997 [spinner_ setFrame:spinrect];
3998 [label_ setFrame:textrect];
3999 [self addSubview:container_];
4005 - (UILabel *)label { return label_; }
4006 - (UIActivityIndicatorView *)activityIndicatorView { return spinner_; }
4010 /* Emulated Loading Controller {{{ */
4011 @interface CYEmulatedLoadingController : CYViewController {
4012 CYLoadingIndicator *indicator_;
4014 UINavigationBar *navbar_;
4018 @implementation CYEmulatedLoadingController
4021 [self releaseSubviews];
4027 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4028 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4030 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4031 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4032 [[self view] addSubview:indicator_];
4034 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4035 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4036 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4037 [[self view] addSubview:tabbar_];
4039 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4040 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4041 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4042 [[self view] addSubview:navbar_];
4045 - (void) releaseSubviews {
4046 [indicator_ release];
4059 /* Cydia Browser Controller {{{ */
4060 @interface CYBrowserController : BrowserController {
4061 CydiaObject *cydia_;
4066 @implementation CYBrowserController
4073 - (NSURL *) navigationURL {
4074 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4077 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4080 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4081 [super webView:view didClearWindowObject:window forFrame:frame];
4083 WebDataSource *source([frame dataSource]);
4084 NSURLResponse *response([source response]);
4086 NSURL *url([response URL]);
4087 NSString *scheme([url scheme]);
4088 NSString *host([url host]);
4090 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4091 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4092 NSDictionary *headers([http allHeaderFields]);
4093 [self setHeaders:headers forHost:host];
4097 [host isEqualToString:@"cydia.saurik.com"] ||
4098 [host hasSuffix:@".cydia.saurik.com"] ||
4099 [scheme isEqualToString:@"file"]
4101 [window setValue:cydia_ forKey:@"cydia"];
4104 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4105 if (System_ != NULL)
4106 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4107 if (Machine_ != NULL)
4108 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4110 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4112 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4115 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4116 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4117 [self _setMoreHeaders:copy];
4121 - (void) setDelegate:(id)delegate {
4122 [super setDelegate:delegate];
4123 [cydia_ setDelegate:delegate];
4127 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4128 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4130 WebView *webview([[webview_ _documentView] webView]);
4132 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4134 NSString *application = package == nil ? @"Cydia" : [NSString
4135 stringWithFormat:@"Cydia/%@",
4140 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4142 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4143 if (Product_ != nil)
4144 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4146 [webview setApplicationNameForUserAgent:application];
4153 /* Confirmation Controller {{{ */
4154 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4155 if (!iterator.end())
4156 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4157 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4159 pkgCache::PkgIterator package(dep.TargetPkg());
4162 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4169 @protocol ConfirmationControllerDelegate
4170 - (void) cancelAndClear:(bool)clear;
4171 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4175 @interface ConfirmationController : CYBrowserController {
4176 _transient Database *database_;
4177 UIAlertView *essential_;
4184 - (id) initWithDatabase:(Database *)database;
4188 @implementation ConfirmationController
4195 if (essential_ != nil)
4196 [essential_ release];
4200 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4201 NSString *context([alert context]);
4203 if ([context isEqualToString:@"remove"]) {
4204 if (button == [alert cancelButtonIndex]) {
4205 [self dismissModalViewControllerAnimated:YES];
4206 } else if (button == [alert firstOtherButtonIndex]) {
4209 [delegate_ confirmWithNavigationController:[self navigationController]];
4212 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4213 } else if ([context isEqualToString:@"unable"]) {
4214 [self dismissModalViewControllerAnimated:YES];
4215 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4217 [super alertView:alert clickedButtonAtIndex:button];
4221 - (void) _doContinue {
4222 [self dismissModalViewControllerAnimated:YES];
4223 [delegate_ cancelAndClear:NO];
4226 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4227 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4231 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4232 [super webView:view didClearWindowObject:window forFrame:frame];
4233 [window setValue:changes_ forKey:@"changes"];
4234 [window setValue:issues_ forKey:@"issues"];
4235 [window setValue:sizes_ forKey:@"sizes"];
4236 [window setValue:self forKey:@"queue"];
4239 - (id) initWithDatabase:(Database *)database {
4240 if ((self = [super init]) != nil) {
4241 database_ = database;
4243 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4245 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4246 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4247 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4248 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4249 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4253 pkgDepCache::Policy *policy([database_ policy]);
4255 pkgCacheFile &cache([database_ cache]);
4256 NSArray *packages = [database_ packages];
4257 for (Package *package in packages) {
4258 pkgCache::PkgIterator iterator = [package iterator];
4259 pkgDepCache::StateCache &state(cache[iterator]);
4261 NSString *name([package name]);
4263 if (state.NewInstall())
4264 [installing addObject:name];
4265 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4266 [reinstalling addObject:name];
4267 else if (state.Upgrade())
4268 [upgrading addObject:name];
4269 else if (state.Downgrade())
4270 [downgrading addObject:name];
4271 else if (state.Delete()) {
4272 if ([package essential])
4274 [removing addObject:name];
4277 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4278 substrate_ |= DepSubstrate(iterator.CurrentVer());
4283 else if (Advanced_) {
4284 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4286 essential_ = [[UIAlertView alloc]
4287 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4288 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4290 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4291 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4294 [essential_ setContext:@"remove"];
4296 essential_ = [[UIAlertView alloc]
4297 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4298 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4300 cancelButtonTitle:UCLocalize("OKAY")
4301 otherButtonTitles:nil
4304 [essential_ setContext:@"unable"];
4307 changes_ = [[NSArray alloc] initWithObjects:
4315 issues_ = [database_ issues];
4317 issues_ = [issues_ retain];
4319 sizes_ = [[NSArray alloc] initWithObjects:
4320 SizeString([database_ fetcher].FetchNeeded()),
4321 SizeString([database_ fetcher].PartialPresent()),
4324 [self loadURL:[NSURL URLWithString:CydiaURL(@"ui/confirm/")]];
4326 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4327 initWithTitle:UCLocalize("CANCEL")
4328 style:UIBarButtonItemStylePlain
4330 action:@selector(cancelButtonClicked)
4335 - (void) applyRightButton {
4336 #if !AlwaysReload && !IgnoreInstall
4337 if (issues_ == nil && ![self isLoading])
4338 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4339 initWithTitle:UCLocalize("CONFIRM")
4340 style:UIBarButtonItemStyleDone
4342 action:@selector(confirmButtonClicked)
4345 [super applyRightButton];
4347 [[self navigationItem] setRightBarButtonItem:nil];
4351 - (void) cancelButtonClicked {
4352 [self dismissModalViewControllerAnimated:YES];
4353 [delegate_ cancelAndClear:YES];
4357 - (void) confirmButtonClicked {
4361 if (essential_ != nil)
4366 [delegate_ confirmWithNavigationController:[self navigationController]];
4374 /* Progress Data {{{ */
4375 @interface ProgressData : NSObject {
4377 // XXX: should these really both be _transient?
4378 _transient id target_;
4379 _transient id object_;
4382 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4389 @implementation ProgressData
4391 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4392 if ((self = [super init]) != nil) {
4393 selector_ = selector;
4413 /* Progress Controller {{{ */
4414 @interface ProgressController : CYViewController <
4415 ConfigurationDelegate,
4418 _transient Database *database_;
4419 UIProgressBar *progress_;
4420 UITextView *output_;
4421 UITextLabel *status_;
4422 UIPushButton *close_;
4424 SHA1SumValue springlist_;
4425 SHA1SumValue notifyconf_;
4429 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4431 - (void) _retachThread;
4432 - (void) _detachNewThreadData:(ProgressData *)data;
4433 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4439 @protocol ProgressControllerDelegate
4440 - (void) progressControllerIsComplete:(ProgressController *)sender;
4443 @implementation ProgressController
4446 [database_ setDelegate:nil];
4447 [progress_ release];
4456 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4457 if ((self = [super init]) != nil) {
4458 database_ = database;
4459 [database_ setDelegate:self];
4460 delegate_ = delegate;
4462 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4464 progress_ = [[UIProgressBar alloc] init];
4465 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4466 [progress_ setStyle:0];
4468 status_ = [[UITextLabel alloc] init];
4469 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4470 [status_ setColor:[UIColor whiteColor]];
4471 [status_ setBackgroundColor:[UIColor clearColor]];
4472 [status_ setCentersHorizontally:YES];
4473 //[status_ setFont:font];
4475 output_ = [[UITextView alloc] init];
4476 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4477 //[output_ setTextFont:@"Courier New"];
4478 [output_ setFont:[[output_ font] fontWithSize:12]];
4479 [output_ setTextColor:[UIColor whiteColor]];
4480 [output_ setBackgroundColor:[UIColor clearColor]];
4481 [output_ setMarginTop:0];
4482 [output_ setAllowsRubberBanding:YES];
4483 [output_ setEditable:NO];
4484 [[self view] addSubview:output_];
4486 close_ = [[UIPushButton alloc] init];
4487 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4488 [close_ setAutosizesToFit:NO];
4489 [close_ setDrawsShadow:YES];
4490 [close_ setStretchBackground:YES];
4491 [close_ setEnabled:YES];
4492 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4493 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4494 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4495 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4499 - (void) positionViews {
4500 CGRect bounds = [[self view] bounds];
4501 CGSize prgsize = [UIProgressBar defaultSize];
4504 (bounds.size.width - prgsize.width) / 2,
4505 bounds.size.height - prgsize.height - 20
4508 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4510 [progress_ setFrame:prgrect];
4511 [status_ setFrame:CGRectMake(
4513 bounds.size.height - prgsize.height - 50,
4514 bounds.size.width - 20,
4517 [output_ setFrame:CGRectMake(
4520 bounds.size.width - 20,
4521 bounds.size.height - 96
4523 [close_ setFrame:CGRectMake(
4524 (bounds.size.width - closewidth) / 2,
4525 bounds.size.height - prgsize.height - 50,
4531 - (void) viewWillAppear:(BOOL)animated {
4532 [super viewDidAppear:animated];
4533 [[self navigationItem] setHidesBackButton:YES];
4534 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4536 [self positionViews];
4539 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4540 [self positionViews];
4543 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4544 NSString *context([alert context]);
4546 if ([context isEqualToString:@"conffile"]) {
4547 FILE *input = [database_ input];
4548 if (button == [alert cancelButtonIndex])
4549 fprintf(input, "N\n");
4550 else if (button == [alert firstOtherButtonIndex])
4551 fprintf(input, "Y\n");
4556 - (void) closeButtonPushed {
4559 UpdateExternalStatus(0);
4563 [self dismissModalViewControllerAnimated:YES];
4567 [delegate_ terminateWithSuccess];
4568 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4569 [delegate_ suspendWithAnimation:YES];
4571 [delegate_ suspend];*/
4583 system("/usr/bin/sbreload");
4589 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4590 SBReboot(SBSSpringBoardServerPort());
4592 reboot2(RB_AUTOBOOT);
4597 - (void) _retachThread {
4598 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4600 [[self view] addSubview:close_];
4601 [progress_ removeFromSuperview];
4602 [status_ removeFromSuperview];
4604 [database_ popErrorWithTitle:title_];
4605 [delegate_ progressControllerIsComplete:self];
4609 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4612 MMap mmap(file, MMap::ReadOnly);
4614 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4615 if (!(notifyconf_ == sha1.Result()))
4622 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4625 MMap mmap(file, MMap::ReadOnly);
4627 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4628 if (!(springlist_ == sha1.Result()))
4634 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4635 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4636 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4637 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4638 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4642 system("su -c /usr/bin/uicache mobile");
4645 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4647 [delegate_ setStatusBarShowsProgress:NO];
4650 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4651 [[data target] performSelector:[data selector] withObject:[data object]];
4652 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4655 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4656 UpdateExternalStatus(1);
4663 title_ = [title retain];
4665 [[self navigationItem] setTitle:title_];
4667 [status_ setText:nil];
4668 [output_ setText:@""];
4669 [progress_ setProgress:0];
4671 [close_ removeFromSuperview];
4672 [[self view] addSubview:progress_];
4673 [[self view] addSubview:status_];
4675 [delegate_ setStatusBarShowsProgress:YES];
4680 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4683 MMap mmap(file, MMap::ReadOnly);
4685 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4686 notifyconf_ = sha1.Result();
4692 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4695 MMap mmap(file, MMap::ReadOnly);
4697 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4698 springlist_ = sha1.Result();
4703 detachNewThreadSelector:@selector(_detachNewThreadData:)
4705 withObject:[[[ProgressData alloc]
4706 initWithSelector:selector
4713 - (void) repairWithSelector:(SEL)selector {
4715 detachNewThreadSelector:selector
4718 title:UCLocalize("REPAIRING")
4722 - (void) setConfigurationData:(NSString *)data {
4724 performSelectorOnMainThread:@selector(_setConfigurationData:)
4730 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4731 CYAlertView *sheet([[[CYAlertView alloc]
4733 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4734 defaultButtonIndex:0
4737 [sheet setMessage:error];
4738 [sheet yieldToPopupAlertAnimated:YES];
4742 - (void) setProgressTitle:(NSString *)title {
4744 performSelectorOnMainThread:@selector(_setProgressTitle:)
4750 - (void) setProgressPercent:(float)percent {
4752 performSelectorOnMainThread:@selector(_setProgressPercent:)
4753 withObject:[NSNumber numberWithFloat:percent]
4758 - (void) startProgress {
4761 - (void) addProgressOutput:(NSString *)output {
4763 performSelectorOnMainThread:@selector(_addProgressOutput:)
4769 - (bool) isCancelling:(size_t)received {
4773 - (void) _setConfigurationData:(NSString *)data {
4774 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4776 if (!conffile_r(data)) {
4777 lprintf("E:invalid conffile\n");
4781 NSString *ofile = conffile_r[1];
4782 //NSString *nfile = conffile_r[2];
4784 UIAlertView *alert = [[[UIAlertView alloc]
4785 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4786 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4788 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4789 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4790 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4794 [alert setContext:@"conffile"];
4798 - (void) _setProgressTitle:(NSString *)title {
4799 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4800 for (size_t i(0), e([words count]); i != e; ++i) {
4801 NSString *word([words objectAtIndex:i]);
4802 if (Package *package = [database_ packageWithName:word])
4803 [words replaceObjectAtIndex:i withObject:[package name]];
4806 [status_ setText:[words componentsJoinedByString:@" "]];
4809 - (void) _setProgressPercent:(NSNumber *)percent {
4810 [progress_ setProgress:[percent floatValue]];
4813 - (void) _addProgressOutput:(NSString *)output {
4814 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4815 CGSize size = [output_ contentSize];
4816 CGPoint offset = [output_ contentOffset];
4817 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4818 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4819 [output_ scrollRectToVisible:rect animated:YES];
4823 - (BOOL) isRunning {
4830 /* Cell Content View {{{ */
4831 @protocol ContentDelegate
4832 - (void) drawContentRect:(CGRect)rect;
4835 @interface ContentView : UIView {
4836 _transient id<ContentDelegate> delegate_;
4841 @implementation ContentView
4843 - (id) initWithFrame:(CGRect)frame {
4844 if ((self = [super initWithFrame:frame]) != nil) {
4845 [self setNeedsDisplayOnBoundsChange:YES];
4849 - (void) setDelegate:(id<ContentDelegate>)delegate {
4850 delegate_ = delegate;
4853 - (void) drawRect:(CGRect)rect {
4854 [super drawRect:rect];
4855 [delegate_ drawContentRect:rect];
4860 /* Cydia TableView Cell {{{ */
4861 @interface CYTableViewCell : UITableViewCell {
4862 ContentView *content_;
4868 @implementation CYTableViewCell
4875 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4876 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4878 if (view == content_) {
4879 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4880 highlighted_ = highlighted;
4883 [super _updateHighlightColorsForView:view highlighted:highlighted];
4886 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4887 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4888 highlighted_ = selected;
4890 [super setSelected:selected animated:animated];
4891 [content_ setNeedsDisplay];
4897 /* Package Cell {{{ */
4898 @interface PackageCell : CYTableViewCell <
4903 NSString *description_;
4911 - (PackageCell *) init;
4912 - (void) setPackage:(Package *)package;
4914 - (void) drawContentRect:(CGRect)rect;
4918 @implementation PackageCell
4920 - (void) clearPackage {
4931 if (description_ != nil) {
4932 [description_ release];
4936 if (source_ != nil) {
4941 if (badge_ != nil) {
4946 if (placard_ != nil) {
4956 [self clearPackage];
4960 - (PackageCell *) init {
4961 CGRect frame(CGRectMake(0, 0, 320, 74));
4962 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4963 UIView *content([self contentView]);
4964 CGRect bounds([content bounds]);
4966 content_ = [[ContentView alloc] initWithFrame:bounds];
4967 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4968 [content addSubview:content_];
4970 [content_ setDelegate:self];
4971 [content_ setOpaque:YES];
4975 - (void) _setBackgroundColor {
4977 if (NSString *mode = [package_ mode]) {
4978 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4979 color = remove ? RemovingColor_ : InstallingColor_;
4981 color = [UIColor whiteColor];
4983 [content_ setBackgroundColor:color];
4984 [self setNeedsDisplay];
4987 - (NSString *) accessibilityLabel {
4988 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
4991 - (void) setPackage:(Package *)package {
4992 [self clearPackage];
4995 Source *source = [package source];
4997 icon_ = [[package icon] retain];
4998 name_ = [[package name] retain];
5001 description_ = [package longDescription];
5002 if (description_ == nil)
5003 description_ = [package shortDescription];
5004 if (description_ != nil)
5005 description_ = [description_ retain];
5007 commercial_ = [package isCommercial];
5009 package_ = [package retain];
5011 NSString *label = nil;
5012 bool trusted = false;
5014 if (source != nil) {
5015 label = [source label];
5016 trusted = [source trusted];
5017 } else if ([[package id] isEqualToString:@"firmware"])
5018 label = UCLocalize("APPLE");
5020 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5022 NSString *from(label);
5024 NSString *section = [package simpleSection];
5025 if (section != nil && ![section isEqualToString:label]) {
5026 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5027 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5030 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5031 source_ = [from retain];
5033 if (NSString *purpose = [package primaryPurpose])
5034 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5035 badge_ = [badge_ retain];
5037 if ([package installed] != nil)
5038 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
5039 placard_ = [placard_ retain];
5041 [self _setBackgroundColor];
5042 [content_ setNeedsDisplay];
5045 - (void) drawContentRect:(CGRect)rect {
5046 bool highlighted(highlighted_);
5047 float width([self bounds].size.width);
5050 CGContextRef context(UIGraphicsGetCurrentContext());
5051 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5052 CGContextFillRect(context, rect);
5057 rect.size = [icon_ size];
5059 rect.size.width /= 2;
5060 rect.size.height /= 2;
5062 rect.origin.x = 25 - rect.size.width / 2;
5063 rect.origin.y = 25 - rect.size.height / 2;
5065 [icon_ drawInRect:rect];
5068 if (badge_ != nil) {
5070 rect.size = [badge_ size];
5072 rect.size.width /= 2;
5073 rect.size.height /= 2;
5075 rect.origin.x = 36 - rect.size.width / 2;
5076 rect.origin.y = 36 - rect.size.height / 2;
5078 [badge_ drawInRect:rect];
5085 UISetColor(commercial_ ? Purple_ : Black_);
5086 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5087 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5090 UISetColor(commercial_ ? Purplish_ : Gray_);
5091 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5093 if (placard_ != nil)
5094 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5099 /* Section Cell {{{ */
5100 @interface SectionCell : CYTableViewCell <
5112 - (void) setSection:(Section *)section editing:(BOOL)editing;
5116 @implementation SectionCell
5118 - (void) clearSection {
5119 if (basic_ != nil) {
5124 if (section_ != nil) {
5134 if (count_ != nil) {
5141 [self clearSection];
5147 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5148 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5149 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5150 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5151 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5153 UIView *content([self contentView]);
5154 CGRect bounds([content bounds]);
5156 content_ = [[ContentView alloc] initWithFrame:bounds];
5157 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5158 [content addSubview:content_];
5159 [content_ setBackgroundColor:[UIColor whiteColor]];
5161 [content_ setDelegate:self];
5165 - (void) onSwitch:(id)sender {
5166 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5167 if (metadata == nil) {
5168 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5169 [Sections_ setObject:metadata forKey:basic_];
5172 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5176 - (void) setSection:(Section *)section editing:(BOOL)editing {
5177 if (editing != editing_) {
5179 [switch_ removeFromSuperview];
5181 [self addSubview:switch_];
5185 [self clearSection];
5187 if (section == nil) {
5188 name_ = [UCLocalize("ALL_PACKAGES") retain];
5191 basic_ = [section name];
5193 basic_ = [basic_ retain];
5195 section_ = [section localized];
5196 if (section_ != nil)
5197 section_ = [section_ retain];
5199 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5200 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5203 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5206 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5207 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5209 [content_ setNeedsDisplay];
5212 - (void) setFrame:(CGRect)frame {
5213 [super setFrame:frame];
5215 CGRect rect([switch_ frame]);
5216 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5219 - (NSString *) accessibilityLabel {
5223 - (void) drawContentRect:(CGRect)rect {
5224 bool highlighted(highlighted_ && !editing_);
5226 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5231 float width(rect.size.width);
5237 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5239 CGSize size = [count_ sizeWithFont:Font14_];
5243 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5249 /* File Table {{{ */
5250 @interface FileTable : CYViewController <
5251 UITableViewDataSource,
5254 _transient Database *database_;
5257 NSMutableArray *files_;
5261 - (id) initWithDatabase:(Database *)database;
5262 - (void) setPackage:(Package *)package;
5266 @implementation FileTable
5269 [self releaseSubviews];
5278 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5279 return files_ == nil ? 0 : [files_ count];
5282 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5286 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5287 static NSString *reuseIdentifier = @"Cell";
5289 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5291 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5292 [cell setFont:[UIFont systemFontOfSize:16]];
5294 [cell setText:[files_ objectAtIndex:indexPath.row]];
5295 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5300 - (NSURL *) navigationURL {
5301 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5305 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5307 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5308 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5309 [list_ setRowHeight:24.0f];
5310 [list_ setDataSource:self];
5311 [list_ setDelegate:self];
5312 [[self view] addSubview:list_];
5315 - (void) viewDidLoad {
5316 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5319 - (void) releaseSubviews {
5324 - (id) initWithDatabase:(Database *)database {
5325 if ((self = [super init]) != nil) {
5326 database_ = database;
5328 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5332 - (void) setPackage:(Package *)package {
5333 if (package_ != nil) {
5334 [package_ autorelease];
5343 [files_ removeAllObjects];
5345 if (package != nil) {
5346 package_ = [package retain];
5347 name_ = [[package id] retain];
5349 if (NSArray *files = [package files])
5350 [files_ addObjectsFromArray:files];
5352 if ([files_ count] != 0) {
5353 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5354 [files_ removeObjectAtIndex:0];
5355 [files_ sortUsingSelector:@selector(compareByPath:)];
5357 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5358 [stack addObject:@"/"];
5360 for (int i(0), e([files_ count]); i != e; ++i) {
5361 NSString *file = [files_ objectAtIndex:i];
5362 while (![file hasPrefix:[stack lastObject]])
5363 [stack removeLastObject];
5364 NSString *directory = [stack lastObject];
5365 [stack addObject:[file stringByAppendingString:@"/"]];
5366 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5367 ([stack count] - 2) * 3, "",
5368 [file substringFromIndex:[directory length]]
5377 - (void) reloadData {
5380 [self setPackage:[database_ packageWithName:name_]];
5385 /* Package Controller {{{ */
5386 @interface CYPackageController : CYBrowserController <
5387 UIActionSheetDelegate
5389 _transient Database *database_;
5393 NSMutableArray *buttons_;
5394 UIBarButtonItem *button_;
5397 - (id) initWithDatabase:(Database *)database;
5399 - (void) setPackage:(Package *)package withName:(NSString *)name;
5400 - (void) setPackage:(Package *)package;
5404 @implementation CYPackageController
5407 if (package_ != nil)
5424 - (NSURL *) navigationURL {
5425 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", [package_ id]]];
5428 /* XXX: this is not safe at all... localization of /fail/ */
5429 - (void) _clickButtonWithName:(NSString *)name {
5430 if ([name isEqualToString:UCLocalize("CLEAR")])
5431 [delegate_ clearPackage:package_];
5432 else if ([name isEqualToString:UCLocalize("INSTALL")])
5433 [delegate_ installPackage:package_];
5434 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5435 [delegate_ installPackage:package_];
5436 else if ([name isEqualToString:UCLocalize("REMOVE")])
5437 [delegate_ removePackage:package_];
5438 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5439 [delegate_ installPackage:package_];
5440 else _assert(false);
5443 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5444 NSString *context([sheet context]);
5446 if ([context isEqualToString:@"modify"]) {
5447 if (button != [sheet cancelButtonIndex]) {
5448 NSString *buttonName = [buttons_ objectAtIndex:button];
5449 [self _clickButtonWithName:buttonName];
5452 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5456 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5457 [super webView:view didClearWindowObject:window forFrame:frame];
5458 [window setValue:package_ forKey:@"package"];
5461 - (bool) _allowJavaScriptPanel {
5466 - (void) _customButtonClicked {
5467 int count([buttons_ count]);
5472 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5474 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5475 [buttons addObjectsFromArray:buttons_];
5477 UIActionSheet *sheet = [[[UIActionSheet alloc]
5480 cancelButtonTitle:nil
5481 destructiveButtonTitle:nil
5482 otherButtonTitles:nil
5485 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5487 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5488 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5490 [sheet setContext:@"modify"];
5492 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5496 // We don't want to allow non-commercial packages to do custom things to the install button,
5497 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5498 - (void) customButtonClicked {
5500 [super customButtonClicked];
5502 [self _customButtonClicked];
5505 - (void) reloadButtonClicked {
5506 // Don't reload a commerical package by tapping the loading button,
5507 // but if it's not an Install button, we should forward it on.
5508 if (![package_ uninstalled])
5509 [self _customButtonClicked];
5512 - (void) applyLoadingTitle {
5513 // Don't show "Loading" as the title. Ever.
5516 - (UIBarButtonItem *) rightButton {
5521 - (void) viewWillAppear:(BOOL)animated {
5522 if (![self hasLoaded])
5523 [self loadURL:[NSURL URLWithString:CydiaURL(@"ui/package/")]];
5524 [super viewWillAppear:animated];
5527 - (id) initWithDatabase:(Database *)database {
5528 if ((self = [super init]) != nil) {
5529 database_ = database;
5530 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5534 - (void) setPackage:(Package *)package withName:(NSString *)name {
5535 if (package_ != nil) {
5536 [package_ autorelease];
5541 [name_ autorelease];
5542 name_ = [[NSString alloc] initWithString:name];
5544 [buttons_ removeAllObjects];
5546 if (package != nil) {
5549 package_ = [package retain];
5550 commercial_ = [package isCommercial];
5552 if ([package_ mode] != nil)
5553 [buttons_ addObject:UCLocalize("CLEAR")];
5554 if ([package_ source] == nil);
5555 else if ([package_ upgradableAndEssential:NO])
5556 [buttons_ addObject:UCLocalize("UPGRADE")];
5557 else if ([package_ uninstalled])
5558 [buttons_ addObject:UCLocalize("INSTALL")];
5560 [buttons_ addObject:UCLocalize("REINSTALL")];
5561 if (![package_ uninstalled])
5562 [buttons_ addObject:UCLocalize("REMOVE")];
5569 switch ([buttons_ count]) {
5570 case 0: title = nil; break;
5571 case 1: title = [buttons_ objectAtIndex:0]; break;
5572 default: title = UCLocalize("MODIFY"); break;
5575 button_ = [[UIBarButtonItem alloc]
5577 style:UIBarButtonItemStylePlain
5579 action:@selector(customButtonClicked)
5582 [self loadURL:[NSURL URLWithString:CydiaURL([NSString stringWithFormat:@"ui/package/#!/%@", name])]];
5585 - (void) setPackage:(Package *)package {
5586 [self setPackage:package withName:[package id]];
5589 - (bool) isLoading {
5590 return commercial_ ? [super isLoading] : false;
5593 - (void) reloadData {
5595 [self setPackage:[database_ packageWithName:name_] withName:name_];
5601 /* Package List Controller {{{ */
5602 @interface PackageListController : CYViewController <
5603 UITableViewDataSource,
5606 _transient Database *database_;
5608 NSMutableArray *packages_;
5609 NSMutableArray *sections_;
5611 NSMutableArray *index_;
5612 NSMutableDictionary *indices_;
5616 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5617 - (void) setDelegate:(id)delegate;
5618 - (void) resetCursor;
5622 @implementation PackageListController
5625 [packages_ release];
5626 [sections_ release];
5635 - (void) deselectWithAnimation:(BOOL)animated {
5636 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5639 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5640 CGRect base = [[self view] bounds];
5641 base.size.height -= bounds.size.height;
5642 base.origin = [list_ frame].origin;
5644 [UIView beginAnimations:nil context:NULL];
5645 [UIView setAnimationBeginsFromCurrentState:YES];
5646 [UIView setAnimationCurve:curve];
5647 [UIView setAnimationDuration:duration];
5648 [list_ setFrame:base];
5649 [UIView commitAnimations];
5652 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5653 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5656 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5657 [self resizeForKeyboardBounds:bounds duration:0];
5660 - (void) keyboardWillShow:(NSNotification *)notification {
5663 NSTimeInterval duration;
5664 UIViewAnimationCurve curve;
5665 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5666 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5667 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5668 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5670 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);
5671 UIViewController *base = self;
5672 while ([base parentViewController] != nil)
5673 base = [base parentViewController];
5674 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5675 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5677 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5680 - (void) keyboardWillHide:(NSNotification *)notification {
5681 NSTimeInterval duration;
5682 UIViewAnimationCurve curve;
5683 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5684 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5686 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5689 - (void) viewWillAppear:(BOOL)animated {
5690 [super viewWillAppear:animated];
5692 [self resizeForKeyboardBounds:CGRectZero];
5693 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5694 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5697 - (void) viewWillDisappear:(BOOL)animated {
5698 [super viewWillDisappear:animated];
5700 [self resizeForKeyboardBounds:CGRectZero];
5701 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5702 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5705 - (void) viewDidAppear:(BOOL)animated {
5706 [super viewDidAppear:animated];
5707 [self deselectWithAnimation:animated];
5710 - (void) didSelectPackage:(Package *)package {
5711 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_] autorelease]);
5712 [view setPackage:package];
5713 [view setDelegate:delegate_];
5714 [[self navigationController] pushViewController:view animated:YES];
5717 #if TryIndexedCollation
5718 + (BOOL) hasIndexedCollation {
5719 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5723 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5724 NSInteger count([sections_ count]);
5725 return count == 0 ? 1 : count;
5728 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5729 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5731 return [[sections_ objectAtIndex:section] name];
5734 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5735 if ([sections_ count] == 0)
5737 return [[sections_ objectAtIndex:section] count];
5740 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5741 @synchronized (database_) {
5742 if ([database_ era] != era_)
5745 Section *section([sections_ objectAtIndex:[path section]]);
5746 NSInteger row([path row]);
5747 Package *package([packages_ objectAtIndex:([section row] + row)]);
5748 return [[package retain] autorelease];
5751 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5752 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5754 cell = [[[PackageCell alloc] init] autorelease];
5755 [cell setPackage:[self packageAtIndexPath:path]];
5759 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5760 Package *package([self packageAtIndexPath:path]);
5761 package = [database_ packageWithName:[package id]];
5762 [self didSelectPackage:package];
5765 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5766 // XXX: is 20 the most optimal number here?
5767 return [packages_ count] > 20 ? index_ : nil;
5770 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5771 #if TryIndexedCollation
5772 if ([[self class] hasIndexedCollation]) {
5773 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5780 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5781 if ((self = [super init]) != nil) {
5782 database_ = database;
5783 title_ = [title copy];
5784 [[self navigationItem] setTitle:title_];
5786 #if TryIndexedCollation
5787 if ([[self class] hasIndexedCollation])
5788 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
5791 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5793 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5795 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5796 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5798 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
5799 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5800 [list_ setRowHeight:73];
5801 [[self view] addSubview:list_];
5803 [list_ setDataSource:self];
5804 [list_ setDelegate:self];
5808 - (void) setDelegate:(id)delegate {
5809 delegate_ = delegate;
5812 - (bool) hasPackage:(Package *)package {
5816 - (void) reloadData {
5819 era_ = [database_ era];
5820 NSArray *packages = [database_ packages];
5822 [packages_ removeAllObjects];
5823 [sections_ removeAllObjects];
5825 _profile(PackageTable$reloadData$Filter)
5826 for (Package *package in packages)
5827 if ([self hasPackage:package])
5828 [packages_ addObject:package];
5831 [indices_ removeAllObjects];
5833 Section *section = nil;
5835 #if TryIndexedCollation
5836 if ([[self class] hasIndexedCollation]) {
5837 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5838 NSArray *titles = [collation sectionIndexTitles];
5841 _profile(PackageTable$reloadData$Section)
5842 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5846 _profile(PackageTable$reloadData$Section$Package)
5847 package = [packages_ objectAtIndex:offset];
5848 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5851 while (secidx < index) {
5854 _profile(PackageTable$reloadData$Section$Allocate)
5855 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5858 _profile(PackageTable$reloadData$Section$Add)
5859 [sections_ addObject:section];
5863 [section addToCount];
5869 [index_ removeAllObjects];
5871 _profile(PackageTable$reloadData$Section)
5872 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5876 _profile(PackageTable$reloadData$Section$Package)
5877 package = [packages_ objectAtIndex:offset];
5878 index = [package index];
5881 if (section == nil || [section index] != index) {
5882 _profile(PackageTable$reloadData$Section$Allocate)
5883 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5886 [index_ addObject:[section name]];
5887 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5889 _profile(PackageTable$reloadData$Section$Add)
5890 [sections_ addObject:section];
5894 [section addToCount];
5899 _profile(PackageTable$reloadData$List)
5904 - (void) resetCursor {
5905 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5910 /* Filtered Package List Controller {{{ */
5911 @interface FilteredPackageListController : PackageListController {
5917 - (void) setObject:(id)object;
5918 - (void) setObject:(id)object forFilter:(SEL)filter;
5920 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5924 @implementation FilteredPackageListController
5932 - (void) setFilter:(SEL)filter {
5935 /* XXX: this is an unsafe optimization of doomy hell */
5936 Method method(class_getInstanceMethod([Package class], filter));
5937 _assert(method != NULL);
5938 imp_ = method_getImplementation(method);
5939 _assert(imp_ != NULL);
5942 - (void) setObject:(id)object {
5948 object_ = [object retain];
5951 - (void) setObject:(id)object forFilter:(SEL)filter {
5952 [self setFilter:filter];
5953 [self setObject:object];
5956 - (bool) hasPackage:(Package *)package {
5957 _profile(FilteredPackageTable$hasPackage)
5958 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5962 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5963 if ((self = [super initWithDatabase:database title:title]) != nil) {
5964 [self setFilter:filter];
5965 [self setObject:object];
5973 /* Home Controller {{{ */
5974 @interface HomeController : CYBrowserController {
5978 @implementation HomeController
5980 + (BOOL) shouldHideNavigationBar {
5984 - (NSURL *) navigationURL {
5985 return [NSURL URLWithString:@"cydia://home"];
5988 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
5989 [super _setMoreHeaders:request];
5992 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
5993 if (UniqueID_ != nil)
5994 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5996 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
5999 - (void) aboutButtonClicked {
6000 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6002 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6003 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6004 [alert setCancelButtonIndex:0];
6007 @"Copyright (C) 2008-2011\n"
6008 "Jay Freeman (saurik)\n"
6009 "saurik@saurik.com\n"
6010 "http://www.saurik.com/"
6016 - (void) viewWillDisappear:(BOOL)animated {
6017 [super viewWillDisappear:animated];
6019 if ([[self class] shouldHideNavigationBar])
6020 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6023 - (void) viewWillAppear:(BOOL)animated {
6024 if (![self hasLoaded])
6025 [self loadURL:[NSURL URLWithString:CydiaURL(@"ui/home/")]];
6027 [super viewWillAppear:animated];
6029 if ([[self class] shouldHideNavigationBar])
6030 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6033 - (void) viewDidLoad {
6034 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6035 initWithTitle:UCLocalize("ABOUT")
6036 style:UIBarButtonItemStylePlain
6038 action:@selector(aboutButtonClicked)
6044 /* Manage Controller {{{ */
6045 @interface ManageController : CYBrowserController {
6048 - (void) queueStatusDidChange;
6051 @implementation ManageController
6053 - (NSURL *) navigationURL {
6054 return [NSURL URLWithString:@"cydia://manage"];
6057 - (void) viewWillAppear:(BOOL)animated {
6058 if (![self hasLoaded])
6059 [self loadURL:[NSURL URLWithString:CydiaURL(@"ui/manage/")]];
6061 [super viewWillAppear:animated];
6064 - (void) viewDidLoad {
6065 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6067 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6068 initWithTitle:UCLocalize("SETTINGS")
6069 style:UIBarButtonItemStylePlain
6071 action:@selector(settingsButtonClicked)
6074 [self queueStatusDidChange];
6077 - (void) settingsButtonClicked {
6078 [delegate_ showSettings];
6082 - (void) queueButtonClicked {
6086 - (void) applyLoadingTitle {
6087 // Disable "Loading" title.
6090 - (void) applyRightButton {
6091 // Disable right button.
6095 - (void) queueStatusDidChange {
6097 if (!IsWildcat_ && Queuing_) {
6098 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6099 initWithTitle:UCLocalize("QUEUE")
6100 style:UIBarButtonItemStyleDone
6102 action:@selector(queueButtonClicked)
6105 [[self navigationItem] setRightBarButtonItem:nil];
6110 - (bool) isLoading {
6111 // Never show as loading.
6118 /* Refresh Bar {{{ */
6119 @interface RefreshBar : UINavigationBar {
6120 UIProgressIndicator *indicator_;
6121 UITextLabel *prompt_;
6122 UIProgressBar *progress_;
6123 UINavigationButton *cancel_;
6128 @implementation RefreshBar
6131 [indicator_ release];
6133 [progress_ release];
6138 - (void) positionViews {
6139 CGRect frame = [cancel_ frame];
6140 frame.size = [cancel_ sizeThatFits:frame.size];
6141 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6142 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6143 [cancel_ setFrame:frame];
6145 CGSize prgsize = {75, 100};
6147 [self frame].size.width - prgsize.width - 10,
6148 ([self frame].size.height - prgsize.height) / 2
6150 [progress_ setFrame:prgrect];
6152 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6153 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6154 CGRect indrect = {{indoffset, indoffset}, indsize};
6155 [indicator_ setFrame:indrect];
6157 CGSize prmsize = {215, indsize.height + 4};
6159 indoffset * 2 + indsize.width,
6160 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6162 [prompt_ setFrame:prmrect];
6165 - (void)setFrame:(CGRect)frame {
6166 [super setFrame:frame];
6168 [self positionViews];
6171 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6172 if ((self = [super initWithFrame:frame])) {
6173 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6175 [self setBarStyle:UIBarStyleBlack];
6177 UIBarStyle barstyle([self _barStyle:NO]);
6178 bool ugly(barstyle == UIBarStyleDefault);
6180 UIProgressIndicatorStyle style = ugly ?
6181 UIProgressIndicatorStyleMediumBrown :
6182 UIProgressIndicatorStyleMediumWhite;
6184 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6185 [indicator_ setStyle:style];
6186 [indicator_ startAnimation];
6187 [self addSubview:indicator_];
6189 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6190 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6191 [prompt_ setBackgroundColor:[UIColor clearColor]];
6192 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6193 [self addSubview:prompt_];
6195 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6196 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6197 [progress_ setStyle:0];
6198 [self addSubview:progress_];
6200 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6201 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6202 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6203 [cancel_ setBarStyle:barstyle];
6205 [self positionViews];
6210 [cancel_ removeFromSuperview];
6214 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6215 [progress_ setProgress:0];
6216 [self addSubview:cancel_];
6220 [cancel_ removeFromSuperview];
6223 - (void) setPrompt:(NSString *)prompt {
6224 [prompt_ setText:prompt];
6227 - (void) setProgress:(float)progress {
6228 [progress_ setProgress:progress];
6234 @class CYNavigationController;
6236 /* Cydia Tab Bar Controller {{{ */
6237 @interface CYTabBarController : UITabBarController <
6240 _transient Database *database_;
6241 RefreshBar *refreshbar_;
6245 // XXX: ok, "updatedelegate_"?...
6246 _transient NSObject<CydiaDelegate> *updatedelegate_;
6251 - (NSArray *) navigationURLCollection;
6252 - (void) dropBar:(BOOL)animated;
6253 - (void) beginUpdate;
6254 - (void) raiseBar:(BOOL)animated;
6259 @implementation CYTabBarController
6261 - (NSArray *) navigationURLCollection {
6262 NSMutableArray *items([NSMutableArray array]);
6264 // XXX: Should this deal with transient view controllers?
6265 for (id navigation in [self viewControllers]) {
6266 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6268 [items addObject:stack];
6274 - (void) reloadData {
6275 for (CYViewController *controller in [self viewControllers])
6276 [controller reloadData];
6278 [(CYNavigationController *)[self transientViewController] reloadData];
6282 [refreshbar_ release];
6283 [[NSNotificationCenter defaultCenter] removeObserver:self];
6288 - (id) initWithDatabase:(Database *)database {
6289 if ((self = [super init]) != nil) {
6290 database_ = database;
6292 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6293 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6295 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6299 - (void) setUpdate:(NSDate *)date {
6303 - (void) beginUpdate {
6304 [refreshbar_ start];
6307 [updatedelegate_ retainNetworkActivityIndicator];
6311 detachNewThreadSelector:@selector(performUpdate)
6317 - (void) performUpdate { _pooled
6319 status.setDelegate(self);
6320 [database_ updateWithStatus:status];
6323 performSelectorOnMainThread:@selector(completeUpdate)
6329 - (void) stopUpdateWithSelector:(SEL)selector {
6331 [updatedelegate_ releaseNetworkActivityIndicator];
6333 [self raiseBar:YES];
6336 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6339 - (void) completeUpdate {
6342 [self stopUpdateWithSelector:@selector(reloadData)];
6345 - (void) cancelUpdate {
6346 [self stopUpdateWithSelector:@selector(updateData)];
6349 - (void) cancelPressed {
6350 [self cancelUpdate];
6357 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6358 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6361 - (void) startProgress {
6364 - (void) setProgressTitle:(NSString *)title {
6366 performSelectorOnMainThread:@selector(_setProgressTitle:)
6372 - (bool) isCancelling:(size_t)received {
6376 - (void) setProgressPercent:(float)percent {
6378 performSelectorOnMainThread:@selector(_setProgressPercent:)
6379 withObject:[NSNumber numberWithFloat:percent]
6384 - (void) addProgressOutput:(NSString *)output {
6386 performSelectorOnMainThread:@selector(_addProgressOutput:)
6392 - (void) _setProgressTitle:(NSString *)title {
6393 [refreshbar_ setPrompt:title];
6396 - (void) _setProgressPercent:(NSNumber *)percent {
6397 [refreshbar_ setProgress:[percent floatValue]];
6400 - (void) _addProgressOutput:(NSString *)output {
6403 - (void) setUpdateDelegate:(id)delegate {
6404 updatedelegate_ = delegate;
6407 - (CGFloat) statusBarHeight {
6408 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6409 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6411 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6415 - (UIView *) transitionView {
6416 if ([self respondsToSelector:@selector(_transitionView)])
6417 return [self _transitionView];
6419 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6422 - (void) dropBar:(BOOL)animated {
6427 UIView *transition([self transitionView]);
6428 [[self view] addSubview:refreshbar_];
6430 CGRect barframe([refreshbar_ frame]);
6432 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6433 barframe.origin.y = [self statusBarHeight];
6435 barframe.origin.y = 0;
6437 [refreshbar_ setFrame:barframe];
6440 [UIView beginAnimations:nil context:NULL];
6442 CGRect viewframe = [transition frame];
6443 viewframe.origin.y += barframe.size.height;
6444 viewframe.size.height -= barframe.size.height;
6445 [transition setFrame:viewframe];
6448 [UIView commitAnimations];
6450 // Ensure bar has the proper width for our view, it might have changed
6451 barframe.size.width = viewframe.size.width;
6452 [refreshbar_ setFrame:barframe];
6454 // XXX: fix Apple's layout bug
6455 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6458 - (void) raiseBar:(BOOL)animated {
6463 UIView *transition([self transitionView]);
6464 [refreshbar_ removeFromSuperview];
6466 CGRect barframe([refreshbar_ frame]);
6469 [UIView beginAnimations:nil context:NULL];
6471 CGRect viewframe = [transition frame];
6472 viewframe.origin.y -= barframe.size.height;
6473 viewframe.size.height += barframe.size.height;
6474 [transition setFrame:viewframe];
6477 [UIView commitAnimations];
6479 // XXX: fix Apple's layout bug
6480 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6484 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6485 // XXX: fix Apple's layout bug
6486 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6490 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6491 bool dropped(dropped_);
6496 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6501 // XXX: fix Apple's layout bug
6502 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6505 - (void) statusBarFrameChanged:(NSNotification *)notification {
6514 /* Cydia Navigation Controller {{{ */
6515 @interface CYNavigationController : UINavigationController {
6516 _transient Database *database_;
6517 _transient id<UINavigationControllerDelegate> delegate_;
6520 - (NSArray *) navigationURLCollection;
6521 - (id) initWithDatabase:(Database *)database;
6522 - (void) reloadData;
6527 @implementation CYNavigationController
6533 - (NSArray *) navigationURLCollection {
6534 NSMutableArray *stack([NSMutableArray array]);
6536 for (CYViewController *controller in [self viewControllers]) {
6537 NSString *url = [[controller navigationURL] absoluteString];
6539 [stack addObject:url];
6545 - (void) reloadData {
6546 for (CYViewController *page in [self viewControllers]) {
6547 if ([page hasLoaded])
6552 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6553 delegate_ = delegate;
6556 - (id) initWithDatabase:(Database *)database {
6557 if ((self = [super init]) != nil) {
6558 database_ = database;
6565 /* Cydia:// Protocol {{{ */
6566 @interface CydiaURLProtocol : NSURLProtocol {
6571 @implementation CydiaURLProtocol
6573 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6574 NSURL *url([request URL]);
6577 NSString *scheme([[url scheme] lowercaseString]);
6578 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6583 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6587 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6588 id<NSURLProtocolClient> client([self client]);
6590 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6592 NSData *data(UIImagePNGRepresentation(icon));
6594 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6595 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6596 [client URLProtocol:self didLoadData:data];
6597 [client URLProtocolDidFinishLoading:self];
6601 - (void) startLoading {
6602 id<NSURLProtocolClient> client([self client]);
6603 NSURLRequest *request([self request]);
6605 NSURL *url([request URL]);
6606 NSString *href([url absoluteString]);
6608 NSString *path([href substringFromIndex:8]);
6609 NSRange slash([path rangeOfString:@"/"]);
6612 if (slash.location == NSNotFound) {
6616 command = [path substringToIndex:slash.location];
6617 path = [path substringFromIndex:(slash.location + 1)];
6620 Database *database([Database sharedInstance]);
6622 if ([command isEqualToString:@"package-icon"]) {
6625 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6626 Package *package([database packageWithName:path]);
6629 UIImage *icon([package icon]);
6630 [self _returnPNGWithImage:icon forRequest:request];
6631 } else if ([command isEqualToString:@"source-icon"]) {
6634 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6635 NSString *source(Simplify(path));
6636 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6638 icon = [UIImage applicationImageNamed:@"unknown.png"];
6639 [self _returnPNGWithImage:icon forRequest:request];
6640 } else if ([command isEqualToString:@"uikit-image"]) {
6643 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6644 UIImage *icon(_UIImageWithName(path));
6645 [self _returnPNGWithImage:icon forRequest:request];
6646 } else if ([command isEqualToString:@"section-icon"]) {
6649 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6650 NSString *section(Simplify(path));
6651 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6653 icon = [UIImage applicationImageNamed:@"unknown.png"];
6654 [self _returnPNGWithImage:icon forRequest:request];
6656 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6660 - (void) stopLoading {
6666 /* Section Controller {{{ */
6667 @interface SectionController : FilteredPackageListController {
6671 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6675 @implementation SectionController
6677 - (NSURL *) navigationURL {
6678 NSString *name = section_;
6682 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6685 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6689 title = UCLocalize("ALL_PACKAGES");
6690 } else if (![name isEqual:@""]) {
6691 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6693 title = UCLocalize("NO_SECTION");
6698 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6704 /* Sections Controller {{{ */
6705 @interface SectionsController : CYViewController <
6706 UITableViewDataSource,
6709 _transient Database *database_;
6710 NSMutableArray *sections_;
6711 NSMutableArray *filtered_;
6716 - (id) initWithDatabase:(Database *)database;
6717 - (void) editButtonClicked;
6721 @implementation SectionsController
6724 [self releaseSubviews];
6725 [sections_ release];
6726 [filtered_ release];
6731 - (NSURL *) navigationURL {
6732 return [NSURL URLWithString:@"cydia://sections"];
6735 - (void) updateNavigationItem {
6736 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6737 if ([sections_ count] == 0) {
6738 [[self navigationItem] setRightBarButtonItem:nil];
6740 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6741 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6743 action:@selector(editButtonClicked)
6744 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6748 - (BOOL) isEditing {
6752 - (void) setEditing:(BOOL)editing {
6753 if ((editing_ = editing))
6756 [delegate_ updateData];
6758 [self updateNavigationItem];
6761 - (void) viewDidAppear:(BOOL)animated {
6762 [super viewDidAppear:animated];
6763 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6766 - (void) viewWillDisappear:(BOOL)animated {
6767 [super viewWillDisappear:animated];
6768 if (editing_) [self setEditing:NO];
6771 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6772 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6776 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6777 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6780 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6784 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6785 static NSString *reuseIdentifier = @"SectionCell";
6787 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6789 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6791 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6796 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6800 Section *section = [self sectionAtIndexPath:indexPath];
6802 SectionController *controller = [[[SectionController alloc]
6803 initWithDatabase:database_
6804 section:[section name]
6806 [controller setDelegate:delegate_];
6808 [[self navigationController] pushViewController:controller animated:YES];
6812 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6814 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6815 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6816 [list_ setRowHeight:45.0f];
6817 [list_ setDataSource:self];
6818 [list_ setDelegate:self];
6819 [[self view] addSubview:list_];
6822 - (void) viewDidLoad {
6823 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6826 - (void) releaseSubviews {
6831 - (id) initWithDatabase:(Database *)database {
6832 if ((self = [super init]) != nil) {
6833 database_ = database;
6835 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6836 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6840 - (void) reloadData {
6843 NSArray *packages = [database_ packages];
6845 [sections_ removeAllObjects];
6846 [filtered_ removeAllObjects];
6848 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6851 for (Package *package in packages) {
6852 NSString *name([package section]);
6853 NSString *key(name == nil ? @"" : name);
6857 _profile(SectionsView$reloadData$Section)
6858 section = [sections objectForKey:key];
6859 if (section == nil) {
6860 _profile(SectionsView$reloadData$Section$Allocate)
6861 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6862 [sections setObject:section forKey:key];
6867 [section addToCount];
6869 _profile(SectionsView$reloadData$Filter)
6870 if (![package valid] || ![package visible])
6878 [sections_ addObjectsFromArray:[sections allValues]];
6880 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6882 for (Section *section in sections_) {
6883 size_t count([section row]);
6887 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6888 [section setCount:count];
6889 [filtered_ addObject:section];
6892 [self updateNavigationItem];
6897 - (void)editButtonClicked {
6898 [self setEditing:!editing_];
6904 /* Changes Controller {{{ */
6905 @interface ChangesController : CYViewController <
6906 UITableViewDataSource,
6909 _transient Database *database_;
6911 CFMutableArrayRef packages_;
6912 NSMutableArray *sections_;
6915 BOOL hasSentFirstLoad_;
6918 - (id) initWithDatabase:(Database *)database;
6922 @implementation ChangesController
6925 [self releaseSubviews];
6926 CFRelease(packages_);
6927 [sections_ release];
6932 - (NSURL *) navigationURL {
6933 return [NSURL URLWithString:@"cydia://changes"];
6936 - (void) viewWillAppear:(BOOL)animated {
6937 // Loads after it appears, so don't load beforehand.
6939 [super viewWillAppear:animated];
6942 - (void) viewDidAppear:(BOOL)animated {
6943 [super viewDidAppear:animated];
6945 if (!hasSentFirstLoad_) {
6946 hasSentFirstLoad_ = YES;
6947 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6949 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6953 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6954 NSInteger count([sections_ count]);
6955 return count == 0 ? 1 : count;
6958 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6959 if ([sections_ count] == 0)
6961 return [[sections_ objectAtIndex:section] name];
6964 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6965 if ([sections_ count] == 0)
6967 return [[sections_ objectAtIndex:section] count];
6970 - (Package *) packageAtIndex:(NSUInteger)index {
6971 return (Package *) CFArrayGetValueAtIndex(packages_, index);
6974 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6975 @synchronized (database_) {
6976 if ([database_ era] != era_)
6979 NSUInteger sectionIndex([path section]);
6980 if (sectionIndex >= [sections_ count])
6982 Section *section([sections_ objectAtIndex:sectionIndex]);
6983 NSInteger row([path row]);
6984 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
6987 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6988 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6990 cell = [[[PackageCell alloc] init] autorelease];
6991 [cell setPackage:[self packageAtIndexPath:path]];
6995 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6996 Package *package([self packageAtIndexPath:path]);
6997 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_] autorelease]);
6998 [view setDelegate:delegate_];
6999 [view setPackage:package];
7000 [[self navigationController] pushViewController:view animated:YES];
7004 - (void) refreshButtonClicked {
7005 [delegate_ beginUpdate];
7006 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7009 - (void) upgradeButtonClicked {
7010 [delegate_ distUpgrade];
7014 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7016 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7017 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7018 [list_ setRowHeight:73];
7019 [list_ setDataSource:self];
7020 [list_ setDelegate:self];
7021 [[self view] addSubview:list_];
7024 - (void) viewDidLoad {
7025 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7028 - (void) releaseSubviews {
7033 - (id) initWithDatabase:(Database *)database {
7034 if ((self = [super init]) != nil) {
7035 database_ = database;
7037 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7038 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7042 - (void) _reloadPackages:(NSArray *)packages {
7043 CFRelease(packages_);
7044 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7047 _profile(ChangesController$_reloadPackages$Filter)
7048 for (Package *package in packages)
7049 if ([package upgradableAndEssential:YES] || [package visible])
7050 CFArrayAppendValue(packages_, package);
7053 _profile(ChangesController$_reloadPackages$radixSort)
7054 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7059 - (void) reloadData {
7060 @synchronized (database_) {
7061 era_ = [database_ era];
7062 NSArray *packages = [database_ packages];
7064 [sections_ removeAllObjects];
7067 UIProgressHUD *hud([delegate_ addProgressHUD]);
7068 [hud setText:UCLocalize("LOADING")];
7069 //NSLog(@"HUD:%@::%@", delegate_, hud);
7070 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7071 [delegate_ removeProgressHUD:hud];
7073 [self _reloadPackages:packages];
7076 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7077 Section *ignored = nil;
7078 Section *section = nil;
7082 bool unseens = false;
7084 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7086 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7087 Package *package = [self packageAtIndex:offset];
7089 BOOL uae = [package upgradableAndEssential:YES];
7093 time_t seen([package seen]);
7095 if (section == nil || last != seen) {
7099 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7102 _profile(ChangesController$reloadData$Allocate)
7103 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7104 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7105 [sections_ addObject:section];
7109 [section addToCount];
7110 } else if ([package ignored]) {
7111 if (ignored == nil) {
7112 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7114 [ignored addToCount];
7117 [upgradable addToCount];
7122 CFRelease(formatter);
7125 Section *last = [sections_ lastObject];
7126 size_t count = [last count];
7127 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7128 [sections_ removeLastObject];
7131 if ([ignored count] != 0)
7132 [sections_ insertObject:ignored atIndex:0];
7134 [sections_ insertObject:upgradable atIndex:0];
7139 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7140 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7141 style:UIBarButtonItemStylePlain
7143 action:@selector(upgradeButtonClicked)
7146 if (![delegate_ updating])
7147 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7148 initWithTitle:UCLocalize("REFRESH")
7149 style:UIBarButtonItemStylePlain
7151 action:@selector(refreshButtonClicked)
7159 /* Search Controller {{{ */
7160 @interface SearchController : FilteredPackageListController <
7163 UISearchBar *search_;
7167 - (id) initWithDatabase:(Database *)database;
7168 - (void) setSearchTerm:(NSString *)term;
7169 - (void) reloadData;
7173 @implementation SearchController
7180 - (NSURL *) navigationURL {
7181 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7182 return [NSURL URLWithString:@"cydia://search"];
7184 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7187 - (void) setSearchTerm:(NSString *)searchTerm {
7188 [search_ setText:searchTerm];
7192 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7193 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7194 [search_ resignFirstResponder];
7198 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7199 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7203 - (id) initWithDatabase:(Database *)database {
7204 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7205 search_ = [[UISearchBar alloc] init];
7209 - (void)viewDidAppear:(BOOL)animated {
7210 [super viewDidAppear:animated];
7212 if (!searchloaded_) {
7213 searchloaded_ = YES;
7214 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7215 [search_ layoutSubviews];
7216 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7218 UITextField *textField;
7219 if ([search_ respondsToSelector:@selector(searchField)])
7220 textField = [search_ searchField];
7222 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7224 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7225 [search_ setDelegate:self];
7226 [textField setEnablesReturnKeyAutomatically:NO];
7227 [[self navigationItem] setTitleView:textField];
7231 - (void) reloadData {
7232 [self setObject:[search_ text]];
7237 - (void) didSelectPackage:(Package *)package {
7238 [search_ resignFirstResponder];
7239 [super didSelectPackage:package];
7244 /* Package Settings Controller {{{ */
7245 @interface PackageSettingsController : CYViewController <
7246 UITableViewDataSource,
7249 _transient Database *database_;
7252 UITableView *table_;
7253 UISwitch *subscribedSwitch_;
7254 UISwitch *ignoredSwitch_;
7255 UITableViewCell *subscribedCell_;
7256 UITableViewCell *ignoredCell_;
7259 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7263 @implementation PackageSettingsController
7266 [self releaseSubviews];
7273 - (NSURL *) navigationURL {
7274 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7277 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7278 if (package_ == nil)
7284 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7285 if (package_ == nil)
7291 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7292 return UCLocalize("CHANGE_PACKAGE_SETTINGS");
7295 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7296 return UCLocalize("SHOW_ALL_CHANGES_EX");
7299 - (void) onSubscribed:(id)control {
7300 bool value([control isOn]);
7301 if (package_ == nil)
7303 if ([package_ setSubscribed:value])
7304 [delegate_ updateData];
7307 - (void) onIgnored:(id)control {
7308 // TODO: set Held state - possibly call out to dpkg, etc.
7311 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7312 if (package_ == nil)
7315 switch ([indexPath row]) {
7316 case 0: return subscribedCell_;
7317 case 1: return ignoredCell_;
7326 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7328 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7329 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7330 [table_ setDataSource:self];
7331 [table_ setDelegate:self];
7332 [[self view] addSubview:table_];
7334 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7335 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7336 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7338 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7339 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7340 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7341 // Disable this switch, since it only reflects (not modifies) the ignored state.
7342 [ignoredSwitch_ setUserInteractionEnabled:NO];
7344 subscribedCell_ = [[UITableViewCell alloc] init];
7345 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7346 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7347 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7349 ignoredCell_ = [[UITableViewCell alloc] init];
7350 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7351 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7352 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7353 // FIXME: Ignored state is not saved.
7354 [ignoredCell_ setUserInteractionEnabled:NO];
7357 - (void) viewDidLoad {
7358 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7361 - (void) releaseSubviews {
7362 [ignoredCell_ release];
7365 [subscribedCell_ release];
7366 subscribedCell_ = nil;
7371 [ignoredSwitch_ release];
7372 ignoredSwitch_ = nil;
7374 [subscribedSwitch_ release];
7375 subscribedSwitch_ = nil;
7378 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7379 if ((self = [super init])) {
7380 database_ = database;
7381 name_ = [package retain];
7385 - (void) reloadData {
7388 if (package_ != nil)
7389 [package_ autorelease];
7390 package_ = [database_ packageWithName:name_];
7391 if (package_ != nil) {
7393 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7394 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7397 [table_ reloadData];
7403 /* Installed Controller {{{ */
7404 @interface InstalledController : FilteredPackageListController {
7408 - (id) initWithDatabase:(Database *)database;
7410 - (void) updateRoleButton;
7411 - (void) queueStatusDidChange;
7415 @implementation InstalledController
7421 - (NSURL *) navigationURL {
7422 return [NSURL URLWithString:@"cydia://installed"];
7425 - (id) initWithDatabase:(Database *)database {
7426 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7427 [self updateRoleButton];
7428 [self queueStatusDidChange];
7433 - (void) queueButtonClicked {
7438 - (void) queueStatusDidChange {
7442 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7443 initWithTitle:UCLocalize("QUEUE")
7444 style:UIBarButtonItemStyleDone
7446 action:@selector(queueButtonClicked)
7449 [[self navigationItem] setLeftBarButtonItem:nil];
7455 - (void) updateRoleButton {
7456 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7457 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7458 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7459 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7461 action:@selector(roleButtonClicked)
7465 - (void) roleButtonClicked {
7466 [self setObject:[NSNumber numberWithBool:expert_]];
7470 [self updateRoleButton];
7476 /* Source Cell {{{ */
7477 @interface SourceCell : CYTableViewCell <
7485 - (void) setSource:(Source *)source;
7489 @implementation SourceCell
7491 - (void) clearSource {
7501 - (void) setSource:(Source *)source {
7505 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7507 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7508 icon_ = [icon_ retain];
7510 origin_ = [[source name] retain];
7511 label_ = [[source uri] retain];
7513 [content_ setNeedsDisplay];
7521 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7522 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7523 UIView *content([self contentView]);
7524 CGRect bounds([content bounds]);
7526 content_ = [[ContentView alloc] initWithFrame:bounds];
7527 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7528 [content_ setBackgroundColor:[UIColor whiteColor]];
7529 [content addSubview:content_];
7531 [content_ setDelegate:self];
7532 [content_ setOpaque:YES];
7536 - (NSString *) accessibilityLabel {
7540 - (void) drawContentRect:(CGRect)rect {
7541 bool highlighted(highlighted_);
7542 float width(rect.size.width);
7545 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7552 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7556 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7561 /* Source Controller {{{ */
7562 @interface SourceController : FilteredPackageListController {
7566 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7570 @implementation SourceController
7572 - (NSURL *) navigationURL {
7573 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7576 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7579 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7585 /* Sources Controller {{{ */
7586 @interface SourcesController : CYViewController <
7587 UITableViewDataSource,
7590 _transient Database *database_;
7592 NSMutableArray *sources_;
7596 UIProgressHUD *hud_;
7599 //NSURLConnection *installer_;
7600 NSURLConnection *trivial_;
7601 NSURLConnection *trivial_bz2_;
7602 NSURLConnection *trivial_gz_;
7603 //NSURLConnection *automatic_;
7608 - (id) initWithDatabase:(Database *)database;
7609 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7613 @implementation SourcesController
7615 - (void) _releaseConnection:(NSURLConnection *)connection {
7616 if (connection != nil) {
7617 [connection cancel];
7618 //[connection setDelegate:nil];
7619 [connection release];
7624 [self releaseSubviews];
7630 //[self _releaseConnection:installer_];
7631 [self _releaseConnection:trivial_];
7632 [self _releaseConnection:trivial_gz_];
7633 [self _releaseConnection:trivial_bz2_];
7634 //[self _releaseConnection:automatic_];
7640 - (NSURL *) navigationURL {
7641 return [NSURL URLWithString:@"cydia://sources"];
7644 - (void) viewDidAppear:(BOOL)animated {
7645 [super viewDidAppear:animated];
7646 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7649 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7650 return offset_ == 0 ? 1 : 2;
7653 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7654 switch (section + (offset_ == 0 ? 1 : 0)) {
7655 case 0: return UCLocalize("ENTERED_BY_USER");
7656 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7662 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7663 int count = [sources_ count];
7665 case 0: return (offset_ == 0 ? count : offset_);
7666 case 1: return count - offset_;
7672 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7674 switch (indexPath.section) {
7675 case 0: idx = indexPath.row; break;
7676 case 1: idx = indexPath.row + offset_; break;
7680 return [sources_ objectAtIndex:idx];
7683 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7684 static NSString *cellIdentifier = @"SourceCell";
7686 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7687 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7688 [cell setSource:[self sourceAtIndexPath:indexPath]];
7689 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7694 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7695 Source *source = [self sourceAtIndexPath:indexPath];
7697 SourceController *controller = [[[SourceController alloc]
7698 initWithDatabase:database_
7702 [controller setDelegate:delegate_];
7704 [[self navigationController] pushViewController:controller animated:YES];
7707 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7708 Source *source = [self sourceAtIndexPath:indexPath];
7709 return [source record] != nil;
7712 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7713 Source *source = [self sourceAtIndexPath:indexPath];
7714 [Sources_ removeObjectForKey:[source key]];
7715 [delegate_ syncData];
7719 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
7722 @"./", @"Distribution",
7723 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
7725 [delegate_ syncData];
7728 - (NSString *) getWarning {
7729 NSString *href(href_);
7730 NSRange colon([href rangeOfString:@"://"]);
7731 if (colon.location != NSNotFound)
7732 href = [href substringFromIndex:(colon.location + 3)];
7733 href = [href stringByAddingPercentEscapes];
7734 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7735 href = [href stringByCachingURLWithCurrentCDN];
7737 NSURL *url([NSURL URLWithString:href]);
7739 NSStringEncoding encoding;
7740 NSError *error(nil);
7742 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7743 return [warning length] == 0 ? nil : warning;
7747 - (void) _endConnection:(NSURLConnection *)connection {
7748 // XXX: the memory management in this method is horribly awkward
7750 NSURLConnection **field = NULL;
7751 if (connection == trivial_)
7753 else if (connection == trivial_bz2_)
7754 field = &trivial_bz2_;
7755 else if (connection == trivial_gz_)
7756 field = &trivial_gz_;
7757 _assert(field != NULL);
7758 [connection release];
7763 trivial_bz2_ == nil &&
7769 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7772 UIAlertView *alert = [[[UIAlertView alloc]
7773 initWithTitle:UCLocalize("SOURCE_WARNING")
7776 cancelButtonTitle:UCLocalize("CANCEL")
7777 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
7780 [alert setContext:@"warning"];
7781 [alert setNumberOfRows:1];
7785 } else if (error_ != nil) {
7786 UIAlertView *alert = [[[UIAlertView alloc]
7787 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7788 message:[error_ localizedDescription]
7790 cancelButtonTitle:UCLocalize("OK")
7791 otherButtonTitles:nil
7794 [alert setContext:@"urlerror"];
7797 UIAlertView *alert = [[[UIAlertView alloc]
7798 initWithTitle:UCLocalize("NOT_REPOSITORY")
7799 message:UCLocalize("NOT_REPOSITORY_EX")
7801 cancelButtonTitle:UCLocalize("OK")
7802 otherButtonTitles:nil
7805 [alert setContext:@"trivial"];
7809 [delegate_ setStatusBarShowsProgress:NO];
7810 [delegate_ removeProgressHUD:hud_];
7820 if (error_ != nil) {
7827 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
7828 switch ([response statusCode]) {
7834 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
7835 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7837 error_ = [error retain];
7838 [self _endConnection:connection];
7841 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
7842 [self _endConnection:connection];
7845 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
7846 NSMutableURLRequest *request = [NSMutableURLRequest
7847 requestWithURL:[NSURL URLWithString:href]
7848 cachePolicy:NSURLRequestUseProtocolCachePolicy
7849 timeoutInterval:120.0
7852 [request setHTTPMethod:method];
7854 if (Machine_ != NULL)
7855 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
7856 if (UniqueID_ != nil)
7857 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
7859 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
7861 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
7864 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7865 NSString *context([alert context]);
7867 if ([context isEqualToString:@"source"]) {
7870 NSString *href = [[alert textField] text];
7872 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
7874 if (![href hasSuffix:@"/"])
7875 href_ = [href stringByAppendingString:@"/"];
7878 href_ = [href_ retain];
7880 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
7881 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
7882 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
7883 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
7887 // XXX: this is stupid
7888 hud_ = [[delegate_ addProgressHUD] retain];
7889 [hud_ setText:UCLocalize("VERIFYING_URL")];
7898 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7899 } else if ([context isEqualToString:@"trivial"])
7900 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7901 else if ([context isEqualToString:@"urlerror"])
7902 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7903 else if ([context isEqualToString:@"warning"]) {
7918 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7923 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7925 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7926 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7927 [list_ setRowHeight:56];
7928 [list_ setDataSource:self];
7929 [list_ setDelegate:self];
7930 [[self view] addSubview:list_];
7933 - (void) viewDidLoad {
7934 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
7935 [self updateButtonsForEditingStatus:NO animated:NO];
7938 - (void) releaseSubviews {
7943 - (id) initWithDatabase:(Database *)database {
7944 if ((self = [super init]) != nil) {
7945 database_ = database;
7946 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
7950 - (void) reloadData {
7954 if (!list.ReadMainList())
7957 [sources_ removeAllObjects];
7958 [sources_ addObjectsFromArray:[database_ sources]];
7960 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
7963 int count([sources_ count]);
7965 for (int i = 0; i != count; i++) {
7966 if ([[sources_ objectAtIndex:i] record] == nil)
7971 [list_ setEditing:NO];
7972 [self updateButtonsForEditingStatus:NO animated:NO];
7976 - (void) showAddSourcePrompt {
7977 UIAlertView *alert = [[[UIAlertView alloc]
7978 initWithTitle:UCLocalize("ENTER_APT_URL")
7981 cancelButtonTitle:UCLocalize("CANCEL")
7982 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
7985 [alert setContext:@"source"];
7986 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
7988 [alert setNumberOfRows:1];
7989 [alert addTextFieldWithValue:@"http://" label:@""];
7991 UITextInputTraits *traits = [[alert textField] textInputTraits];
7992 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7993 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7994 [traits setKeyboardType:UIKeyboardTypeURL];
7995 // XXX: UIReturnKeyDone
7996 [traits setReturnKeyType:UIReturnKeyNext];
8001 - (void) addButtonClicked {
8002 [self showAddSourcePrompt];
8005 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8006 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8007 initWithTitle:UCLocalize("ADD")
8008 style:UIBarButtonItemStylePlain
8010 action:@selector(addButtonClicked)
8011 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8013 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8014 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8015 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8017 action:@selector(editButtonClicked)
8018 ] autorelease] animated:animated];
8020 if (IsWildcat_ && !editing)
8021 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8022 initWithTitle:UCLocalize("SETTINGS")
8023 style:UIBarButtonItemStylePlain
8025 action:@selector(settingsButtonClicked)
8029 - (void) settingsButtonClicked {
8030 [delegate_ showSettings];
8033 - (void) editButtonClicked {
8034 [list_ setEditing:![list_ isEditing] animated:YES];
8036 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8042 /* Settings Controller {{{ */
8043 @interface SettingsController : CYViewController <
8044 UITableViewDataSource,
8047 _transient Database *database_;
8048 // XXX: ok, "roledelegate_"?...
8049 _transient id roledelegate_;
8050 UITableView *table_;
8051 UISegmentedControl *segment_;
8055 - (void) showDoneButton;
8056 - (void) resizeSegmentedControl;
8060 @implementation SettingsController
8063 [self releaseSubviews];
8069 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8071 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8072 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8073 [table_ setDelegate:self];
8074 [table_ setDataSource:self];
8075 [[self view] addSubview:table_];
8077 NSArray *items = [NSArray arrayWithObjects:
8079 UCLocalize("HACKER"),
8080 UCLocalize("DEVELOPER"),
8082 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8083 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8084 [container_ addSubview:segment_];
8087 - (void) viewDidLoad {
8088 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8091 if ([Role_ isEqualToString:@"User"]) index = 0;
8092 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8093 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8095 [segment_ setSelectedSegmentIndex:index];
8096 [self showDoneButton];
8099 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8100 [self resizeSegmentedControl];
8103 - (void) releaseSubviews {
8110 [container_ release];
8114 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8115 if ((self = [super init])) {
8116 database_ = database;
8117 roledelegate_ = delegate;
8121 - (void) resizeSegmentedControl {
8122 CGFloat width = [[self view] frame].size.width;
8123 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8126 - (void) viewWillAppear:(BOOL)animated {
8127 [super viewWillAppear:animated];
8129 [self resizeSegmentedControl];
8132 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8133 [self resizeSegmentedControl];
8136 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8137 [self resizeSegmentedControl];
8141 NSString *role(nil);
8143 switch ([segment_ selectedSegmentIndex]) {
8144 case 0: role = @"User"; break;
8145 case 1: role = @"Hacker"; break;
8146 case 2: role = @"Developer"; break;
8151 if (![role isEqualToString:Role_]) {
8152 bool rolling(Role_ == nil);
8155 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8159 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8163 [roledelegate_ loadData];
8165 [roledelegate_ updateData];
8169 - (void) segmentChanged:(UISegmentedControl *)control {
8170 [self showDoneButton];
8173 - (void) saveAndClose {
8176 [[self navigationItem] setRightBarButtonItem:nil];
8177 [[self navigationController] dismissModalViewControllerAnimated:YES];
8180 - (void) doneButtonClicked {
8181 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8182 [spinner startAnimating];
8183 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8184 [[self navigationItem] setRightBarButtonItem:spinItem];
8186 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8189 - (void) showDoneButton {
8190 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8191 initWithTitle:UCLocalize("DONE")
8192 style:UIBarButtonItemStyleDone
8194 action:@selector(doneButtonClicked)
8195 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8198 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8199 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8203 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8207 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8208 return nil; // This method is required by the protocol.
8211 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8213 return UCLocalize("ROLE_EX");
8215 return [NSString stringWithFormat:
8216 @"%@: %@\n%@: %@\n%@: %@",
8217 UCLocalize("USER"), UCLocalize("USER_EX"),
8218 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8219 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8224 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8225 return section == 3 ? 44.0f : 0;
8228 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8229 return section == 3 ? container_ : nil;
8232 - (void) reloadData {
8234 [table_ reloadData];
8239 /* Stash Controller {{{ */
8240 @interface StashController : CYViewController {
8241 UIActivityIndicatorView *spinner_;
8247 @implementation StashController
8250 [self releaseSubviews];
8256 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8257 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8259 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8260 CGRect spinrect = [spinner_ frame];
8261 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8262 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8263 [spinner_ setFrame:spinrect];
8264 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8265 [[self view] addSubview:spinner_];
8266 [spinner_ startAnimating];
8269 captrect.size.width = [[self view] frame].size.width;
8270 captrect.size.height = 40.0f;
8271 captrect.origin.x = 0;
8272 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8273 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8274 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8275 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8276 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8277 [caption_ setTextColor:[UIColor whiteColor]];
8278 [caption_ setBackgroundColor:[UIColor clearColor]];
8279 [caption_ setShadowColor:[UIColor blackColor]];
8280 [caption_ setTextAlignment:UITextAlignmentCenter];
8281 [[self view] addSubview:caption_];
8284 statusrect.size.width = [[self view] frame].size.width;
8285 statusrect.size.height = 30.0f;
8286 statusrect.origin.x = 0;
8287 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8288 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8289 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8290 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8291 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8292 [status_ setTextColor:[UIColor whiteColor]];
8293 [status_ setBackgroundColor:[UIColor clearColor]];
8294 [status_ setShadowColor:[UIColor blackColor]];
8295 [status_ setTextAlignment:UITextAlignmentCenter];
8296 [[self view] addSubview:status_];
8299 - (void) releaseSubviews {
8313 @interface Cydia : UIApplication <
8314 ConfirmationControllerDelegate,
8315 ProgressControllerDelegate,
8317 UINavigationControllerDelegate,
8318 UITabBarControllerDelegate
8320 // XXX: evaluate all fields for _transient
8323 CYTabBarController *tabbar_;
8325 NSMutableArray *essential_;
8326 NSMutableArray *broken_;
8328 Database *database_;
8335 StashController *stash_;
8344 @implementation Cydia
8346 - (void) beginUpdate {
8347 [tabbar_ beginUpdate];
8351 return [tabbar_ updating];
8355 if ([broken_ count] != 0) {
8356 int count = [broken_ count];
8358 UIAlertView *alert = [[[UIAlertView alloc]
8359 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8360 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8362 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8363 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8366 [alert setContext:@"fixhalf"];
8368 } else if (!Ignored_ && [essential_ count] != 0) {
8369 int count = [essential_ count];
8371 UIAlertView *alert = [[[UIAlertView alloc]
8372 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8373 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8375 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8376 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8379 [alert setContext:@"upgrade"];
8384 - (void) _saveConfig {
8390 NSString *error(nil);
8392 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8394 NSError *error(nil);
8395 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8396 NSLog(@"failure to save metadata data: %@", error);
8401 NSLog(@"failure to serialize metadata: %@", error);
8406 // Navigation controller for the queuing badge.
8407 - (CYNavigationController *) queueNavigationController {
8408 NSArray *controllers = [tabbar_ viewControllers];
8409 return [controllers objectAtIndex:3];
8412 - (void) _updateData {
8415 [tabbar_ reloadData];
8417 CYNavigationController *navigation = [self queueNavigationController];
8419 id queuedelegate = nil;
8420 if ([[navigation viewControllers] count] > 0)
8421 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8423 [queuedelegate queueStatusDidChange];
8424 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8427 - (void) _refreshIfPossible {
8428 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8430 bool recently = false;
8431 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8432 if (update != nil) {
8433 NSTimeInterval interval([update timeIntervalSinceNow]);
8434 if (interval <= 0 && interval > -(15*60))
8438 // Don't automatic refresh if:
8439 // - We already refreshed recently.
8440 // - We already auto-refreshed this launch.
8441 // - Auto-refresh is disabled.
8442 if (recently || loaded_ || ManualRefresh) {
8443 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8445 // If we are cancelling, we need to make sure it knows it's already loaded.
8449 // We are going to load, so remember that.
8453 SCNetworkReachabilityFlags flags; {
8454 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8455 SCNetworkReachabilityGetFlags(reachability, &flags);
8456 CFRelease(reachability);
8459 // XXX: this elaborate mess is what Apple is using to determine this? :(
8460 // XXX: do we care if the user has to intervene? maybe that's ok?
8462 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8463 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8464 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8465 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8466 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8467 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8471 // If we can reach the server, auto-refresh!
8473 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8478 - (void) refreshIfPossible {
8479 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8482 - (void) _reloadData {
8483 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8484 [hud setText:UCLocalize("RELOADING_DATA")];
8486 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8489 [self removeProgressHUD:hud];
8493 [essential_ removeAllObjects];
8494 [broken_ removeAllObjects];
8496 NSArray *packages([database_ packages]);
8497 for (Package *package in packages) {
8499 [broken_ addObject:package];
8500 if ([package upgradableAndEssential:NO]) {
8501 if ([package essential])
8502 [essential_ addObject:package];
8507 NSLog(@"changes:#%u", changes);
8509 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8512 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8513 [changesItem setBadgeValue:badge];
8514 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8515 [self setApplicationIconBadgeNumber:changes];
8518 [changesItem setBadgeValue:nil];
8519 [changesItem setAnimatedBadge:NO];
8520 [self setApplicationIconBadgeNumber:0];
8525 [self refreshIfPossible];
8528 - (void) updateData {
8537 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8538 _assert(file != NULL);
8540 for (NSString *key in [Sources_ allKeys]) {
8541 NSDictionary *source([Sources_ objectForKey:key]);
8543 fprintf(file, "%s %s %s\n",
8544 [[source objectForKey:@"Type"] UTF8String],
8545 [[source objectForKey:@"URI"] UTF8String],
8546 [[source objectForKey:@"Distribution"] UTF8String]
8554 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8555 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8557 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8558 [tabbar_ presentModalViewController:navigation animated:YES];
8561 detachNewThreadSelector:@selector(update_)
8564 title:UCLocalize("UPDATING_SOURCES")
8568 - (void) reloadData {
8569 @synchronized (self) {
8575 pkgProblemResolver *resolver = [database_ resolver];
8577 resolver->InstallProtect();
8578 if (!resolver->Resolve(true))
8583 if (![database_ prepare])
8586 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8587 [page setDelegate:self];
8588 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8589 [confirm_ setDelegate:self];
8592 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8593 [tabbar_ presentModalViewController:confirm_ animated:YES];
8599 @synchronized (self) {
8604 - (void) clearPackage:(Package *)package {
8605 @synchronized (self) {
8612 - (void) installPackages:(NSArray *)packages {
8613 @synchronized (self) {
8614 for (Package *package in packages)
8621 - (void) installPackage:(Package *)package {
8622 @synchronized (self) {
8629 - (void) removePackage:(Package *)package {
8630 @synchronized (self) {
8637 - (void) distUpgrade {
8638 @synchronized (self) {
8639 if (![database_ upgrade])
8646 @synchronized (self) {
8651 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8654 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8656 if (navigation != nil) {
8657 [navigation pushViewController:progress animated:YES];
8659 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8661 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8662 [tabbar_ presentModalViewController:navigation animated:YES];
8666 detachNewThreadSelector:@selector(perform)
8669 title:UCLocalize("RUNNING")
8675 - (void) progressControllerIsComplete:(ProgressController *)progress {
8680 - (void) showSettings {
8681 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8682 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8684 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8685 [tabbar_ presentModalViewController:nav animated:YES];
8688 - (void) retainNetworkActivityIndicator {
8689 if (activity_++ == 0)
8690 [self setNetworkActivityIndicatorVisible:YES];
8693 - (void) releaseNetworkActivityIndicator {
8694 if (--activity_ == 0)
8695 [self setNetworkActivityIndicatorVisible:NO];
8698 - (void) cancelAndClear:(bool)clear {
8699 @synchronized (self) {
8711 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8712 NSString *context([alert context]);
8714 if ([context isEqualToString:@"fixhalf"]) {
8715 if (button == [alert firstOtherButtonIndex]) {
8716 @synchronized (self) {
8717 for (Package *broken in broken_) {
8720 NSString *id = [broken id];
8721 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8722 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8723 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8724 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8730 } else if (button == [alert cancelButtonIndex]) {
8731 [broken_ removeAllObjects];
8735 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8736 } else if ([context isEqualToString:@"upgrade"]) {
8737 if (button == [alert firstOtherButtonIndex]) {
8738 @synchronized (self) {
8739 for (Package *essential in essential_)
8740 [essential install];
8745 } else if (button == [alert firstOtherButtonIndex] + 1) {
8747 } else if (button == [alert cancelButtonIndex]) {
8751 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8755 - (void) system:(NSString *)command { _pooled
8757 system([command UTF8String]);
8761 - (void) applicationWillSuspend {
8763 [super applicationWillSuspend];
8766 - (BOOL) isSafeToSuspend {
8767 // Use external process status API internally.
8768 // This is probably a really bad idea.
8769 // XXX: what is the point of this? does this solve anything at all?
8770 uint64_t status = 0;
8772 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8773 notify_get_state(notify_token, &status);
8774 notify_cancel(notify_token);
8777 return locked_ == 0 && status == 0;
8780 - (void) applicationSuspend:(__GSEvent *)event {
8781 if ([self isSafeToSuspend])
8782 [super applicationSuspend:event];
8785 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8786 if ([self isSafeToSuspend])
8787 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8790 - (void) _setSuspended:(BOOL)value {
8791 if ([self isSafeToSuspend])
8792 [super _setSuspended:value];
8795 - (UIProgressHUD *) addProgressHUD {
8796 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8797 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8799 [window_ setUserInteractionEnabled:NO];
8802 UIViewController *target = tabbar_;
8803 while ([target modalViewController] != nil) target = [target modalViewController];
8804 [[target view] addSubview:hud];
8810 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8812 [hud removeFromSuperview];
8813 [window_ setUserInteractionEnabled:YES];
8817 - (CYViewController *) pageForPackage:(NSString *)name {
8818 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_] autorelease]);
8819 [view setPackage:[database_ packageWithName:name] withName:name];
8823 - (CYViewController *) pageForURL:(NSURL *)url {
8824 NSString *scheme([[url scheme] lowercaseString]);
8825 if ([[url absoluteString] length] <= [scheme length] + 3)
8827 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
8828 NSArray *components([path pathComponents]);
8830 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
8831 return [self pageForPackage:[components objectAtIndex:1]];
8833 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
8836 NSString *base([components objectAtIndex:0]);
8838 CYViewController *controller = nil;
8840 if ([base isEqualToString:@"url"]) {
8841 // This kind of URL can contain slashes in the argument, so we can't parse them below.
8842 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
8843 controller = [[[CYBrowserController alloc] init] autorelease];
8844 [(CYBrowserController *)controller loadURL:[NSURL URLWithString:destination]];
8845 } else if ([components count] == 1) {
8846 if ([base isEqualToString:@"storage"]) {
8847 controller = [[[CYBrowserController alloc] init] autorelease];
8848 [(CYBrowserController *)controller loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]]];
8851 if ([base isEqualToString:@"manage"]) {
8852 controller = [[[ManageController alloc] init] autorelease];
8855 if ([base isEqualToString:@"sources"]) {
8856 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8859 if ([base isEqualToString:@"home"]) {
8860 controller = [[[HomeController alloc] init] autorelease];
8863 if ([base isEqualToString:@"sections"]) {
8864 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
8867 if ([base isEqualToString:@"search"]) {
8868 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8871 if ([base isEqualToString:@"changes"]) {
8872 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
8875 if ([base isEqualToString:@"installed"]) {
8876 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8878 } else if ([components count] == 2) {
8879 NSString *argument = [components objectAtIndex:1];
8881 if ([base isEqualToString:@"package"]) {
8882 controller = [self pageForPackage:argument];
8885 if ([base isEqualToString:@"search"]) {
8886 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8887 [(SearchController *)controller setSearchTerm:argument];
8890 if ([base isEqualToString:@"sections"]) {
8891 if ([argument isEqualToString:@"all"])
8893 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
8896 if ([base isEqualToString:@"sources"]) {
8897 if ([argument isEqualToString:@"add"]) {
8898 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8899 [(SourcesController *)controller showAddSourcePrompt];
8901 NSArray *sources = [database_ sources];
8902 for (Source *source in sources) {
8903 if ([[source name] caseInsensitiveCompare:argument] == NSOrderedSame) {
8904 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
8911 if ([base isEqualToString:@"launch"]) {
8912 [self launchApplicationWithIdentifier:argument suspended:NO];
8915 } else if ([components count] == 3) {
8916 NSString *arg1 = [components objectAtIndex:1];
8917 NSString *arg2 = [components objectAtIndex:2];
8919 if ([base isEqualToString:@"package"]) {
8920 if ([arg2 isEqualToString:@"settings"]) {
8921 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
8922 } else if ([arg2 isEqualToString:@"files"]) {
8923 if (Package *package = [database_ packageWithName:arg1]) {
8924 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8925 [(FileTable *)controller setPackage:package];
8931 [controller setDelegate:self];
8935 - (BOOL) openCydiaURL:(NSURL *)url {
8936 CYViewController *page([self pageForURL:url]);
8939 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
8940 [nav setViewControllers:[NSArray arrayWithObject:page]];
8941 [tabbar_ setTransientViewController:nav];
8947 - (void) applicationOpenURL:(NSURL *)url {
8948 [super applicationOpenURL:url];
8950 if (!loaded_) starturl_ = [url retain];
8951 else [self openCydiaURL:url];
8954 - (void) applicationWillResignActive:(UIApplication *)application {
8955 // Stop refreshing if you get a phone call or lock the device.
8956 if ([tabbar_ updating])
8957 [tabbar_ cancelUpdate];
8959 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8960 [super applicationWillResignActive:application];
8963 - (void) applicationWillTerminate:(UIApplication *)application {
8965 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
8966 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
8967 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
8972 - (void) addStashController {
8974 stash_ = [[StashController alloc] init];
8975 [window_ addSubview:[stash_ view]];
8978 - (void) removeStashController {
8979 [[stash_ view] removeFromSuperview];
8985 [self setIdleTimerDisabled:YES];
8987 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8988 [self setStatusBarShowsProgress:YES];
8989 UpdateExternalStatus(1);
8991 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8993 UpdateExternalStatus(0);
8994 [self setStatusBarShowsProgress:NO];
8996 [self removeStashController];
8998 if (ExecFork() == 0) {
8999 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9000 perror("launchctl stop");
9004 - (void) setupViewControllers {
9005 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9006 [tabbar_ setDelegate:self];
9008 NSMutableArray *items([NSMutableArray arrayWithObjects:
9009 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9010 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9011 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9012 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9016 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9017 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9019 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9022 NSMutableArray *controllers([NSMutableArray array]);
9023 for (UITabBarItem *item in items) {
9024 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9025 [controller setTabBarItem:item];
9026 [controllers addObject:controller];
9028 [tabbar_ setViewControllers:controllers];
9030 [tabbar_ setUpdateDelegate:self];
9033 - (CYEmulatedLoadingController *)showEmulatedLoadingControllerInView:(UIView *)view {
9034 static CYEmulatedLoadingController *fake = [[CYEmulatedLoadingController alloc] init];
9036 [view addSubview:[fake view]];
9038 [[fake view] removeFromSuperview];
9044 - (void) applicationDidFinishLaunching:(id)unused {
9048 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9049 [self setApplicationSupportsShakeToEdit:NO];
9051 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9052 initWithMemoryCapacity:524288
9053 diskCapacity:10485760
9054 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9057 [CYBrowserController _initialize];
9059 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9061 Font12_ = [[UIFont systemFontOfSize:12] retain];
9062 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9063 Font14_ = [[UIFont systemFontOfSize:14] retain];
9064 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9065 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9067 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9068 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9070 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9071 [window_ orderFront:self];
9072 [window_ makeKey:self];
9073 [window_ setHidden:NO];
9076 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9077 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9078 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9079 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9080 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9081 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9082 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9083 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9084 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9087 [self addStashController];
9088 // XXX: this would be much cleaner as a yieldToSelector:
9089 // that way the removeStashController could happen right here inline
9090 // we also could no longer require the useless stash_ field anymore
9091 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9095 database_ = [Database sharedInstance];
9097 [window_ setUserInteractionEnabled:NO];
9098 [self setupViewControllers];
9099 [self showEmulatedLoadingControllerInView:window_];
9101 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9108 [window_ setUserInteractionEnabled:YES];
9110 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9111 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9113 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9114 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9118 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9119 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9120 [window_ setUserInteractionEnabled:NO];
9126 [window_ addSubview:[tabbar_ view]];
9127 [self showEmulatedLoadingControllerInView:nil];
9128 [window_ setUserInteractionEnabled:YES];
9130 int selectedIndex = 0;
9131 NSMutableArray *items = nil;
9133 bool recently = false;
9134 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9135 if (closed != nil) {
9136 NSTimeInterval interval([closed timeIntervalSinceNow]);
9137 // XXX: Is 15 minutes the optimal time here?
9138 if (interval <= 0 && interval > -(15*60))
9142 if (recently && [Metadata_ objectForKey:@"InterfaceState"]) {
9143 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9144 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9146 items = [NSMutableArray array];
9147 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9148 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9149 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9151 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9153 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9154 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9156 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9159 [tabbar_ setSelectedIndex:selectedIndex];
9160 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9161 NSArray *stack = [items objectAtIndex:tab];
9162 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9163 NSMutableArray *current = [NSMutableArray array];
9165 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9166 NSString *addr = [stack objectAtIndex:nav];
9167 NSURL *url = [NSURL URLWithString:addr];
9168 CYViewController *page = [self pageForURL:url];
9170 [current addObject:page];
9173 [navigation setViewControllers:current];
9176 // (Try to) show the startup URL.
9177 if (starturl_ != nil) {
9178 [self openCydiaURL:starturl_];
9179 [starturl_ release];
9184 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9185 if (item != nil && IsWildcat_) {
9186 [sheet showFromBarButtonItem:item animated:YES];
9188 [sheet showInView:window_];
9195 id Alloc_(id self, SEL selector) {
9196 id object = alloc_(self, selector);
9197 lprintf("[%s]A-%p\n", self->isa->name, object);
9202 id Dealloc_(id self, SEL selector) {
9203 id object = dealloc_(self, selector);
9204 lprintf("[%s]D-%p\n", self->isa->name, object);
9208 Class $WebDefaultUIKitDelegate;
9210 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9211 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9212 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9213 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9216 static NSNumber *shouldPlayKeyboardSounds;
9220 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9222 case 1104: // Keyboard Button Clicked
9223 case 1105: // Keyboard Delete Repeated
9224 if (shouldPlayKeyboardSounds == nil) {
9225 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9226 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9229 if (![shouldPlayKeyboardSounds boolValue])
9233 _UIHardware$_playSystemSound$(self, _cmd, sound);
9237 Class $UIApplication;
9239 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9240 static BOOL initialized = NO;
9241 static BOOL started = NO;
9243 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9244 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9246 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9247 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9248 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9249 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9251 if (initialized && !enabled) {
9253 [bundle performSelector:@selector(_accessibilityStopServer)];
9254 } else if (enabled) {
9258 [bundle performSelector:@selector(_accessibilityStartServer)];
9264 int main(int argc, char *argv[]) { _pooled
9267 if (Class $UIDevice = objc_getClass("UIDevice")) {
9268 UIDevice *device([$UIDevice currentDevice]);
9269 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9273 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9275 /* Library Hacks {{{ */
9276 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9278 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9279 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9280 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9281 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9282 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9285 $UIHardware = objc_getClass("UIHardware");
9286 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9287 if (UIHardware$_playSystemSound$ != NULL) {
9288 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9289 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9292 $UIApplication = objc_getClass("UIApplication");
9293 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9294 if (UIApplication$_updateApplicationAccessibility != NULL) {
9295 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9296 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9299 /* Set Locale {{{ */
9300 Locale_ = CFLocaleCopyCurrent();
9301 Languages_ = [NSLocale preferredLanguages];
9302 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9303 //NSLog(@"%@", [Languages_ description]);
9306 if (Languages_ == nil || [Languages_ count] == 0)
9307 // XXX: consider just setting to C and then falling through?
9310 lang = [[Languages_ objectAtIndex:0] UTF8String];
9311 setenv("LANG", lang, true);
9314 //std::setlocale(LC_ALL, lang);
9315 NSLog(@"Setting Language: %s", lang);
9318 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9320 /* Parse Arguments {{{ */
9321 bool substrate(false);
9327 for (int argi(1); argi != argc; ++argi)
9328 if (strcmp(argv[argi], "--") == 0) {
9330 argv[argi] = argv[0];
9336 for (int argi(1); argi != arge; ++argi)
9337 if (strcmp(args[argi], "--substrate") == 0)
9340 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9344 App_ = [[NSBundle mainBundle] bundlePath];
9345 Home_ = NSHomeDirectory();
9351 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9352 alloc_ = alloc->method_imp;
9353 alloc->method_imp = (IMP) &Alloc_;*/
9355 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9356 dealloc_ = dealloc->method_imp;
9357 dealloc->method_imp = (IMP) &Dealloc_;*/
9359 /* System Information {{{ */
9363 size = sizeof(maxproc);
9364 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9365 perror("sysctlbyname(\"kern.maxproc\", ?)");
9366 else if (maxproc < 64) {
9368 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9369 perror("sysctlbyname(\"kern.maxproc\", #)");
9372 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9373 char *osversion = new char[size];
9374 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9375 perror("sysctlbyname(\"kern.osversion\", ?)");
9377 System_ = [NSString stringWithUTF8String:osversion];
9379 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9380 char *machine = new char[size];
9381 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9382 perror("sysctlbyname(\"hw.machine\", ?)");
9386 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9387 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9388 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9389 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9393 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9394 NSData *data((NSData *) ecid);
9395 size_t length([data length]);
9396 uint8_t bytes[length];
9397 [data getBytes:bytes];
9398 char string[length * 2 + 1];
9399 for (size_t i(0); i != length; ++i)
9400 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9401 ChipID_ = [NSString stringWithUTF8String:string];
9405 IOObjectRelease(service);
9409 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9411 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9412 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9413 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9415 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9416 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9417 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9419 if (mcc != NULL && mnc != NULL)
9420 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9427 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9428 Build_ = [system objectForKey:@"ProductBuildVersion"];
9429 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9430 Product_ = [info objectForKey:@"SafariProductVersion"];
9431 Safari_ = [info objectForKey:@"CFBundleVersion"];
9434 /* Load Database {{{ */
9436 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9438 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9440 if (Metadata_ == NULL)
9441 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9443 Settings_ = [Metadata_ objectForKey:@"Settings"];
9445 Packages_ = [Metadata_ objectForKey:@"Packages"];
9446 Sections_ = [Metadata_ objectForKey:@"Sections"];
9447 Sources_ = [Metadata_ objectForKey:@"Sources"];
9449 Token_ = [Metadata_ objectForKey:@"Token"];
9452 if (Settings_ != nil)
9453 Role_ = [Settings_ objectForKey:@"Role"];
9455 if (Sections_ == nil) {
9456 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9457 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9460 if (Sources_ == nil) {
9461 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9462 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9467 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9470 if (Packages_ != nil) {
9472 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9476 [Metadata_ removeObjectForKey:@"Packages"];
9482 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9484 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9485 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9486 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9487 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9488 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9489 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9491 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9493 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9494 unlink("/tmp/.cydia.fw");
9496 } else if (access("/User", F_OK) != 0 || version < 2) {
9499 system("/usr/libexec/cydia/firmware.sh");
9503 _assert([[NSFileManager defaultManager]
9504 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9505 withIntermediateDirectories:YES
9510 if (access("/tmp/cydia.chk", F_OK) == 0) {
9511 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9512 _assert(errno == ENOENT);
9513 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9514 _assert(errno == ENOENT);
9517 /* APT Initialization {{{ */
9518 _assert(pkgInitConfig(*_config));
9519 _assert(pkgInitSystem(*_config, _system));
9522 _config->Set("APT::Acquire::Translation", lang);
9524 // XXX: this timeout might be important :(
9525 //_config->Set("Acquire::http::Timeout", 15);
9527 _config->Set("Acquire::http::MaxParallel", 3);
9529 /* Color Choices {{{ */
9530 space_ = CGColorSpaceCreateDeviceRGB();
9532 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9533 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9534 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9535 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9536 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9537 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9538 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9539 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9540 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9542 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9543 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9545 /* UIKit Configuration {{{ */
9546 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9547 if ($GSFontSetUseLegacyFontMetrics != NULL)
9548 $GSFontSetUseLegacyFontMetrics(YES);
9550 // XXX: I have a feeling this was important
9551 //UIKeyboardDisableAutomaticAppearance();
9554 Colon_ = UCLocalize("COLON_DELIMITED");
9555 Elision_ = UCLocalize("ELISION");
9556 Error_ = UCLocalize("ERROR");
9557 Warning_ = UCLocalize("WARNING");
9560 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9562 CGColorSpaceRelease(space_);