1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 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 void NSLogPoint(const char *fix, const CGPoint &point) {
221 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
224 void NSLogRect(const char *fix, const CGRect &rect) {
225 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
228 static _finline NSString *CydiaURL(NSString *path) {
230 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
231 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
232 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
233 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
234 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
235 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
238 static _finline void UpdateExternalStatus(uint64_t newStatus) {
240 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
241 notify_set_state(notify_token, newStatus);
242 notify_cancel(notify_token);
244 notify_post("com.saurik.Cydia.status");
247 /* [NSObject yieldToSelector:(withObject:)] {{{*/
248 @interface NSObject (Cydia)
249 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
250 - (id) yieldToSelector:(SEL)selector;
253 @implementation NSObject (Cydia)
258 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
259 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
260 id object([[context objectAtIndex:1] nonretainedObjectValue]);
261 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
263 /* XXX: deal with exceptions */
264 id value([self performSelector:selector withObject:object]);
266 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
267 [context removeAllObjects];
268 if ([signature methodReturnLength] != 0 && value != nil)
269 [context addObject:value];
274 performSelectorOnMainThread:@selector(doNothing)
280 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
281 volatile bool stopped(false);
283 NSMutableArray *context([NSMutableArray arrayWithObjects:
284 [NSValue valueWithPointer:selector],
285 [NSValue valueWithNonretainedObject:object],
286 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
289 NSThread *thread([[[NSThread alloc]
291 selector:@selector(_yieldToContext:)
297 NSRunLoop *loop([NSRunLoop currentRunLoop]);
298 NSDate *future([NSDate distantFuture]);
300 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
302 return [context count] == 0 ? nil : [context objectAtIndex:0];
305 - (id) yieldToSelector:(SEL)selector {
306 return [self yieldToSelector:selector withObject:nil];
312 /* Cydia Action Sheet {{{ */
313 @interface CYActionSheet : UIAlertView {
317 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
320 @implementation CYActionSheet
322 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
323 if ((self = [super init])) {
324 [self setTitle:title];
325 [self setDelegate:self];
326 for (NSString *button in buttons) [self addButtonWithTitle:button];
327 [self setCancelButtonIndex:index];
331 - (void) _updateFrameForDisplay {
332 [super _updateFrameForDisplay];
333 if ([self cancelButtonIndex] == -1) {
334 NSArray *buttons = [self buttons];
335 if ([buttons count]) {
336 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
337 for (UIThreePartButton *button in buttons)
338 [button setBackground:background forState:0];
343 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
344 button_ = buttonIndex + 1;
348 [self dismissWithClickedButtonIndex:-1 animated:YES];
351 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
352 [self setRunsModal:YES];
361 /* NSForcedOrderingSearch doesn't work on the iPhone */
362 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
363 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
364 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
366 /* Information Dictionaries {{{ */
367 @interface NSMutableArray (Cydia)
368 - (void) addInfoDictionary:(NSDictionary *)info;
371 @implementation NSMutableArray (Cydia)
373 - (void) addInfoDictionary:(NSDictionary *)info {
374 [self addObject:info];
379 @interface NSMutableDictionary (Cydia)
380 - (void) addInfoDictionary:(NSDictionary *)info;
383 @implementation NSMutableDictionary (Cydia)
385 - (void) addInfoDictionary:(NSDictionary *)info {
386 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
392 #define lprintf(args...) fprintf(stderr, args)
395 #define TraceLogging (1 && !ForRelease)
396 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
397 #define ProfileTimes (0 && !ForRelease)
398 #define ForSaurik (0 && !ForRelease)
399 #define LogBrowser (0 && !ForRelease)
400 #define TrackResize (0 && !ForRelease)
401 #define ManualRefresh (1 && !ForRelease)
402 #define ShowInternals (0 && !ForRelease)
403 #define IgnoreInstall (0 && !ForRelease)
404 #define AlwaysReload (0 && !ForRelease)
408 #define _trace(args...)
413 #define _profile(name) {
416 #define PrintTimes() do {} while (false)
420 typedef uint32_t (*SKRadixFunction)(id, void *);
422 @interface NSMutableArray (Radix)
423 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
431 @implementation NSMutableArray (Radix)
433 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
434 size_t count([self count]);
435 struct RadixItem_ *swap(new RadixItem_[count * 2]);
437 for (size_t i(0); i != count; ++i) {
438 RadixItem_ &item(swap[i]);
441 id object([self objectAtIndex:i]);
442 item.key = function(object, argument);
445 struct RadixItem_ *lhs(swap), *rhs(swap + count);
447 static const size_t width = 32;
448 static const size_t bits = 11;
449 static const size_t slots = 1 << bits;
450 static const size_t passes = (width + (bits - 1)) / bits;
452 size_t *hist(new size_t[slots]);
454 for (size_t pass(0); pass != passes; ++pass) {
455 memset(hist, 0, sizeof(size_t) * slots);
457 for (size_t i(0); i != count; ++i) {
458 uint32_t key(lhs[i].key);
460 key &= _not(uint32_t) >> width - bits;
465 for (size_t i(0); i != slots; ++i) {
466 size_t local(offset);
471 for (size_t i(0); i != count; ++i) {
472 uint32_t key(lhs[i].key);
474 key &= _not(uint32_t) >> width - bits;
475 rhs[hist[key]++] = lhs[i];
478 RadixItem_ *tmp(lhs);
485 const void **values(new const void *[count]);
486 for (size_t i(0); i != count; ++i)
487 values[i] = [self objectAtIndex:lhs[i].index];
488 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
496 /* Insertion Sort {{{ */
498 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
499 const char *ptr = (const char *)list;
501 CFIndex half = count / 2;
502 const char *probe = ptr + elementSize * half;
503 CFComparisonResult cr = comparator(element, probe, context);
504 if (0 == cr) return (probe - (const char *)list) / elementSize;
505 ptr = (cr < 0) ? ptr : probe + elementSize;
506 count = (cr < 0) ? half : (half + (count & 1) - 1);
508 return (ptr - (const char *)list) / elementSize;
511 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
512 const char *ptr = (const char *)list;
514 CFIndex half = count / 2;
515 const char *probe = ptr + elementSize * half;
516 CFComparisonResult cr = comparator(element, probe, context);
517 if (0 == cr) return (probe - (const char *)list) / elementSize;
518 ptr = (cr < 0) ? ptr : probe + elementSize;
519 count = (cr < 0) ? half : (half + (count & 1) - 1);
521 return (ptr - (const char *)list) / elementSize;
524 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
525 if (range.length == 0)
527 const void **values(new const void *[range.length]);
528 CFArrayGetValues(array, range, values);
530 #if HistogramInsertionSort > 0
531 uint32_t total(0), *offsets(new uint32_t[range.length]);
534 for (CFIndex index(1); index != range.length; ++index) {
535 const void *value(values[index]);
536 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
537 CFIndex correct(index);
538 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
539 #if HistogramInsertionSort > 1
540 NSLog(@"%@ < %@", value, values[correct - 1]);
545 if (correct != index) {
546 size_t offset(index - correct);
547 #if HistogramInsertionSort
551 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
553 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
554 values[correct] = value;
558 CFArrayReplaceValues(array, range, values, range.length);
561 #if HistogramInsertionSort > 0
562 for (CFIndex index(0); index != range.length; ++index)
563 if (offsets[index] != 0)
564 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
565 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
572 /* Apple Bug Fixes {{{ */
573 @implementation UIWebDocumentView (Cydia)
575 - (void) _setScrollerOffset:(CGPoint)offset {
576 UIScroller *scroller([self _scroller]);
578 CGSize size([scroller contentSize]);
579 CGSize bounds([scroller bounds].size);
582 max.x = size.width - bounds.width;
583 max.y = size.height - bounds.height;
591 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
592 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
594 [scroller setOffset:offset];
600 @implementation WebScriptObject (NSFastEnumeration)
602 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
603 size_t length([self count] - state->state);
606 else if (length > count)
608 for (size_t i(0); i != length; ++i)
609 objects[i] = [self objectAtIndex:state->state++];
610 state->itemsPtr = objects;
611 state->mutationsPtr = (unsigned long *) self;
617 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
618 size_t length([self length] - state->state);
621 else if (length > count)
623 for (size_t i(0); i != length; ++i)
624 objects[i] = [self item:state->state++];
625 state->itemsPtr = objects;
626 state->mutationsPtr = (unsigned long *) self;
630 /* Cydia NSString Additions {{{ */
631 @interface NSString (Cydia)
632 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
633 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
634 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
635 - (NSComparisonResult) compareByPath:(NSString *)other;
636 - (NSString *) stringByCachingURLWithCurrentCDN;
637 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
640 @implementation NSString (Cydia)
642 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
643 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
646 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
647 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
648 memcpy(data, bytes, length);
649 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
652 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
653 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
656 - (NSComparisonResult) compareByPath:(NSString *)other {
657 NSString *prefix = [self commonPrefixWithString:other options:0];
658 size_t length = [prefix length];
660 NSRange lrange = NSMakeRange(length, [self length] - length);
661 NSRange rrange = NSMakeRange(length, [other length] - length);
663 lrange = [self rangeOfString:@"/" options:0 range:lrange];
664 rrange = [other rangeOfString:@"/" options:0 range:rrange];
666 NSComparisonResult value;
668 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
669 value = NSOrderedSame;
670 else if (lrange.location == NSNotFound)
671 value = NSOrderedAscending;
672 else if (rrange.location == NSNotFound)
673 value = NSOrderedDescending;
675 value = NSOrderedSame;
677 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
678 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
679 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
680 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
682 NSComparisonResult result = [lpath compare:rpath];
683 return result == NSOrderedSame ? value : result;
686 - (NSString *) stringByCachingURLWithCurrentCDN {
688 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
689 withString:@"://cache.cydia.saurik.com/"
693 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
694 return [(id)CFURLCreateStringByAddingPercentEscapes(
699 kCFStringEncodingUTF8
706 /* C++ NSString Wrapper Cache {{{ */
707 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
708 return size == 0 ? NULL :
709 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
710 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
713 static _finline CFStringRef CYStringCreate(const char *data) {
714 return CYStringCreate(data, strlen(data));
723 _finline void clear_() {
724 if (cache_ != NULL) {
731 _finline bool empty() const {
735 _finline size_t size() const {
739 _finline char *data() const {
743 _finline void clear() {
748 _finline CYString() :
755 _finline ~CYString() {
759 void operator =(const CYString &rhs) {
763 if (rhs.cache_ == nil)
766 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
769 void copy(apr_pool_t *pool) {
770 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
771 memcpy(temp, data_, size_);
776 void set(apr_pool_t *pool, const char *data, size_t size) {
782 data_ = const_cast<char *>(data);
790 _finline void set(apr_pool_t *pool, const char *data) {
791 set(pool, data, data == NULL ? 0 : strlen(data));
794 _finline void set(apr_pool_t *pool, const std::string &rhs) {
795 set(pool, rhs.data(), rhs.size());
798 bool operator ==(const CYString &rhs) const {
799 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
802 _finline operator CFStringRef() {
804 cache_ = CYStringCreate(data_, size_);
808 _finline operator id() {
809 return (NSString *) static_cast<CFStringRef>(*this);
812 _finline operator const char *() {
813 return reinterpret_cast<const char *>(data_);
817 /* C++ NSString Algorithm Adapters {{{ */
819 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
822 struct NSStringMapHash :
823 std::unary_function<NSString *, size_t>
825 _finline size_t operator ()(NSString *value) const {
826 return CFStringHashNSString((CFStringRef) value);
830 struct NSStringMapLess :
831 std::binary_function<NSString *, NSString *, bool>
833 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
834 return [lhs compare:rhs] == NSOrderedAscending;
838 struct NSStringMapEqual :
839 std::binary_function<NSString *, NSString *, bool>
841 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
842 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
843 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
844 //[lhs isEqualToString:rhs];
849 /* Perl-Compatible RegEx {{{ */
859 Pcre(const char *regex) :
864 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
867 lprintf("%d:%s\n", offset, error);
871 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
872 matches_ = new int[(capture_ + 1) * 3];
880 NSString *operator [](size_t match) {
881 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
884 bool operator ()(NSString *data) {
885 // XXX: length is for characters, not for bytes
886 return operator ()([data UTF8String], [data length]);
889 bool operator ()(const char *data, size_t size) {
891 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
895 /* Mime Addresses {{{ */
896 @interface Address : NSObject {
902 - (NSString *) address;
904 - (void) setAddress:(NSString *)address;
906 + (Address *) addressWithString:(NSString *)string;
907 - (Address *) initWithString:(NSString *)string;
910 @implementation Address
919 - (NSString *) name {
923 - (NSString *) address {
927 - (void) setAddress:(NSString *)address {
929 [address_ autorelease];
933 address_ = [address retain];
936 + (Address *) addressWithString:(NSString *)string {
937 return [[[Address alloc] initWithString:string] autorelease];
940 + (NSArray *) _attributeKeys {
941 return [NSArray arrayWithObjects:@"address", @"name", nil];
944 - (NSArray *) attributeKeys {
945 return [[self class] _attributeKeys];
948 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
949 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
952 - (Address *) initWithString:(NSString *)string {
953 if ((self = [super init]) != nil) {
954 const char *data = [string UTF8String];
955 size_t size = [string length];
957 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
959 if (address_r(data, size)) {
960 name_ = [address_r[1] retain];
961 address_ = [address_r[2] retain];
963 name_ = [string retain];
971 /* CoreGraphics Primitives {{{ */
976 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
977 CGFloat color[] = {red, green, blue, alpha};
978 return CGColorCreate(space, color);
987 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
988 color_(Create_(space, red, green, blue, alpha))
990 Set(space, red, green, blue, alpha);
995 CGColorRelease(color_);
1002 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1004 color_ = Create_(space, red, green, blue, alpha);
1007 operator CGColorRef() {
1013 /* Random Global Variables {{{ */
1014 static const int PulseInterval_ = 50000;
1017 static NSArray *Finishes_;
1019 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1020 #define NotifyConfig_ "/etc/notify.conf"
1022 static bool Queuing_;
1024 static CYColor Blue_;
1025 static CYColor Blueish_;
1026 static CYColor Black_;
1027 static CYColor Off_;
1028 static CYColor White_;
1029 static CYColor Gray_;
1030 static CYColor Green_;
1031 static CYColor Purple_;
1032 static CYColor Purplish_;
1034 static UIColor *InstallingColor_;
1035 static UIColor *RemovingColor_;
1037 static NSString *App_;
1038 static NSString *Home_;
1040 static BOOL Advanced_;
1041 static BOOL Ignored_;
1043 static UIFont *Font12_;
1044 static UIFont *Font12Bold_;
1045 static UIFont *Font14_;
1046 static UIFont *Font18Bold_;
1047 static UIFont *Font22Bold_;
1049 static const char *Machine_ = NULL;
1050 static NSString *System_ = nil;
1051 static NSString *SerialNumber_ = nil;
1052 static NSString *ChipID_ = nil;
1053 static NSString *Token_ = nil;
1054 static NSString *UniqueID_ = nil;
1055 static NSString *PLMN_ = nil;
1056 static NSString *Build_ = nil;
1057 static NSString *Product_ = nil;
1058 static NSString *Safari_ = nil;
1060 static CFLocaleRef Locale_;
1061 static NSArray *Languages_;
1062 static CGColorSpaceRef space_;
1064 static NSDictionary *SectionMap_;
1065 static NSMutableDictionary *Metadata_;
1066 static _transient NSMutableDictionary *Settings_;
1067 static _transient NSString *Role_;
1068 static _transient NSMutableDictionary *Packages_;
1069 static _transient NSMutableDictionary *Sections_;
1070 static _transient NSMutableDictionary *Sources_;
1071 static bool Changed_;
1074 static bool IsWildcat_;
1077 /* Display Helpers {{{ */
1078 inline float Interpolate(float begin, float end, float fraction) {
1079 return (end - begin) * fraction + begin;
1082 /* XXX: localize this! */
1083 NSString *SizeString(double size) {
1084 bool negative = size < 0;
1089 while (size > 1024) {
1094 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1096 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1099 static _finline const char *StripVersion_(const char *version) {
1100 const char *colon(strchr(version, ':'));
1101 return colon == NULL ? version : colon + 1;
1104 NSString *LocalizeSection(NSString *section) {
1105 static Pcre title_r("^(.*?) \\((.*)\\)$");
1106 if (title_r(section)) {
1107 NSString *parent(title_r[1]);
1108 NSString *child(title_r[2]);
1110 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1111 LocalizeSection(parent),
1112 LocalizeSection(child)
1116 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1119 NSString *Simplify(NSString *title) {
1120 const char *data = [title UTF8String];
1121 size_t size = [title length];
1123 static Pcre square_r("^\\[(.*)\\]$");
1124 if (square_r(data, size))
1125 return Simplify(square_r[1]);
1127 static Pcre paren_r("^\\((.*)\\)$");
1128 if (paren_r(data, size))
1129 return Simplify(paren_r[1]);
1131 static Pcre title_r("^(.*?) \\((.*)\\)$");
1132 if (title_r(data, size))
1133 return Simplify(title_r[1]);
1139 NSString *GetLastUpdate() {
1140 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1143 return UCLocalize("NEVER_OR_UNKNOWN");
1145 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1146 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1148 CFRelease(formatter);
1150 return [(NSString *) formatted autorelease];
1153 bool isSectionVisible(NSString *section) {
1154 NSDictionary *metadata([Sections_ objectForKey:section]);
1155 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1156 return hidden == nil || ![hidden boolValue];
1161 /* Delegate Prototypes {{{ */
1165 @interface NSObject (ProgressDelegate)
1168 @protocol ProgressDelegate
1169 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1170 - (void) setProgressTitle:(NSString *)title;
1171 - (void) setProgressPercent:(float)percent;
1172 - (void) startProgress;
1173 - (void) addProgressOutput:(NSString *)output;
1174 - (bool) isCancelling:(size_t)received;
1177 @protocol ConfigurationDelegate
1178 - (void) repairWithSelector:(SEL)selector;
1179 - (void) setConfigurationData:(NSString *)data;
1182 @class CYPackageController;
1184 @protocol CydiaDelegate
1185 - (void) retainNetworkActivityIndicator;
1186 - (void) releaseNetworkActivityIndicator;
1187 - (void) setPackageController:(CYPackageController *)view;
1188 - (void) clearPackage:(Package *)package;
1189 - (void) installPackage:(Package *)package;
1190 - (void) installPackages:(NSArray *)packages;
1191 - (void) removePackage:(Package *)package;
1192 - (void) beginUpdate;
1194 - (void) distUpgrade;
1196 - (void) updateData;
1198 - (void) showSettings;
1199 - (UIProgressHUD *) addProgressHUD;
1200 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1201 - (CYViewController *) pageForPackage:(NSString *)name;
1202 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1205 static id<CydiaDelegate> CydiaApp;
1208 /* Status Delegation {{{ */
1210 public pkgAcquireStatus
1213 _transient NSObject<ProgressDelegate> *delegate_;
1221 void setDelegate(id delegate) {
1222 delegate_ = delegate;
1225 NSObject<ProgressDelegate> *getDelegate() const {
1229 virtual bool MediaChange(std::string media, std::string drive) {
1233 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1236 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1237 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1238 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1241 virtual void Done(pkgAcquire::ItemDesc &item) {
1244 virtual void Fail(pkgAcquire::ItemDesc &item) {
1246 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1247 item.Owner->Status == pkgAcquire::Item::StatDone
1251 std::string &error(item.Owner->ErrorText);
1255 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1256 NSArray *fields([description componentsSeparatedByString:@" "]);
1257 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1259 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1260 withObject:[NSArray arrayWithObjects:
1261 [NSString stringWithUTF8String:error.c_str()],
1268 virtual bool Pulse(pkgAcquire *Owner) {
1269 bool value = pkgAcquireStatus::Pulse(Owner);
1272 double(CurrentBytes + CurrentItems) /
1273 double(TotalBytes + TotalItems)
1276 [delegate_ setProgressPercent:percent];
1277 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1280 virtual void Start() {
1281 [delegate_ startProgress];
1284 virtual void Stop() {
1288 /* Progress Delegation {{{ */
1293 _transient id<ProgressDelegate> delegate_;
1297 virtual void Update() {
1298 /*if (abs(Percent - percent_) > 2)
1299 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1303 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1304 [delegate_ setProgressPercent:(Percent / 100)];*/
1314 void setDelegate(id delegate) {
1315 delegate_ = delegate;
1318 id getDelegate() const {
1322 virtual void Done() {
1324 //[delegate_ setProgressPercent:1];
1329 /* Database Interface {{{ */
1330 typedef std::map< unsigned long, _H<Source> > SourceMap;
1332 @interface Database : NSObject {
1338 pkgCacheFile cache_;
1339 pkgDepCache::Policy *policy_;
1340 pkgRecords *records_;
1341 pkgProblemResolver *resolver_;
1342 pkgAcquire *fetcher_;
1344 SPtr<pkgPackageManager> manager_;
1345 pkgSourceList *list_;
1348 CFMutableArrayRef deadSources_;
1349 CFMutableArrayRef packages_;
1351 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1359 std::map<const char *, _H<NSString> > sections_;
1362 + (Database *) sharedInstance;
1365 - (void) _readCydia:(NSNumber *)fd;
1366 - (void) _readStatus:(NSNumber *)fd;
1367 - (void) _readOutput:(NSNumber *)fd;
1371 - (Package *) packageWithName:(NSString *)name;
1373 - (pkgCacheFile &) cache;
1374 - (pkgDepCache::Policy *) policy;
1375 - (pkgRecords *) records;
1376 - (pkgProblemResolver *) resolver;
1377 - (pkgAcquire &) fetcher;
1378 - (pkgSourceList &) list;
1379 - (NSArray *) packages;
1380 - (NSArray *) sources;
1381 - (void) reloadData;
1389 - (void) updateWithStatus:(Status &)status;
1391 - (void) setDelegate:(id)delegate;
1392 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1394 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1398 /* Delegate Helpers {{{ */
1399 @implementation NSObject (ProgressDelegate)
1401 - (void) _setProgressErrorPackage:(NSArray *)args {
1402 [self performSelector:@selector(setProgressError:forPackage:)
1403 withObject:[args objectAtIndex:0]
1404 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1408 - (void) _setProgressErrorTitle:(NSArray *)args {
1409 [self performSelector:@selector(setProgressError:withTitle:)
1410 withObject:[args objectAtIndex:0]
1411 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1415 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1416 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1417 withObject:[NSArray arrayWithObjects:error, title, nil]
1422 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1423 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1425 [self performSelector:@selector(setProgressError:withTitle:)
1427 withObject:(package == nil ? id : [package name])
1434 // Cytore Definitions {{{
1435 struct PackageValue :
1438 Cytore::Offset<PackageValue> next_;
1440 uint32_t index_ : 23;
1441 uint32_t subscribed_ : 1;
1458 Cytore::Offset<PackageValue> packages_[1 << 16];
1461 static Cytore::File<MetaValue> MetaFile_;
1463 // Cytore Helper Functions {{{
1464 static PackageValue *PackageFind(const char *name, size_t length) {
1465 SplitHash nhash = { hashlittle(name, length) };
1467 PackageValue *metadata;
1469 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1470 offset: if (offset->IsNull()) {
1471 *offset = MetaFile_.New<PackageValue>(length + 1);
1472 metadata = &MetaFile_.Get(*offset);
1474 memcpy(metadata->name_, name, length + 1);
1475 metadata->nhash_ = nhash.u16[1];
1477 metadata = &MetaFile_.Get(*offset);
1479 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1480 offset = &metadata->next_;
1488 static void PackageImport(const void *key, const void *value, void *context) {
1490 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1491 NSLog(@"failed to import package %@", key);
1495 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1496 NSDictionary *package((NSDictionary *) value);
1498 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1499 if ([subscribed boolValue] && !metadata->subscribed_)
1500 metadata->subscribed_ = true;
1502 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1503 time_t time([date timeIntervalSince1970]);
1504 if (metadata->first_ > time || metadata->first_ == 0)
1505 metadata->first_ = time;
1508 NSDate *date([package objectForKey:@"LastSeen"]);
1509 NSString *version([package objectForKey:@"LastVersion"]);
1511 if (date != nil && version != nil) {
1512 time_t time([date timeIntervalSince1970]);
1513 if (metadata->last_ < time || metadata->last_ == 0)
1514 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1515 size_t length(strlen(buffer));
1516 uint16_t vhash(hashlittle(buffer, length));
1518 size_t capped(std::min<size_t>(8, length));
1519 char *latest(buffer + length - capped);
1521 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1522 metadata->vhash_ = vhash;
1524 metadata->last_ = time;
1530 /* Source Class {{{ */
1531 @interface Source : NSObject {
1532 CYString depiction_;
1533 CYString description_;
1539 CYString distribution_;
1544 NSString *authority_;
1546 CYString defaultIcon_;
1548 NSDictionary *record_;
1552 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1554 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1556 - (NSString *) depictionForPackage:(NSString *)package;
1557 - (NSString *) supportForPackage:(NSString *)package;
1559 - (NSDictionary *) record;
1563 - (NSString *) distribution;
1564 - (NSString *) type;
1566 - (NSString *) host;
1568 - (NSString *) name;
1569 - (NSString *) description;
1570 - (NSString *) label;
1571 - (NSString *) origin;
1572 - (NSString *) version;
1574 - (NSString *) defaultIcon;
1578 @implementation Source
1582 distribution_.clear();
1585 description_.clear();
1591 defaultIcon_.clear();
1593 if (record_ != nil) {
1603 if (authority_ != nil) {
1604 [authority_ release];
1610 // XXX: this is a very inefficient way to call these deconstructors
1615 + (NSArray *) _attributeKeys {
1616 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1619 - (NSArray *) attributeKeys {
1620 return [[self class] _attributeKeys];
1623 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1624 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1627 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1630 trusted_ = index->IsTrusted();
1632 uri_.set(pool, index->GetURI());
1633 distribution_.set(pool, index->GetDist());
1634 type_.set(pool, index->GetType());
1636 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1637 if (dindex != NULL) {
1639 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1642 pkgTagFile tags(&fd);
1644 pkgTagSection section;
1651 {"default-icon", &defaultIcon_},
1652 {"depiction", &depiction_},
1653 {"description", &description_},
1655 {"origin", &origin_},
1656 {"support", &support_},
1657 {"version", &version_},
1660 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1661 const char *start, *end;
1663 if (section.Find(names[i].name_, start, end)) {
1664 CYString &value(*names[i].value_);
1665 value.set(pool, start, end - start);
1671 record_ = [Sources_ objectForKey:[self key]];
1673 record_ = [record_ retain];
1675 NSURL *url([NSURL URLWithString:uri_]);
1679 host_ = [[host_ lowercaseString] retain];
1684 authority_ = [url path];
1686 if (authority_ != nil)
1687 authority_ = [authority_ retain];
1690 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1691 if ((self = [super init]) != nil) {
1692 [self setMetaIndex:index inPool:pool];
1696 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1697 NSDictionary *lhr = [self record];
1698 NSDictionary *rhr = [source record];
1701 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1703 NSString *lhs = [self name];
1704 NSString *rhs = [source name];
1706 if ([lhs length] != 0 && [rhs length] != 0) {
1707 unichar lhc = [lhs characterAtIndex:0];
1708 unichar rhc = [rhs characterAtIndex:0];
1710 if (isalpha(lhc) && !isalpha(rhc))
1711 return NSOrderedAscending;
1712 else if (!isalpha(lhc) && isalpha(rhc))
1713 return NSOrderedDescending;
1716 return [lhs compare:rhs options:LaxCompareOptions_];
1719 - (NSString *) depictionForPackage:(NSString *)package {
1720 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1723 - (NSString *) supportForPackage:(NSString *)package {
1724 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1727 - (NSDictionary *) record {
1735 - (NSString *) uri {
1739 - (NSString *) distribution {
1740 return distribution_;
1743 - (NSString *) type {
1747 - (NSString *) key {
1748 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1751 - (NSString *) host {
1755 - (NSString *) name {
1756 return origin_.empty() ? authority_ : origin_;
1759 - (NSString *) description {
1760 return description_;
1763 - (NSString *) label {
1764 return label_.empty() ? authority_ : label_;
1767 - (NSString *) origin {
1771 - (NSString *) version {
1775 - (NSString *) defaultIcon {
1776 return defaultIcon_;
1781 /* Relationship Class {{{ */
1782 @interface Relationship : NSObject {
1787 - (NSString *) type;
1789 - (NSString *) name;
1793 @implementation Relationship
1801 - (NSString *) type {
1809 - (NSString *) name {
1816 /* Package Class {{{ */
1817 struct ParsedPackage {
1822 CYString depiction_;
1832 @interface Package : NSObject {
1835 uint32_t essential_ : 1;
1836 uint32_t obsolete_ : 1;
1837 uint32_t ignored_ : 1;
1841 _transient Database *database_;
1843 pkgCache::VerIterator version_;
1844 pkgCache::PkgIterator iterator_;
1845 pkgCache::VerFileIterator file_;
1851 CYString installed_;
1853 const char *section_;
1854 _transient NSString *section$_;
1858 PackageValue *metadata_;
1859 ParsedPackage *parsed_;
1861 NSMutableArray *tags_;
1864 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1865 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1867 - (pkgCache::PkgIterator) iterator;
1870 - (NSString *) section;
1871 - (NSString *) simpleSection;
1873 - (NSString *) longSection;
1874 - (NSString *) shortSection;
1878 - (Address *) maintainer;
1880 - (NSString *) longDescription;
1881 - (NSString *) shortDescription;
1884 - (PackageValue *) metadata;
1887 - (bool) subscribed;
1888 - (bool) setSubscribed:(bool)subscribed;
1892 - (NSString *) latest;
1893 - (NSString *) installed;
1894 - (BOOL) uninstalled;
1897 - (BOOL) upgradableAndEssential:(BOOL)essential;
1900 - (BOOL) unfiltered;
1904 - (BOOL) halfConfigured;
1905 - (BOOL) halfInstalled;
1907 - (NSString *) mode;
1910 - (NSString *) name;
1912 - (NSString *) homepage;
1913 - (NSString *) depiction;
1914 - (Address *) author;
1916 - (NSString *) support;
1918 - (NSArray *) files;
1919 - (NSArray *) warnings;
1920 - (NSArray *) applications;
1922 - (Source *) source;
1924 - (BOOL) matches:(NSString *)text;
1926 - (bool) hasSupportingRole;
1927 - (BOOL) hasTag:(NSString *)tag;
1928 - (NSString *) primaryPurpose;
1929 - (NSArray *) purposes;
1930 - (bool) isCommercial;
1932 - (void) setIndex:(size_t)index;
1934 - (CYString &) cyname;
1936 - (uint32_t) compareBySection:(NSArray *)sections;
1941 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1942 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1943 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1944 - (bool) isVisibleInSection:(NSString *)section;
1945 - (bool) isVisibleInSource:(Source *)source;
1949 uint32_t PackageChangesRadix(Package *self, void *) {
1954 uint32_t timestamp : 30;
1955 uint32_t ignored : 1;
1956 uint32_t upgradable : 1;
1960 bool upgradable([self upgradableAndEssential:YES]);
1961 value.bits.upgradable = upgradable ? 1 : 0;
1964 value.bits.timestamp = 0;
1965 value.bits.ignored = [self ignored] ? 0 : 1;
1966 value.bits.upgradable = 1;
1968 value.bits.timestamp = [self seen] >> 2;
1969 value.bits.ignored = 0;
1970 value.bits.upgradable = 0;
1973 return _not(uint32_t) - value.key;
1976 uint32_t PackagePrefixRadix(Package *self, void *context) {
1977 size_t offset(reinterpret_cast<size_t>(context));
1978 CYString &name([self cyname]);
1980 size_t size(name.size());
1983 char *text(name.data());
1986 if (!isdigit(text[0]))
1990 while (size != digits && isdigit(text[digits]))
1998 if (offset == 0 && zeros != 0) {
1999 memset(data, '0', zeros);
2000 memcpy(data + zeros, text, 4 - zeros);
2002 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2003 if (size <= offset - zeros)
2006 text += offset - zeros;
2007 size -= offset - zeros;
2010 memcpy(data, text, 4);
2012 memcpy(data, text, size);
2013 memset(data + size, 0, 4 - size);
2016 for (size_t i(0); i != 4; ++i)
2017 if (isalpha(data[i]))
2025 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2027 /* XXX: ntohl may be more honest */
2028 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2031 CYString &(*PackageName)(Package *self, SEL sel);
2033 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2034 _profile(PackageNameCompare)
2035 CYString &lhi(PackageName(lhs, @selector(cyname)));
2036 CYString &rhi(PackageName(rhs, @selector(cyname)));
2037 CFStringRef lhn(lhi), rhn(rhi);
2040 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2041 else if (rhn == NULL)
2042 return NSOrderedDescending;
2044 _profile(PackageNameCompare$NumbersLast)
2045 if (!lhi.empty() && !rhi.empty()) {
2046 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2047 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2048 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2049 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2050 return lha ? NSOrderedAscending : NSOrderedDescending;
2054 CFIndex length = CFStringGetLength(lhn);
2056 _profile(PackageNameCompare$Compare)
2057 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2062 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2063 return PackageNameCompare(*lhs, *rhs, context);
2066 struct PackageNameOrdering :
2067 std::binary_function<Package *, Package *, bool>
2069 _finline bool operator ()(Package *lhs, Package *rhs) const {
2070 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2074 @implementation Package
2076 - (NSString *) description {
2077 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2081 if (parsed_ != NULL)
2090 + (NSString *) webScriptNameForSelector:(SEL)selector {
2091 if (selector == @selector(hasTag:))
2097 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2098 return [self webScriptNameForSelector:selector] == nil;
2101 + (NSArray *) _attributeKeys {
2102 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];
2105 - (NSArray *) attributeKeys {
2106 return [[self class] _attributeKeys];
2109 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2110 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2114 if (parsed_ != NULL)
2116 @synchronized (database_) {
2117 if ([database_ era] != era_ || file_.end())
2120 ParsedPackage *parsed(new ParsedPackage);
2123 _profile(Package$parse)
2124 pkgRecords::Parser *parser;
2126 _profile(Package$parse$Lookup)
2127 parser = &[database_ records]->Lookup(file_);
2132 _profile(Package$parse$Find)
2137 {"icon", &parsed->icon_},
2138 {"depiction", &parsed->depiction_},
2139 {"homepage", &parsed->homepage_},
2140 {"website", &website},
2141 {"bugs", &parsed->bugs_},
2142 {"support", &parsed->support_},
2143 {"sponsor", &parsed->sponsor_},
2144 {"author", &parsed->author_},
2147 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2148 const char *start, *end;
2150 if (parser->Find(names[i].name_, start, end)) {
2151 CYString &value(*names[i].value_);
2152 _profile(Package$parse$Value)
2153 value.set(pool_, start, end - start);
2159 _profile(Package$parse$Tagline)
2160 const char *start, *end;
2161 if (parser->ShortDesc(start, end)) {
2162 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2165 while (stop != start && stop[-1] == '\r')
2167 parsed->tagline_.set(pool_, start, stop - start);
2171 _profile(Package$parse$Retain)
2172 if (parsed->homepage_.empty())
2173 parsed->homepage_ = website;
2174 if (parsed->homepage_ == parsed->depiction_)
2175 parsed->homepage_.clear();
2180 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2181 if ((self = [super init]) != nil) {
2182 _profile(Package$initWithVersion)
2185 database_ = database;
2186 era_ = [database era];
2190 pkgCache::PkgIterator iterator(version.ParentPkg());
2191 iterator_ = iterator;
2193 _profile(Package$initWithVersion$Version)
2194 if (!version_.end())
2195 file_ = version_.FileList();
2197 pkgCache &cache([database_ cache]);
2198 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2202 _profile(Package$initWithVersion$Cache)
2203 name_.set(NULL, iterator.Display());
2205 latest_.set(NULL, StripVersion_(version_.VerStr()));
2207 pkgCache::VerIterator current(iterator.CurrentVer());
2209 installed_.set(NULL, StripVersion_(current.VerStr()));
2212 _profile(Package$initWithVersion$Tags)
2213 pkgCache::TagIterator tag(iterator.TagList());
2215 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2217 const char *name(tag.Name());
2218 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2220 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2221 if (strcmp(name + 6, "enduser") == 0)
2223 else if (strcmp(name + 6, "hacker") == 0)
2225 else if (strcmp(name + 6, "developer") == 0)
2227 else if (strcmp(name + 6, "cydia") == 0)
2233 if (strncmp(name, "cydia::", 7) == 0) {
2234 if (strcmp(name + 7, "essential") == 0)
2236 else if (strcmp(name + 7, "obsolete") == 0)
2241 } while (!tag.end());
2245 _profile(Package$initWithVersion$Metadata)
2246 const char *mixed(iterator.Name());
2247 size_t size(strlen(mixed));
2248 char lower[size + 1];
2250 for (size_t i(0); i != size; ++i)
2251 lower[i] = mixed[i] | 0x20;
2254 PackageValue *metadata(PackageFind(lower, size));
2255 metadata_ = metadata;
2257 id_.set(NULL, metadata->name_, size);
2259 const char *latest(version_.VerStr());
2260 size_t length(strlen(latest));
2262 uint16_t vhash(hashlittle(latest, length));
2264 size_t capped(std::min<size_t>(8, length));
2265 latest = latest + length - capped;
2267 if (metadata->first_ == 0)
2268 metadata->first_ = now_;
2270 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2271 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2272 metadata->vhash_ = vhash;
2273 metadata->last_ = now_;
2274 } else if (metadata->last_ == 0)
2275 metadata->last_ = metadata->first_;
2278 _profile(Package$initWithVersion$Section)
2279 section_ = iterator.Section();
2282 _profile(Package$initWithVersion$Flags)
2283 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2284 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2289 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2290 pkgCache::VerIterator version;
2292 _profile(Package$packageWithIterator$GetCandidateVer)
2293 version = [database policy]->GetCandidateVer(iterator);
2301 _profile(Package$packageWithIterator$Allocate)
2302 package = [Package allocWithZone:zone];
2305 _profile(Package$packageWithIterator$Initialize)
2307 initWithVersion:version
2314 _profile(Package$packageWithIterator$Autorelease)
2315 package = [package autorelease];
2321 - (pkgCache::PkgIterator) iterator {
2325 - (NSString *) section {
2326 if (section$_ == nil) {
2327 if (section_ == NULL)
2330 _profile(Package$section$mappedSectionForPointer)
2331 section$_ = [database_ mappedSectionForPointer:section_];
2336 - (NSString *) simpleSection {
2337 if (NSString *section = [self section])
2338 return Simplify(section);
2343 - (NSString *) longSection {
2344 return LocalizeSection([self section]);
2347 - (NSString *) shortSection {
2348 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2351 - (NSString *) uri {
2354 pkgIndexFile *index;
2355 pkgCache::PkgFileIterator file(file_.File());
2356 if (![database_ list].FindIndex(file, index))
2358 return [NSString stringWithUTF8String:iterator_->Path];
2359 //return [NSString stringWithUTF8String:file.Site()];
2360 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2364 - (Address *) maintainer {
2365 @synchronized (database_) {
2366 if ([database_ era] != era_ || file_.end())
2369 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2370 const std::string &maintainer(parser->Maintainer());
2371 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2375 @synchronized (database_) {
2376 if ([database_ era] != era_ || version_.end())
2379 return version_->InstalledSize;
2382 - (NSString *) longDescription {
2383 @synchronized (database_) {
2384 if ([database_ era] != era_ || file_.end())
2387 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2388 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2390 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2391 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2392 if ([lines count] < 2)
2395 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2396 for (size_t i(1), e([lines count]); i != e; ++i) {
2397 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2398 [trimmed addObject:trim];
2401 return [trimmed componentsJoinedByString:@"\n"];
2404 - (NSString *) shortDescription {
2405 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2409 _profile(Package$index)
2410 CFStringRef name((CFStringRef) [self name]);
2411 if (CFStringGetLength(name) == 0)
2413 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2414 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2416 return toupper(character);
2420 - (PackageValue *) metadata {
2425 PackageValue *metadata([self metadata]);
2426 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2429 - (bool) subscribed {
2430 return [self metadata]->subscribed_;
2433 - (bool) setSubscribed:(bool)subscribed {
2434 PackageValue *metadata([self metadata]);
2435 if (metadata->subscribed_ == subscribed)
2437 metadata->subscribed_ = subscribed;
2445 - (NSString *) latest {
2449 - (NSString *) installed {
2453 - (BOOL) uninstalled {
2454 return installed_.empty();
2458 return !version_.end();
2461 - (BOOL) upgradableAndEssential:(BOOL)essential {
2462 _profile(Package$upgradableAndEssential)
2463 pkgCache::VerIterator current(iterator_.CurrentVer());
2465 return essential && essential_;
2467 return !version_.end() && version_ != current;
2471 - (BOOL) essential {
2476 return [database_ cache][iterator_].InstBroken();
2479 - (BOOL) unfiltered {
2480 _profile(Package$unfiltered$obsolete)
2481 if (_unlikely(obsolete_))
2485 _profile(Package$unfiltered$hasSupportingRole)
2486 if (_unlikely(![self hasSupportingRole]))
2494 if (![self unfiltered])
2499 _profile(Package$visible$section)
2500 section = [self section];
2503 _profile(Package$visible$isSectionVisible)
2504 if (section != nil && !isSectionVisible(section))
2512 unsigned char current(iterator_->CurrentState);
2513 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2516 - (BOOL) halfConfigured {
2517 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2520 - (BOOL) halfInstalled {
2521 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2525 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2526 return state.Mode != pkgDepCache::ModeKeep;
2529 - (NSString *) mode {
2530 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2532 switch (state.Mode) {
2533 case pkgDepCache::ModeDelete:
2534 if ((state.iFlags & pkgDepCache::Purge) != 0)
2538 case pkgDepCache::ModeKeep:
2539 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2540 return @"REINSTALL";
2541 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2545 case pkgDepCache::ModeInstall:
2546 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2547 return @"REINSTALL";
2548 else*/ switch (state.Status) {
2550 return @"DOWNGRADE";
2556 return @"NEW_INSTALL";
2567 - (NSString *) name {
2568 return name_.empty() ? id_ : name_;
2571 - (UIImage *) icon {
2572 NSString *section = [self simpleSection];
2575 if (parsed_ != NULL)
2576 if (NSString *href = parsed_->icon_)
2577 if ([href hasPrefix:@"file:///"])
2578 // XXX: correct escaping
2579 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2580 if (icon == nil) if (section != nil)
2581 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2582 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2583 if ([dicon hasPrefix:@"file:///"])
2584 // XXX: correct escaping
2585 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2587 icon = [UIImage applicationImageNamed:@"unknown.png"];
2591 - (NSString *) homepage {
2592 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2595 - (NSString *) depiction {
2596 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2599 - (Address *) sponsor {
2600 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2603 - (Address *) author {
2604 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2607 - (NSString *) support {
2608 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2611 - (NSArray *) files {
2612 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2613 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2616 fin.open([path UTF8String]);
2621 while (std::getline(fin, line))
2622 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2627 - (NSArray *) warnings {
2628 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2629 const char *name(iterator_.Name());
2631 size_t length(strlen(name));
2632 if (length < 2) invalid:
2633 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2634 else for (size_t i(0); i != length; ++i)
2636 /* XXX: technically this is not allowed */
2637 (name[i] < 'A' || name[i] > 'Z') &&
2638 (name[i] < 'a' || name[i] > 'z') &&
2639 (name[i] < '0' || name[i] > '9') &&
2640 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2643 if (strcmp(name, "cydia") != 0) {
2646 bool _private = false;
2649 bool repository = [[self section] isEqualToString:@"Repositories"];
2651 if (NSArray *files = [self files])
2652 for (NSString *file in files)
2653 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2655 else if (!user && [file isEqualToString:@"/User"])
2657 else if (!_private && [file isEqualToString:@"/private"])
2659 else if (!stash && [file isEqualToString:@"/var/stash"])
2662 /* XXX: this is not sensitive enough. only some folders are valid. */
2663 if (cydia && !repository)
2664 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2666 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2668 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2670 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2673 return [warnings count] == 0 ? nil : warnings;
2676 - (NSArray *) applications {
2677 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2679 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2681 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2682 if (NSArray *files = [self files])
2683 for (NSString *file in files)
2684 if (application_r(file)) {
2685 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2686 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2687 if ([id isEqualToString:me])
2690 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2692 display = application_r[1];
2694 NSString *bundle([file stringByDeletingLastPathComponent]);
2695 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2696 if (icon == nil || [icon length] == 0)
2698 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2700 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2701 [applications addObject:application];
2703 [application addObject:id];
2704 [application addObject:display];
2705 [application addObject:url];
2708 return [applications count] == 0 ? nil : applications;
2711 - (Source *) source {
2712 if (source_ == nil) {
2713 @synchronized (database_) {
2714 if ([database_ era] != era_ || file_.end())
2715 source_ = (Source *) [NSNull null];
2717 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2721 return source_ == (Source *) [NSNull null] ? nil : source_;
2724 - (BOOL) matches:(NSString *)text {
2730 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2731 if (range.location != NSNotFound)
2734 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2735 if (range.location != NSNotFound)
2738 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2739 if (range.location != NSNotFound)
2745 - (bool) hasSupportingRole {
2750 if ([Role_ isEqualToString:@"User"])
2754 if ([Role_ isEqualToString:@"Hacker"])
2758 if ([Role_ isEqualToString:@"Developer"])
2763 - (BOOL) hasTag:(NSString *)tag {
2764 return tags_ == nil ? NO : [tags_ containsObject:tag];
2767 - (NSString *) primaryPurpose {
2768 for (NSString *tag in tags_)
2769 if ([tag hasPrefix:@"purpose::"])
2770 return [tag substringFromIndex:9];
2774 - (NSArray *) purposes {
2775 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2776 for (NSString *tag in tags_)
2777 if ([tag hasPrefix:@"purpose::"])
2778 [purposes addObject:[tag substringFromIndex:9]];
2779 return [purposes count] == 0 ? nil : purposes;
2782 - (bool) isCommercial {
2783 return [self hasTag:@"cydia::commercial"];
2786 - (void) setIndex:(size_t)index {
2787 if (metadata_->index_ != index)
2788 metadata_->index_ = index;
2791 - (CYString &) cyname {
2792 return name_.empty() ? id_ : name_;
2795 - (uint32_t) compareBySection:(NSArray *)sections {
2796 NSString *section([self section]);
2797 for (size_t i(0), e([sections count]); i != e; ++i) {
2798 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2802 return _not(uint32_t);
2806 @synchronized (database_) {
2807 pkgProblemResolver *resolver = [database_ resolver];
2808 resolver->Clear(iterator_);
2810 pkgCacheFile &cache([database_ cache]);
2811 cache->SetReInstall(iterator_, false);
2812 cache->MarkKeep(iterator_, false);
2816 @synchronized (database_) {
2817 pkgProblemResolver *resolver = [database_ resolver];
2818 resolver->Clear(iterator_);
2819 resolver->Protect(iterator_);
2821 pkgCacheFile &cache([database_ cache]);
2822 cache->SetReInstall(iterator_, false);
2823 cache->MarkInstall(iterator_, false);
2825 pkgDepCache::StateCache &state((*cache)[iterator_]);
2826 if (!state.Install())
2827 cache->SetReInstall(iterator_, true);
2831 @synchronized (database_) {
2832 pkgProblemResolver *resolver = [database_ resolver];
2833 resolver->Clear(iterator_);
2834 resolver->Remove(iterator_);
2835 resolver->Protect(iterator_);
2837 pkgCacheFile &cache([database_ cache]);
2838 cache->SetReInstall(iterator_, false);
2839 cache->MarkDelete(iterator_, true);
2842 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2843 _profile(Package$isUnfilteredAndSearchedForBy)
2846 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2847 value &= [self unfiltered];
2850 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2851 value &= [self matches:search];
2858 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2859 if ([search length] == 0)
2862 _profile(Package$isUnfilteredAndSelectedForBy)
2865 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2866 value &= [self unfiltered];
2869 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2870 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2877 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2878 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2881 - (bool) isVisibleInSection:(NSString *)name {
2882 NSString *section([self section]);
2886 section == nil && [name length] == 0 ||
2887 [name isEqualToString:section]
2888 ) && [self visible];
2891 - (bool) isVisibleInSource:(Source *)source {
2892 return [self source] == source && [self visible];
2897 /* Section Class {{{ */
2898 @interface Section : NSObject {
2903 NSString *localized_;
2906 - (NSComparisonResult) compareByLocalized:(Section *)section;
2907 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2908 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2909 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2910 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2911 - (NSString *) name;
2918 - (void) addToCount;
2920 - (void) setCount:(size_t)count;
2921 - (NSString *) localized;
2925 @implementation Section
2929 if (localized_ != nil)
2930 [localized_ release];
2934 - (NSComparisonResult) compareByLocalized:(Section *)section {
2935 NSString *lhs(localized_);
2936 NSString *rhs([section localized]);
2938 /*if ([lhs length] != 0 && [rhs length] != 0) {
2939 unichar lhc = [lhs characterAtIndex:0];
2940 unichar rhc = [rhs characterAtIndex:0];
2942 if (isalpha(lhc) && !isalpha(rhc))
2943 return NSOrderedAscending;
2944 else if (!isalpha(lhc) && isalpha(rhc))
2945 return NSOrderedDescending;
2948 return [lhs compare:rhs options:LaxCompareOptions_];
2951 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2952 if ((self = [self initWithName:name localize:NO]) != nil) {
2953 if (localized != nil)
2954 localized_ = [localized retain];
2958 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2959 return [self initWithName:name row:0 localize:localize];
2962 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2963 if ((self = [super init]) != nil) {
2964 name_ = [name retain];
2968 localized_ = [LocalizeSection(name_) retain];
2972 /* XXX: localize the index thingees */
2973 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2974 if ((self = [super init]) != nil) {
2975 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2981 - (NSString *) name {
3001 - (void) addToCount {
3005 - (void) setCount:(size_t)count {
3009 - (NSString *) localized {
3016 static NSString *Colon_;
3017 static NSString *Elision_;
3018 static NSString *Error_;
3019 static NSString *Warning_;
3021 /* Database Implementation {{{ */
3022 @implementation Database
3024 + (Database *) sharedInstance {
3025 static Database *instance;
3026 if (instance == nil)
3027 instance = [[Database alloc] init];
3035 - (void) releasePackages {
3036 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3037 CFArrayRemoveAllValues(packages_);
3041 // XXX: actually implement this thing
3044 CFRelease(deadSources_);
3045 [self releasePackages];
3046 apr_pool_destroy(pool_);
3047 NSRecycleZone(zone_);
3051 - (void) _readCydia:(NSNumber *)fd { _pooled
3052 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3053 std::istream is(&ib);
3056 static Pcre finish_r("^finish:([^:]*)$");
3058 while (std::getline(is, line)) {
3059 const char *data(line.c_str());
3060 size_t size = line.size();
3061 lprintf("C:%s\n", data);
3063 if (finish_r(data, size)) {
3064 NSString *finish = finish_r[1];
3065 int index = [Finishes_ indexOfObject:finish];
3066 if (index != INT_MAX && index > Finish_)
3074 - (void) _readStatus:(NSNumber *)fd { _pooled
3075 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3076 std::istream is(&ib);
3079 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3080 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3082 while (std::getline(is, line)) {
3083 const char *data(line.c_str());
3084 size_t size(line.size());
3085 lprintf("S:%s\n", data);
3087 if (conffile_r(data, size)) {
3088 [delegate_ setConfigurationData:conffile_r[1]];
3089 } else if (strncmp(data, "status: ", 8) == 0) {
3090 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3091 [delegate_ setProgressTitle:string];
3092 } else if (pmstatus_r(data, size)) {
3093 std::string type([pmstatus_r[1] UTF8String]);
3094 NSString *id = pmstatus_r[2];
3096 float percent([pmstatus_r[3] floatValue]);
3097 [delegate_ setProgressPercent:(percent / 100)];
3099 NSString *string = pmstatus_r[4];
3101 if (type == "pmerror")
3102 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3103 withObject:[NSArray arrayWithObjects:string, id, nil]
3106 else if (type == "pmstatus") {
3107 [delegate_ setProgressTitle:string];
3108 } else if (type == "pmconffile")
3109 [delegate_ setConfigurationData:string];
3111 lprintf("E:unknown pmstatus\n");
3113 lprintf("E:unknown status\n");
3119 - (void) _readOutput:(NSNumber *)fd { _pooled
3120 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3121 std::istream is(&ib);
3124 while (std::getline(is, line)) {
3125 lprintf("O:%s\n", line.c_str());
3126 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3136 - (Package *) packageWithName:(NSString *)name {
3137 @synchronized (self) {
3138 if (static_cast<pkgDepCache *>(cache_) == NULL)
3140 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3141 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3145 if ((self = [super init]) != nil) {
3152 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3153 apr_pool_create(&pool_, NULL);
3155 size_t capacity(MetaFile_->active_);
3161 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3162 deadSources_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
3166 _assert(pipe(fds) != -1);
3169 _config->Set("APT::Keep-Fds::", cydiafd_);
3170 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3173 detachNewThreadSelector:@selector(_readCydia:)
3175 withObject:[NSNumber numberWithInt:fds[0]]
3178 _assert(pipe(fds) != -1);
3182 detachNewThreadSelector:@selector(_readStatus:)
3184 withObject:[NSNumber numberWithInt:fds[0]]
3187 _assert(pipe(fds) != -1);
3188 _assert(dup2(fds[0], 0) != -1);
3189 _assert(close(fds[0]) != -1);
3191 input_ = fdopen(fds[1], "a");
3193 _assert(pipe(fds) != -1);
3194 _assert(dup2(fds[1], 1) != -1);
3195 _assert(close(fds[1]) != -1);
3198 detachNewThreadSelector:@selector(_readOutput:)
3200 withObject:[NSNumber numberWithInt:fds[0]]
3205 - (pkgCacheFile &) cache {
3209 - (pkgDepCache::Policy *) policy {
3213 - (pkgRecords *) records {
3217 - (pkgProblemResolver *) resolver {
3221 - (pkgAcquire &) fetcher {
3225 - (pkgSourceList &) list {
3229 - (NSArray *) packages {
3230 return (NSArray *) packages_;
3233 - (NSArray *) sources {
3234 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3235 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3236 [sources addObject:i->second];
3237 [sources addObjectsFromArray:(NSArray *)deadSources_];
3241 - (NSArray *) issues {
3242 if (cache_->BrokenCount() == 0)
3245 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3247 for (Package *package in [self packages]) {
3248 if (![package broken])
3250 pkgCache::PkgIterator pkg([package iterator]);
3252 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3253 [entry addObject:[package name]];
3254 [issues addObject:entry];
3256 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3260 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3261 pkgCache::DepIterator start;
3262 pkgCache::DepIterator end;
3263 dep.GlobOr(start, end); // ++dep
3265 if (!cache_->IsImportantDep(end))
3267 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3270 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3271 [entry addObject:failure];
3272 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3274 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3275 if (Package *package = [self packageWithName:name])
3276 name = [package name];
3277 [failure addObject:name];
3279 pkgCache::PkgIterator target(start.TargetPkg());
3280 if (target->ProvidesList != 0)
3281 [failure addObject:@"?"];
3283 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3285 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3286 else if (!cache_[target].CandidateVerIter(cache_).end())
3287 [failure addObject:@"-"];
3288 else if (target->ProvidesList == 0)
3289 [failure addObject:@"!"];
3291 [failure addObject:@"%"];
3295 if (start.TargetVer() != 0)
3296 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3307 - (bool) popErrorWithTitle:(NSString *)title {
3309 std::string message;
3311 while (!_error->empty()) {
3313 bool warning(!_error->PopMessage(error));
3317 size_t size(error.size());
3318 if (size == 0 || error[size - 1] != '\n')
3320 error.resize(size - 1);
3322 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3324 if (!message.empty())
3329 if (fatal && !message.empty())
3330 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3335 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3336 return [self popErrorWithTitle:title] || !success;
3339 - (void) reloadData { CYPoolStart() {
3340 @synchronized (self) {
3343 [self releasePackages];
3346 CFArrayRemoveAllValues(deadSources_);
3366 apr_pool_clear(pool_);
3368 NSRecycleZone(zone_);
3369 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3371 int chk(creat("/tmp/cydia.chk", 0644));
3375 NSString *title(UCLocalize("DATABASE"));
3378 if (!cache_.Open(progress_, true)) { pop:
3380 bool warning(!_error->PopMessage(error));
3381 lprintf("cache_.Open():[%s]\n", error.c_str());
3383 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3384 [delegate_ repairWithSelector:@selector(configure)];
3385 else if (error == "The package lists or status file could not be parsed or opened.")
3386 [delegate_ repairWithSelector:@selector(update)];
3387 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3388 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3389 // else if (error == "The list of sources could not be read.")
3391 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3400 unlink("/tmp/cydia.chk");
3402 now_ = [[NSDate date] timeIntervalSince1970];
3404 policy_ = new pkgDepCache::Policy();
3405 records_ = new pkgRecords(cache_);
3406 resolver_ = new pkgProblemResolver(cache_);
3407 fetcher_ = new pkgAcquire(&status_);
3410 list_ = new pkgSourceList();
3411 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3414 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3415 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3419 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3422 if (cache_->BrokenCount() != 0) {
3423 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3426 if (cache_->BrokenCount() != 0) {
3427 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3431 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3435 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3437 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3438 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3439 // XXX: this could be more intelligent
3440 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3441 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3442 if (!cached.end()) {
3443 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3448 CFArrayAppendValue(deadSources_, [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3452 /*std::vector<Package *> packages;
3453 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3454 [packages_ release];
3459 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3460 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3461 //packages.push_back(package);
3462 CFArrayAppendValue(packages_, [package retain]);
3466 /*if (packages.empty())
3467 packages_ = [[NSArray alloc] init];
3469 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3472 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3473 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3474 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3482 /*if (!packages.empty())
3483 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3484 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3486 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3488 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3490 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3494 size_t count(CFArrayGetCount(packages_));
3495 MetaFile_->active_ = count;
3497 for (size_t index(0); index != count; ++index)
3498 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3502 } } CYPoolEnd() _trace(); }
3505 @synchronized (self) {
3507 resolver_ = new pkgProblemResolver(cache_);
3509 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3510 if (!cache_[iterator].Keep()) {
3511 cache_->MarkKeep(iterator, false);
3512 cache_->SetReInstall(iterator, false);
3517 - (void) configure {
3518 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3520 system([dpkg UTF8String]);
3525 // XXX: I don't remember this condition
3530 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3532 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3534 if ([self popErrorWithTitle:title])
3538 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3541 public pkgArchiveCleaner
3544 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3549 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3556 fetcher_->Shutdown();
3558 pkgRecords records(cache_);
3560 lock_ = new FileFd();
3561 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3563 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3565 if ([self popErrorWithTitle:title])
3569 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3572 manager_ = (_system->CreatePM(cache_));
3573 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3580 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3582 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3584 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3586 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3587 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3590 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3595 [CydiaApp retainNetworkActivityIndicator];
3597 bool failed = false;
3598 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3599 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3601 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3604 std::string uri = (*item)->DescURI();
3605 std::string error = (*item)->ErrorText;
3607 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3610 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3611 withObject:[NSArray arrayWithObjects:
3612 [NSString stringWithUTF8String:error.c_str()],
3618 [CydiaApp releaseNetworkActivityIndicator];
3626 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3628 if (_error->PendingError()) {
3633 if (result == pkgPackageManager::Failed) {
3638 if (result != pkgPackageManager::Completed) {
3643 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3645 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3647 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3648 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3651 if (![before isEqualToArray:after])
3656 NSString *title(UCLocalize("UPGRADE"));
3657 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3663 [self updateWithStatus:status_];
3666 - (void) updateWithStatus:(Status &)status {
3667 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3668 NSString *title(UCLocalize("REFRESHING_DATA"));
3671 if (!list.ReadMainList())
3672 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3675 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3676 if ([self popErrorWithTitle:title])
3679 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3680 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3681 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3683 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3687 - (void) setDelegate:(id)delegate {
3688 delegate_ = delegate;
3689 status_.setDelegate(delegate);
3690 progress_.setDelegate(delegate);
3693 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3694 SourceMap::const_iterator i(sources_.find(file->ID));
3695 return i == sources_.end() ? nil : i->second;
3698 - (NSString *) mappedSectionForPointer:(const char *)section {
3699 _H<NSString> *mapped;
3701 _profile(Database$mappedSectionForPointer$Cache)
3702 mapped = §ions_[section];
3705 if (*mapped == NULL) {
3706 size_t length(strlen(section));
3707 char spaced[length + 1];
3709 _profile(Database$mappedSectionForPointer$Replace)
3710 for (size_t index(0); index != length; ++index)
3711 spaced[index] = section[index] == '_' ? ' ' : section[index];
3712 spaced[length] = '\0';
3717 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3718 string = [NSString stringWithUTF8String:spaced];
3721 _profile(Database$mappedSectionForPointer$Map)
3722 string = [SectionMap_ objectForKey:string] ?: string;
3732 /* Confirmation Controller {{{ */
3733 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3734 if (!iterator.end())
3735 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3736 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3738 pkgCache::PkgIterator package(dep.TargetPkg());
3741 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3749 /* Web Scripting {{{ */
3750 @interface CydiaObject : NSObject {
3752 _transient id delegate_;
3755 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3758 @implementation CydiaObject
3761 [indirect_ release];
3765 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3766 if ((self = [super init]) != nil) {
3767 indirect_ = [indirect retain];
3771 - (void) setDelegate:(id)delegate {
3772 delegate_ = delegate;
3775 + (NSArray *) _attributeKeys {
3776 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3779 - (NSArray *) attributeKeys {
3780 return [[self class] _attributeKeys];
3783 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3784 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3787 - (NSString *) device {
3788 return [[UIDevice currentDevice] uniqueIdentifier];
3791 #if 0 // XXX: implement!
3792 - (NSString *) mac {
3793 if (![indirect_ promptForSensitive:@"Mac Address"])
3797 - (NSString *) serial {
3798 if (![indirect_ promptForSensitive:@"Serial #"])
3802 - (NSString *) firewire {
3803 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3807 - (NSString *) imei {
3808 if (![indirect_ promptForSensitive:@"IMEI"])
3813 + (NSString *) webScriptNameForSelector:(SEL)selector {
3814 if (selector == @selector(close))
3816 else if (selector == @selector(getInstalledPackages))
3817 return @"getInstalledPackages";
3818 else if (selector == @selector(getPackageById:))
3819 return @"getPackageById";
3820 else if (selector == @selector(installPackages:))
3821 return @"installPackages";
3822 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3823 return @"setButtonImage";
3824 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3825 return @"setButtonTitle";
3826 else if (selector == @selector(setPopupHook:))
3827 return @"setPopupHook";
3828 else if (selector == @selector(setSpecial:))
3829 return @"setSpecial";
3830 else if (selector == @selector(setToken:))
3832 else if (selector == @selector(setViewportWidth:))
3833 return @"setViewportWidth";
3834 else if (selector == @selector(supports:))
3836 else if (selector == @selector(stringWithFormat:arguments:))
3838 else if (selector == @selector(localizedStringForKey:value:table:))
3840 else if (selector == @selector(du:))
3842 else if (selector == @selector(statfs:))
3848 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3849 return [self webScriptNameForSelector:selector] == nil;
3852 - (BOOL) supports:(NSString *)feature {
3853 return [feature isEqualToString:@"window.open"];
3856 - (NSArray *) getInstalledPackages {
3857 NSArray *packages([[Database sharedInstance] packages]);
3858 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3859 for (Package *package in packages)
3860 if ([package installed] != nil)
3861 [installed addObject:package];
3865 - (Package *) getPackageById:(NSString *)id {
3866 Package *package([[Database sharedInstance] packageWithName:id]);
3871 - (NSArray *) statfs:(NSString *)path {
3874 if (path == nil || statfs([path UTF8String], &stat) == -1)
3877 return [NSArray arrayWithObjects:
3878 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3879 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3880 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3884 - (NSNumber *) du:(NSString *)path {
3885 NSNumber *value(nil);
3888 _assert(pipe(fds) != -1);
3890 pid_t pid(ExecFork());
3892 _assert(dup2(fds[1], 1) != -1);
3893 _assert(close(fds[0]) != -1);
3894 _assert(close(fds[1]) != -1);
3895 /* XXX: this should probably not use du */
3896 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3901 _assert(close(fds[1]) != -1);
3903 if (FILE *du = fdopen(fds[0], "r")) {
3905 while (fgets(line, sizeof(line), du) != NULL) {
3906 size_t length(strlen(line));
3907 while (length != 0 && line[length - 1] == '\n')
3908 line[--length] = '\0';
3909 if (char *tab = strchr(line, '\t')) {
3911 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3916 } else _assert(close(fds[0]));
3920 if (waitpid(pid, &status, 0) == -1)
3923 else _assert(false);
3932 - (void) installPackages:(NSArray *)packages {
3933 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3936 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3937 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3940 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3941 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3944 - (void) setSpecial:(id)function {
3945 [indirect_ setSpecial:function];
3948 - (void) setToken:(NSString *)token {
3951 Token_ = [token retain];
3953 [Metadata_ setObject:Token_ forKey:@"Token"];
3957 - (void) setPopupHook:(id)function {
3958 [indirect_ setPopupHook:function];
3961 - (void) setViewportWidth:(float)width {
3962 [indirect_ setViewportWidth:width];
3965 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3966 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3967 unsigned count([arguments count]);
3969 for (unsigned i(0); i != count; ++i)
3970 values[i] = [arguments objectAtIndex:i];
3971 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3974 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3975 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3977 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3979 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3985 /* @ Loading... Indicator {{{ */
3986 @interface CYLoadingIndicator : UIView {
3987 UIActivityIndicatorView *spinner_;
3992 @property (readonly, nonatomic) UILabel *label;
3993 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
3997 @implementation CYLoadingIndicator
3999 - (id)initWithFrame:(CGRect)frame {
4000 if ((self = [super initWithFrame:frame])) {
4001 container_ = [[[UIView alloc] init] autorelease];
4002 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4004 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4005 [spinner_ startAnimating];
4006 [container_ addSubview:spinner_];
4008 label_ = [[[UILabel alloc] init] autorelease];
4009 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4010 [label_ setBackgroundColor:[UIColor clearColor]];
4011 [label_ setTextColor:[UIColor blackColor]];
4012 [label_ setShadowColor:[UIColor whiteColor]];
4013 [label_ setShadowOffset:CGSizeMake(0, 1)];
4014 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4015 [container_ addSubview:label_];
4017 CGSize viewsize = frame.size;
4018 CGSize spinnersize = [spinner_ bounds].size;
4019 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4020 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4022 CGRect containrect = {
4023 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4024 CGSizeMake(bothwidth, spinnersize.height)
4027 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4035 [container_ setFrame:containrect];
4036 [spinner_ setFrame:spinrect];
4037 [label_ setFrame:textrect];
4038 [self addSubview:container_];
4044 - (UILabel *)label { return label_; }
4045 - (UIActivityIndicatorView *)activityIndicatorView { return spinner_; }
4049 /* Emulated Loading Controller {{{ */
4050 @interface CYEmulatedLoadingController : UIViewController {
4051 CYLoadingIndicator *indicator_;
4053 UINavigationBar *navbar_;
4057 @implementation CYEmulatedLoadingController
4059 - (CYEmulatedLoadingController *) init {
4060 if ((self = [super init])) {
4061 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4063 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4064 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4065 [[self view] addSubview:indicator_];
4066 [indicator_ release];
4068 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4069 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4070 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4071 [[self view] addSubview:tabbar_];
4074 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4075 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4076 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4077 [[self view] addSubview:navbar_];
4082 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
4083 return (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
4089 /* Cydia Browser Controller {{{ */
4090 @interface CYBrowserController : BrowserController {
4091 CydiaObject *cydia_;
4096 @implementation CYBrowserController
4103 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4106 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4107 [super webView:view didClearWindowObject:window forFrame:frame];
4109 WebDataSource *source([frame dataSource]);
4110 NSURLResponse *response([source response]);
4111 NSURL *url([response URL]);
4112 NSString *scheme([url scheme]);
4114 NSHTTPURLResponse *http;
4115 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
4116 http = (NSHTTPURLResponse *) response;
4120 NSDictionary *headers([http allHeaderFields]);
4121 NSString *host([url host]);
4122 [self setHeaders:headers forHost:host];
4125 [host isEqualToString:@"cydia.saurik.com"] ||
4126 [host hasSuffix:@".cydia.saurik.com"] ||
4127 [scheme isEqualToString:@"file"]
4129 [window setValue:cydia_ forKey:@"cydia"];
4132 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4133 if (System_ != NULL)
4134 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4135 if (Machine_ != NULL)
4136 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4138 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4140 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4143 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4144 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4145 [self _setMoreHeaders:copy];
4149 - (void) setDelegate:(id)delegate {
4150 [super setDelegate:delegate];
4151 [cydia_ setDelegate:delegate];
4155 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4156 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4158 WebView *webview([[webview_ _documentView] webView]);
4160 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4162 NSString *application = package == nil ? @"Cydia" : [NSString
4163 stringWithFormat:@"Cydia/%@",
4168 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4170 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4171 if (Product_ != nil)
4172 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4174 [webview setApplicationNameForUserAgent:application];
4181 /* Confirmation {{{ */
4182 @protocol ConfirmationControllerDelegate
4183 - (void) cancelAndClear:(bool)clear;
4184 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4188 @interface ConfirmationController : CYBrowserController {
4189 _transient Database *database_;
4190 UIAlertView *essential_;
4197 - (id) initWithDatabase:(Database *)database;
4201 @implementation ConfirmationController
4208 if (essential_ != nil)
4209 [essential_ release];
4213 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4214 NSString *context([alert context]);
4216 if ([context isEqualToString:@"remove"]) {
4217 if (button == [alert cancelButtonIndex]) {
4218 [self dismissModalViewControllerAnimated:YES];
4219 } else if (button == [alert firstOtherButtonIndex]) {
4222 [delegate_ confirmWithNavigationController:[self navigationController]];
4225 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4226 } else if ([context isEqualToString:@"unable"]) {
4227 [self dismissModalViewControllerAnimated:YES];
4228 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4230 [super alertView:alert clickedButtonAtIndex:button];
4234 - (void) _doContinue {
4235 [self dismissModalViewControllerAnimated:YES];
4236 [delegate_ cancelAndClear:NO];
4239 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4240 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4244 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4245 [super webView:view didClearWindowObject:window forFrame:frame];
4246 [window setValue:changes_ forKey:@"changes"];
4247 [window setValue:issues_ forKey:@"issues"];
4248 [window setValue:sizes_ forKey:@"sizes"];
4249 [window setValue:self forKey:@"queue"];
4252 - (id) initWithDatabase:(Database *)database {
4253 if ((self = [super init]) != nil) {
4254 database_ = database;
4256 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4258 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4259 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4260 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4261 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4262 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4266 pkgDepCache::Policy *policy([database_ policy]);
4268 pkgCacheFile &cache([database_ cache]);
4269 NSArray *packages = [database_ packages];
4270 for (Package *package in packages) {
4271 pkgCache::PkgIterator iterator = [package iterator];
4272 pkgDepCache::StateCache &state(cache[iterator]);
4274 NSString *name([package name]);
4276 if (state.NewInstall())
4277 [installing addObject:name];
4278 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4279 [reinstalling addObject:name];
4280 else if (state.Upgrade())
4281 [upgrading addObject:name];
4282 else if (state.Downgrade())
4283 [downgrading addObject:name];
4284 else if (state.Delete()) {
4285 if ([package essential])
4287 [removing addObject:name];
4290 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4291 substrate_ |= DepSubstrate(iterator.CurrentVer());
4296 else if (Advanced_) {
4297 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4299 essential_ = [[UIAlertView alloc]
4300 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4301 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4303 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4304 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4307 [essential_ setContext:@"remove"];
4309 essential_ = [[UIAlertView alloc]
4310 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4311 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4313 cancelButtonTitle:UCLocalize("OKAY")
4314 otherButtonTitles:nil
4317 [essential_ setContext:@"unable"];
4320 changes_ = [[NSArray alloc] initWithObjects:
4328 issues_ = [database_ issues];
4330 issues_ = [issues_ retain];
4332 sizes_ = [[NSArray alloc] initWithObjects:
4333 SizeString([database_ fetcher].FetchNeeded()),
4334 SizeString([database_ fetcher].PartialPresent()),
4337 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4339 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4340 initWithTitle:UCLocalize("CANCEL")
4341 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4342 style:UIBarButtonItemStylePlain
4344 action:@selector(cancelButtonClicked)
4349 - (void) applyRightButton {
4350 #if !AlwaysReload && !IgnoreInstall
4351 if (issues_ == nil && ![self isLoading])
4352 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4353 initWithTitle:UCLocalize("CONFIRM")
4354 style:UIBarButtonItemStylePlain
4356 action:@selector(confirmButtonClicked)
4359 [super applyRightButton];
4361 [[self navigationItem] setRightBarButtonItem:nil];
4365 - (void) cancelButtonClicked {
4366 [self dismissModalViewControllerAnimated:YES];
4367 [delegate_ cancelAndClear:YES];
4371 - (void) confirmButtonClicked {
4375 if (essential_ != nil)
4380 [delegate_ confirmWithNavigationController:[self navigationController]];
4388 /* Progress Data {{{ */
4389 @interface ProgressData : NSObject {
4391 // XXX: should these really both be _transient?
4392 _transient id target_;
4393 _transient id object_;
4396 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4403 @implementation ProgressData
4405 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4406 if ((self = [super init]) != nil) {
4407 selector_ = selector;
4427 /* Progress Controller {{{ */
4428 @interface ProgressController : CYViewController <
4429 ConfigurationDelegate,
4432 _transient Database *database_;
4433 UIProgressBar *progress_;
4434 UITextView *output_;
4435 UITextLabel *status_;
4436 UIPushButton *close_;
4438 SHA1SumValue springlist_;
4439 SHA1SumValue notifyconf_;
4443 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4445 - (void) _retachThread;
4446 - (void) _detachNewThreadData:(ProgressData *)data;
4447 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4453 @protocol ProgressControllerDelegate
4454 - (void) progressControllerIsComplete:(ProgressController *)sender;
4457 @implementation ProgressController
4460 [database_ setDelegate:nil];
4461 [progress_ release];
4470 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4471 if ((self = [super init]) != nil) {
4472 database_ = database;
4473 [database_ setDelegate:self];
4474 delegate_ = delegate;
4476 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4478 progress_ = [[UIProgressBar alloc] init];
4479 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4480 [progress_ setStyle:0];
4482 status_ = [[UITextLabel alloc] init];
4483 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4484 [status_ setColor:[UIColor whiteColor]];
4485 [status_ setBackgroundColor:[UIColor clearColor]];
4486 [status_ setCentersHorizontally:YES];
4487 //[status_ setFont:font];
4489 output_ = [[UITextView alloc] init];
4491 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4492 //[output_ setTextFont:@"Courier New"];
4493 [output_ setFont:[[output_ font] fontWithSize:12]];
4494 [output_ setTextColor:[UIColor whiteColor]];
4495 [output_ setBackgroundColor:[UIColor clearColor]];
4496 [output_ setMarginTop:0];
4497 [output_ setAllowsRubberBanding:YES];
4498 [output_ setEditable:NO];
4499 [[self view] addSubview:output_];
4501 close_ = [[UIPushButton alloc] init];
4502 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4503 [close_ setAutosizesToFit:NO];
4504 [close_ setDrawsShadow:YES];
4505 [close_ setStretchBackground:YES];
4506 [close_ setEnabled:YES];
4507 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4508 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4509 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4510 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4514 - (void) positionViews {
4515 CGRect bounds = [[self view] bounds];
4516 CGSize prgsize = [UIProgressBar defaultSize];
4519 (bounds.size.width - prgsize.width) / 2,
4520 bounds.size.height - prgsize.height - 20
4523 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4525 [progress_ setFrame:prgrect];
4526 [status_ setFrame:CGRectMake(
4528 bounds.size.height - prgsize.height - 50,
4529 bounds.size.width - 20,
4532 [output_ setFrame:CGRectMake(
4535 bounds.size.width - 20,
4536 bounds.size.height - 62
4538 [close_ setFrame:CGRectMake(
4539 (bounds.size.width - closewidth) / 2,
4540 bounds.size.height - prgsize.height - 50,
4546 - (void) viewWillAppear:(BOOL)animated {
4547 [super viewDidAppear:animated];
4548 [[self navigationItem] setHidesBackButton:YES];
4549 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4551 [self positionViews];
4554 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4555 [self positionViews];
4558 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4559 NSString *context([alert context]);
4561 if ([context isEqualToString:@"conffile"]) {
4562 FILE *input = [database_ input];
4563 if (button == [alert cancelButtonIndex])
4564 fprintf(input, "N\n");
4565 else if (button == [alert firstOtherButtonIndex])
4566 fprintf(input, "Y\n");
4571 - (void) closeButtonPushed {
4574 UpdateExternalStatus(0);
4578 [self dismissModalViewControllerAnimated:YES];
4582 [delegate_ terminateWithSuccess];
4583 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4584 [delegate_ suspendWithAnimation:YES];
4586 [delegate_ suspend];*/
4598 system("/usr/bin/sbreload");
4604 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4605 SBReboot(SBSSpringBoardServerPort());
4607 reboot2(RB_AUTOBOOT);
4612 - (void) _retachThread {
4613 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4615 [[self view] addSubview:close_];
4616 [progress_ removeFromSuperview];
4617 [status_ removeFromSuperview];
4619 [database_ popErrorWithTitle:title_];
4620 [delegate_ progressControllerIsComplete:self];
4624 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4627 MMap mmap(file, MMap::ReadOnly);
4629 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4630 if (!(notifyconf_ == sha1.Result()))
4637 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4640 MMap mmap(file, MMap::ReadOnly);
4642 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4643 if (!(springlist_ == sha1.Result()))
4649 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4650 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4651 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4652 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4653 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4657 system("su -c /usr/bin/uicache mobile");
4660 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4662 [delegate_ setStatusBarShowsProgress:NO];
4665 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4666 [[data target] performSelector:[data selector] withObject:[data object]];
4667 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4670 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4671 UpdateExternalStatus(1);
4678 title_ = [title retain];
4680 [[self navigationItem] setTitle:title_];
4682 [status_ setText:nil];
4683 [output_ setText:@""];
4684 [progress_ setProgress:0];
4686 [close_ removeFromSuperview];
4687 [[self view] addSubview:progress_];
4688 [[self view] addSubview:status_];
4690 [delegate_ setStatusBarShowsProgress:YES];
4695 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4698 MMap mmap(file, MMap::ReadOnly);
4700 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4701 notifyconf_ = sha1.Result();
4707 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4710 MMap mmap(file, MMap::ReadOnly);
4712 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4713 springlist_ = sha1.Result();
4718 detachNewThreadSelector:@selector(_detachNewThreadData:)
4720 withObject:[[[ProgressData alloc]
4721 initWithSelector:selector
4728 - (void) repairWithSelector:(SEL)selector {
4730 detachNewThreadSelector:selector
4733 title:UCLocalize("REPAIRING")
4737 - (void) setConfigurationData:(NSString *)data {
4739 performSelectorOnMainThread:@selector(_setConfigurationData:)
4745 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4746 CYActionSheet *sheet([[[CYActionSheet alloc]
4748 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4749 defaultButtonIndex:0
4752 [sheet setMessage:error];
4753 [sheet yieldToPopupAlertAnimated:YES];
4757 - (void) setProgressTitle:(NSString *)title {
4759 performSelectorOnMainThread:@selector(_setProgressTitle:)
4765 - (void) setProgressPercent:(float)percent {
4767 performSelectorOnMainThread:@selector(_setProgressPercent:)
4768 withObject:[NSNumber numberWithFloat:percent]
4773 - (void) startProgress {
4776 - (void) addProgressOutput:(NSString *)output {
4778 performSelectorOnMainThread:@selector(_addProgressOutput:)
4784 - (bool) isCancelling:(size_t)received {
4788 - (void) _setConfigurationData:(NSString *)data {
4789 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4791 if (!conffile_r(data)) {
4792 lprintf("E:invalid conffile\n");
4796 NSString *ofile = conffile_r[1];
4797 //NSString *nfile = conffile_r[2];
4799 UIAlertView *alert = [[[UIAlertView alloc]
4800 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4801 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4803 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4804 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4805 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4809 [alert setContext:@"conffile"];
4813 - (void) _setProgressTitle:(NSString *)title {
4814 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4815 for (size_t i(0), e([words count]); i != e; ++i) {
4816 NSString *word([words objectAtIndex:i]);
4817 if (Package *package = [database_ packageWithName:word])
4818 [words replaceObjectAtIndex:i withObject:[package name]];
4821 [status_ setText:[words componentsJoinedByString:@" "]];
4824 - (void) _setProgressPercent:(NSNumber *)percent {
4825 [progress_ setProgress:[percent floatValue]];
4828 - (void) _addProgressOutput:(NSString *)output {
4829 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4830 CGSize size = [output_ contentSize];
4831 CGPoint offset = [output_ contentOffset];
4832 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4833 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4834 [output_ scrollRectToVisible:rect animated:YES];
4838 - (BOOL) isRunning {
4845 /* Cell Content View {{{ */
4846 @protocol ContentDelegate
4847 - (void) drawContentRect:(CGRect)rect;
4850 @interface ContentView : UIView {
4851 _transient id<ContentDelegate> delegate_;
4856 @implementation ContentView
4858 - (id) initWithFrame:(CGRect)frame {
4859 if ((self = [super initWithFrame:frame]) != nil) {
4860 [self setNeedsDisplayOnBoundsChange:YES];
4864 - (void) setDelegate:(id<ContentDelegate>)delegate {
4865 delegate_ = delegate;
4868 - (void) drawRect:(CGRect)rect {
4869 [super drawRect:rect];
4870 [delegate_ drawContentRect:rect];
4875 /* Cydia TableView Cell {{{ */
4876 @interface CYTableViewCell : UITableViewCell {
4877 ContentView *content_;
4883 @implementation CYTableViewCell
4890 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4891 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4893 if (view == content_) {
4894 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4895 highlighted_ = highlighted;
4898 [super _updateHighlightColorsForView:view highlighted:highlighted];
4901 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4902 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4903 highlighted_ = selected;
4905 [super setSelected:selected animated:animated];
4906 [content_ setNeedsDisplay];
4911 /* Package Cell {{{ */
4912 @interface PackageCell : CYTableViewCell <
4917 NSString *description_;
4925 - (PackageCell *) init;
4926 - (void) setPackage:(Package *)package;
4928 - (void) drawContentRect:(CGRect)rect;
4932 @implementation PackageCell
4934 - (void) clearPackage {
4945 if (description_ != nil) {
4946 [description_ release];
4950 if (source_ != nil) {
4955 if (badge_ != nil) {
4960 if (placard_ != nil) {
4970 [self clearPackage];
4974 - (PackageCell *) init {
4975 CGRect frame(CGRectMake(0, 0, 320, 74));
4976 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4977 UIView *content([self contentView]);
4978 CGRect bounds([content bounds]);
4980 content_ = [[ContentView alloc] initWithFrame:bounds];
4981 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4982 [content addSubview:content_];
4984 [content_ setDelegate:self];
4985 [content_ setOpaque:YES];
4989 - (void) _setBackgroundColor {
4991 if (NSString *mode = [package_ mode]) {
4992 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4993 color = remove ? RemovingColor_ : InstallingColor_;
4995 color = [UIColor whiteColor];
4997 [content_ setBackgroundColor:color];
4998 [self setNeedsDisplay];
5001 - (void) setPackage:(Package *)package {
5002 [self clearPackage];
5005 Source *source = [package source];
5007 icon_ = [[package icon] retain];
5008 name_ = [[package name] retain];
5011 description_ = [package longDescription];
5012 if (description_ == nil)
5013 description_ = [package shortDescription];
5014 if (description_ != nil)
5015 description_ = [description_ retain];
5017 commercial_ = [package isCommercial];
5019 package_ = [package retain];
5021 NSString *label = nil;
5022 bool trusted = false;
5024 if (source != nil) {
5025 label = [source label];
5026 trusted = [source trusted];
5027 } else if ([[package id] isEqualToString:@"firmware"])
5028 label = UCLocalize("APPLE");
5030 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5032 NSString *from(label);
5034 NSString *section = [package simpleSection];
5035 if (section != nil && ![section isEqualToString:label]) {
5036 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5037 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5040 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5041 source_ = [from retain];
5043 if (NSString *purpose = [package primaryPurpose])
5044 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5045 badge_ = [badge_ retain];
5047 if ([package installed] != nil)
5048 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
5049 placard_ = [placard_ retain];
5051 [self _setBackgroundColor];
5052 [content_ setNeedsDisplay];
5055 - (void) drawContentRect:(CGRect)rect {
5056 bool highlighted(highlighted_);
5057 float width([self bounds].size.width);
5060 CGContextRef context(UIGraphicsGetCurrentContext());
5061 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5062 CGContextFillRect(context, rect);
5067 rect.size = [icon_ size];
5069 rect.size.width /= 2;
5070 rect.size.height /= 2;
5072 rect.origin.x = 25 - rect.size.width / 2;
5073 rect.origin.y = 25 - rect.size.height / 2;
5075 [icon_ drawInRect:rect];
5078 if (badge_ != nil) {
5080 rect.size = [badge_ size];
5082 rect.size.width /= 2;
5083 rect.size.height /= 2;
5085 rect.origin.x = 36 - rect.size.width / 2;
5086 rect.origin.y = 36 - rect.size.height / 2;
5088 [badge_ drawInRect:rect];
5095 UISetColor(commercial_ ? Purple_ : Black_);
5096 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5097 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5100 UISetColor(commercial_ ? Purplish_ : Gray_);
5101 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5103 if (placard_ != nil)
5104 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5109 /* Section Cell {{{ */
5110 @interface SectionCell : CYTableViewCell <
5122 - (void) setSection:(Section *)section editing:(BOOL)editing;
5126 @implementation SectionCell
5128 - (void) clearSection {
5129 if (basic_ != nil) {
5134 if (section_ != nil) {
5144 if (count_ != nil) {
5151 [self clearSection];
5157 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5158 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5159 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5160 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5161 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5163 UIView *content([self contentView]);
5164 CGRect bounds([content bounds]);
5166 content_ = [[ContentView alloc] initWithFrame:bounds];
5167 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5168 [content addSubview:content_];
5169 [content_ setBackgroundColor:[UIColor whiteColor]];
5171 [content_ setDelegate:self];
5175 - (void) onSwitch:(id)sender {
5176 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5177 if (metadata == nil) {
5178 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5179 [Sections_ setObject:metadata forKey:basic_];
5182 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5186 - (void) setSection:(Section *)section editing:(BOOL)editing {
5187 if (editing != editing_) {
5189 [switch_ removeFromSuperview];
5191 [self addSubview:switch_];
5195 [self clearSection];
5197 if (section == nil) {
5198 name_ = [UCLocalize("ALL_PACKAGES") retain];
5201 basic_ = [section name];
5203 basic_ = [basic_ retain];
5205 section_ = [section localized];
5206 if (section_ != nil)
5207 section_ = [section_ retain];
5209 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5210 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5213 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5216 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5217 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5219 [content_ setNeedsDisplay];
5222 - (void) setFrame:(CGRect)frame {
5223 [super setFrame:frame];
5225 CGRect rect([switch_ frame]);
5226 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5229 - (void) drawContentRect:(CGRect)rect {
5230 bool highlighted(highlighted_ && !editing_);
5232 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5237 float width(rect.size.width);
5243 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5245 CGSize size = [count_ sizeWithFont:Font14_];
5249 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5255 /* File Table {{{ */
5256 @interface FileTable : CYViewController <
5257 UITableViewDataSource,
5260 _transient Database *database_;
5263 NSMutableArray *files_;
5267 - (id) initWithDatabase:(Database *)database;
5268 - (void) setPackage:(Package *)package;
5272 @implementation FileTable
5275 if (package_ != nil)
5284 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5285 return files_ == nil ? 0 : [files_ count];
5288 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5292 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5293 static NSString *reuseIdentifier = @"Cell";
5295 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5297 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5298 [cell setFont:[UIFont systemFontOfSize:16]];
5300 [cell setText:[files_ objectAtIndex:indexPath.row]];
5301 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5306 - (id) initWithDatabase:(Database *)database {
5307 if ((self = [super init]) != nil) {
5308 database_ = database;
5310 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5312 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5314 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5315 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5316 [list_ setRowHeight:24.0f];
5317 [[self view] addSubview:list_];
5319 [list_ setDataSource:self];
5320 [list_ setDelegate:self];
5324 - (void) setPackage:(Package *)package {
5325 if (package_ != nil) {
5326 [package_ autorelease];
5335 [files_ removeAllObjects];
5337 if (package != nil) {
5338 package_ = [package retain];
5339 name_ = [[package id] retain];
5341 if (NSArray *files = [package files])
5342 [files_ addObjectsFromArray:files];
5344 if ([files_ count] != 0) {
5345 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5346 [files_ removeObjectAtIndex:0];
5347 [files_ sortUsingSelector:@selector(compareByPath:)];
5349 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5350 [stack addObject:@"/"];
5352 for (int i(0), e([files_ count]); i != e; ++i) {
5353 NSString *file = [files_ objectAtIndex:i];
5354 while (![file hasPrefix:[stack lastObject]])
5355 [stack removeLastObject];
5356 NSString *directory = [stack lastObject];
5357 [stack addObject:[file stringByAppendingString:@"/"]];
5358 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5359 ([stack count] - 2) * 3, "",
5360 [file substringFromIndex:[directory length]]
5369 - (void) reloadData {
5370 [self setPackage:[database_ packageWithName:name_]];
5375 /* Package Controller {{{ */
5376 @interface CYPackageController : CYBrowserController <
5377 UIActionSheetDelegate
5379 _transient Database *database_;
5383 NSMutableArray *buttons_;
5384 UIBarButtonItem *button_;
5387 - (id) initWithDatabase:(Database *)database;
5388 - (void) setPackage:(Package *)package;
5392 @implementation CYPackageController
5395 if (package_ != nil)
5409 if ([self retainCount] == 1)
5410 [delegate_ setPackageController:self];
5414 /* XXX: this is not safe at all... localization of /fail/ */
5415 - (void) _clickButtonWithName:(NSString *)name {
5416 if ([name isEqualToString:UCLocalize("CLEAR")])
5417 [delegate_ clearPackage:package_];
5418 else if ([name isEqualToString:UCLocalize("INSTALL")])
5419 [delegate_ installPackage:package_];
5420 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5421 [delegate_ installPackage:package_];
5422 else if ([name isEqualToString:UCLocalize("REMOVE")])
5423 [delegate_ removePackage:package_];
5424 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5425 [delegate_ installPackage:package_];
5426 else _assert(false);
5429 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5430 NSString *context([sheet context]);
5432 if ([context isEqualToString:@"modify"]) {
5433 if (button != [sheet cancelButtonIndex]) {
5434 NSString *buttonName = [buttons_ objectAtIndex:button];
5435 [self _clickButtonWithName:buttonName];
5438 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5442 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5443 [super webView:view didClearWindowObject:window forFrame:frame];
5444 [window setValue:package_ forKey:@"package"];
5447 - (bool) _allowJavaScriptPanel {
5452 - (void) _customButtonClicked {
5453 int count([buttons_ count]);
5458 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5460 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5461 [buttons addObjectsFromArray:buttons_];
5463 UIActionSheet *sheet = [[[UIActionSheet alloc]
5466 cancelButtonTitle:nil
5467 destructiveButtonTitle:nil
5468 otherButtonTitles:nil
5471 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5473 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5474 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5476 [sheet setContext:@"modify"];
5478 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5482 // We don't want to allow non-commercial packages to do custom things to the install button,
5483 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5484 - (void) customButtonClicked {
5486 [super customButtonClicked];
5488 [self _customButtonClicked];
5491 - (void) reloadButtonClicked {
5492 // Don't reload a commerical package by tapping the loading button,
5493 // but if it's not an Install button, we should forward it on.
5494 if (![package_ uninstalled])
5495 [self _customButtonClicked];
5498 - (void) applyLoadingTitle {
5499 // Don't show "Loading" as the title. Ever.
5502 - (UIBarButtonItem *) rightButton {
5507 - (id) initWithDatabase:(Database *)database {
5508 if ((self = [super init]) != nil) {
5509 database_ = database;
5510 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5511 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5515 - (void) setPackage:(Package *)package {
5516 if (package_ != nil) {
5517 [package_ autorelease];
5526 [buttons_ removeAllObjects];
5528 if (package != nil) {
5531 package_ = [package retain];
5532 name_ = [[package id] retain];
5533 commercial_ = [package isCommercial];
5535 if ([package_ mode] != nil)
5536 [buttons_ addObject:UCLocalize("CLEAR")];
5537 if ([package_ source] == nil);
5538 else if ([package_ upgradableAndEssential:NO])
5539 [buttons_ addObject:UCLocalize("UPGRADE")];
5540 else if ([package_ uninstalled])
5541 [buttons_ addObject:UCLocalize("INSTALL")];
5543 [buttons_ addObject:UCLocalize("REINSTALL")];
5544 if (![package_ uninstalled])
5545 [buttons_ addObject:UCLocalize("REMOVE")];
5552 switch ([buttons_ count]) {
5553 case 0: title = nil; break;
5554 case 1: title = [buttons_ objectAtIndex:0]; break;
5555 default: title = UCLocalize("MODIFY"); break;
5558 button_ = [[UIBarButtonItem alloc]
5560 style:UIBarButtonItemStylePlain
5562 action:@selector(customButtonClicked)
5568 - (bool) isLoading {
5569 return commercial_ ? [super isLoading] : false;
5572 - (void) reloadData {
5573 [self setPackage:[database_ packageWithName:name_]];
5578 /* Package Table {{{ */
5579 @interface PackageTable : UIView <
5580 UITableViewDataSource,
5583 _transient Database *database_;
5585 NSMutableArray *packages_;
5586 NSMutableArray *sections_;
5588 NSMutableArray *index_;
5589 NSMutableDictionary *indices_;
5590 // XXX: this target_ seems to be delegate_. :(
5591 _transient id target_;
5593 // XXX: why do we even have this delegate_?
5594 _transient id delegate_;
5597 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5599 - (void) setDelegate:(id)delegate;
5601 - (void) reloadData;
5602 - (void) resetCursor;
5604 - (UITableView *) list;
5606 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5608 - (void) deselectWithAnimation:(BOOL)animated;
5612 @implementation PackageTable
5615 [packages_ release];
5616 [sections_ release];
5624 + (BOOL) hasIndexedCollation {
5625 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5628 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5629 NSInteger count([sections_ count]);
5630 return count == 0 ? 1 : count;
5633 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5634 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5636 return [[sections_ objectAtIndex:section] name];
5639 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5640 if ([sections_ count] == 0)
5642 return [[sections_ objectAtIndex:section] count];
5645 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5646 @synchronized (database_) {
5647 if ([database_ era] != era_)
5650 Section *section([sections_ objectAtIndex:[path section]]);
5651 NSInteger row([path row]);
5652 Package *package([packages_ objectAtIndex:([section row] + row)]);
5653 return [[package retain] autorelease];
5656 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5657 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5659 cell = [[[PackageCell alloc] init] autorelease];
5660 [cell setPackage:[self packageAtIndexPath:path]];
5664 - (void) deselectWithAnimation:(BOOL)animated {
5665 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5668 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5669 Package *package([self packageAtIndexPath:path]);
5670 package = [database_ packageWithName:[package id]];
5671 [target_ performSelector:action_ withObject:package];
5675 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5676 // XXX: is 20 the most optimal number here?
5677 return [packages_ count] > 20 ? index_ : nil;
5680 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5681 if ([[self class] hasIndexedCollation]) {
5682 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5688 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5689 if ((self = [super initWithFrame:frame]) != nil) {
5690 database_ = database;
5695 index_ = [[self class] hasIndexedCollation]
5696 ? [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
5697 : [[NSMutableArray alloc] initWithCapacity:32];
5698 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5700 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5701 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5703 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5704 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5705 [list_ setRowHeight:73.0f];
5706 [self addSubview:list_];
5708 [list_ setDataSource:self];
5709 [list_ setDelegate:self];
5713 - (void) setDelegate:(id)delegate {
5714 delegate_ = delegate;
5717 - (bool) hasPackage:(Package *)package {
5721 - (void) reloadData {
5722 era_ = [database_ era];
5723 NSArray *packages = [database_ packages];
5725 [packages_ removeAllObjects];
5726 [sections_ removeAllObjects];
5728 _profile(PackageTable$reloadData$Filter)
5729 for (Package *package in packages)
5730 if ([self hasPackage:package])
5731 [packages_ addObject:package];
5734 [indices_ removeAllObjects];
5736 Section *section = nil;
5738 if ([[self class] hasIndexedCollation]) {
5739 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5740 NSArray *titles = [collation sectionIndexTitles];
5743 _profile(PackageTable$reloadData$Section)
5744 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5748 _profile(PackageTable$reloadData$Section$Package)
5749 package = [packages_ objectAtIndex:offset];
5750 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5753 while (secidx < index) {
5756 _profile(PackageTable$reloadData$Section$Allocate)
5757 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5760 _profile(PackageTable$reloadData$Section$Add)
5761 [sections_ addObject:section];
5765 [section addToCount];
5769 [index_ removeAllObjects];
5771 _profile(PackageTable$reloadData$Section)
5772 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5776 _profile(PackageTable$reloadData$Section$Package)
5777 package = [packages_ objectAtIndex:offset];
5778 index = [package index];
5781 if (section == nil || [section index] != index) {
5782 _profile(PackageTable$reloadData$Section$Allocate)
5783 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5786 [index_ addObject:[section name]];
5787 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5789 _profile(PackageTable$reloadData$Section$Add)
5790 [sections_ addObject:section];
5794 [section addToCount];
5799 _profile(PackageTable$reloadData$List)
5804 - (void) resetCursor {
5805 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5808 - (UITableView *) list {
5812 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5813 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5818 /* Filtered Package Table {{{ */
5819 @interface FilteredPackageTable : PackageTable {
5825 - (void) setObject:(id)object;
5826 - (void) setObject:(id)object forFilter:(SEL)filter;
5828 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5832 @implementation FilteredPackageTable
5840 - (void) setFilter:(SEL)filter {
5843 /* XXX: this is an unsafe optimization of doomy hell */
5844 Method method(class_getInstanceMethod([Package class], filter));
5845 _assert(method != NULL);
5846 imp_ = method_getImplementation(method);
5847 _assert(imp_ != NULL);
5850 - (void) setObject:(id)object {
5856 object_ = [object retain];
5859 - (void) setObject:(id)object forFilter:(SEL)filter {
5860 [self setFilter:filter];
5861 [self setObject:object];
5864 - (bool) hasPackage:(Package *)package {
5865 _profile(FilteredPackageTable$hasPackage)
5866 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5870 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5871 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5872 [self setFilter:filter];
5873 object_ = [object retain];
5881 /* Filtered Package Controller {{{ */
5882 @interface FilteredPackageController : CYViewController {
5883 _transient Database *database_;
5884 FilteredPackageTable *packages_;
5888 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5892 @implementation FilteredPackageController
5895 [packages_ release];
5901 - (void) viewDidAppear:(BOOL)animated {
5902 [super viewDidAppear:animated];
5903 [packages_ deselectWithAnimation:animated];
5906 - (void) didSelectPackage:(Package *)package {
5907 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_] autorelease]);
5908 [view setPackage:package];
5909 [view setDelegate:delegate_];
5910 [[self navigationController] pushViewController:view animated:YES];
5913 - (NSString *) title { return title_; }
5915 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5916 if ((self = [super init]) != nil) {
5917 database_ = database;
5918 title_ = [title copy];
5919 [[self navigationItem] setTitle:title_];
5921 packages_ = [[FilteredPackageTable alloc]
5922 initWithFrame:[[self view] bounds]
5925 action:@selector(didSelectPackage:)
5930 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5931 [[self view] addSubview:packages_];
5935 - (void) reloadData {
5936 [packages_ reloadData];
5939 - (void) setDelegate:(id)delegate {
5940 [super setDelegate:delegate];
5941 [packages_ setDelegate:delegate];
5948 /* Source Cell {{{ */
5949 @interface SourceCell : CYTableViewCell <
5954 NSString *description_;
5958 - (void) setSource:(Source *)source;
5962 @implementation SourceCell
5964 - (void) clearSource {
5967 [description_ release];
5976 - (void) setSource:(Source *)source {
5980 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5982 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5983 icon_ = [icon_ retain];
5985 origin_ = [[source name] retain];
5986 label_ = [[source uri] retain];
5987 description_ = [[source description] retain];
5989 [content_ setNeedsDisplay];
5997 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5998 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5999 UIView *content([self contentView]);
6000 CGRect bounds([content bounds]);
6002 content_ = [[ContentView alloc] initWithFrame:bounds];
6003 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6004 [content_ setBackgroundColor:[UIColor whiteColor]];
6005 [content addSubview:content_];
6007 [content_ setDelegate:self];
6008 [content_ setOpaque:YES];
6012 - (void) drawContentRect:(CGRect)rect {
6013 bool highlighted(highlighted_);
6014 float width(rect.size.width);
6017 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
6024 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
6028 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
6032 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
6037 /* Source Table {{{ */
6038 @interface SourcesController : CYViewController <
6039 UITableViewDataSource,
6042 _transient Database *database_;
6044 NSMutableArray *sources_;
6048 UIProgressHUD *hud_;
6051 //NSURLConnection *installer_;
6052 NSURLConnection *trivial_;
6053 NSURLConnection *trivial_bz2_;
6054 NSURLConnection *trivial_gz_;
6055 //NSURLConnection *automatic_;
6060 - (id) initWithDatabase:(Database *)database;
6062 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
6066 @implementation SourcesController
6068 - (void) _releaseConnection:(NSURLConnection *)connection {
6069 if (connection != nil) {
6070 [connection cancel];
6071 //[connection setDelegate:nil];
6072 [connection release];
6084 //[self _releaseConnection:installer_];
6085 [self _releaseConnection:trivial_];
6086 [self _releaseConnection:trivial_gz_];
6087 [self _releaseConnection:trivial_bz2_];
6088 //[self _releaseConnection:automatic_];
6095 - (void) viewDidAppear:(BOOL)animated {
6096 [super viewDidAppear:animated];
6097 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6100 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
6101 return offset_ == 0 ? 1 : 2;
6104 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
6105 switch (section + (offset_ == 0 ? 1 : 0)) {
6106 case 0: return UCLocalize("ENTERED_BY_USER");
6107 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
6113 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6114 int count = [sources_ count];
6116 case 0: return (offset_ == 0 ? count : offset_);
6117 case 1: return count - offset_;
6123 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
6125 switch (indexPath.section) {
6126 case 0: idx = indexPath.row; break;
6127 case 1: idx = indexPath.row + offset_; break;
6131 return [sources_ objectAtIndex:idx];
6134 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6135 Source *source = [self sourceAtIndexPath:indexPath];
6136 return [source description] == nil ? 56 : 73;
6139 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6140 static NSString *cellIdentifier = @"SourceCell";
6142 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
6143 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
6144 [cell setSource:[self sourceAtIndexPath:indexPath]];
6149 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
6150 return UITableViewCellAccessoryDisclosureIndicator;
6153 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6154 Source *source = [self sourceAtIndexPath:indexPath];
6156 FilteredPackageController *packages = [[[FilteredPackageController alloc]
6157 initWithDatabase:database_
6158 title:[source label]
6159 filter:@selector(isVisibleInSource:)
6163 [packages setDelegate:delegate_];
6165 [[self navigationController] pushViewController:packages animated:YES];
6168 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
6169 Source *source = [self sourceAtIndexPath:indexPath];
6170 return [source record] != nil;
6173 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
6174 Source *source = [self sourceAtIndexPath:indexPath];
6175 [Sources_ removeObjectForKey:[source key]];
6176 [delegate_ syncData];
6180 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
6183 @"./", @"Distribution",
6184 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
6186 [delegate_ syncData];
6189 - (NSString *) getWarning {
6190 NSString *href(href_);
6191 NSRange colon([href rangeOfString:@"://"]);
6192 if (colon.location != NSNotFound)
6193 href = [href substringFromIndex:(colon.location + 3)];
6194 href = [href stringByAddingPercentEscapes];
6195 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
6196 href = [href stringByCachingURLWithCurrentCDN];
6198 NSURL *url([NSURL URLWithString:href]);
6200 NSStringEncoding encoding;
6201 NSError *error(nil);
6203 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
6204 return [warning length] == 0 ? nil : warning;
6208 - (void) _endConnection:(NSURLConnection *)connection {
6209 // XXX: the memory management in this method is horribly awkward
6211 NSURLConnection **field = NULL;
6212 if (connection == trivial_)
6214 else if (connection == trivial_bz2_)
6215 field = &trivial_bz2_;
6216 else if (connection == trivial_gz_)
6217 field = &trivial_gz_;
6218 _assert(field != NULL);
6219 [connection release];
6224 trivial_bz2_ == nil &&
6230 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6233 UIAlertView *alert = [[[UIAlertView alloc]
6234 initWithTitle:UCLocalize("SOURCE_WARNING")
6237 cancelButtonTitle:UCLocalize("CANCEL")
6238 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6241 [alert setContext:@"warning"];
6242 [alert setNumberOfRows:1];
6246 } else if (error_ != nil) {
6247 UIAlertView *alert = [[[UIAlertView alloc]
6248 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6249 message:[error_ localizedDescription]
6251 cancelButtonTitle:UCLocalize("OK")
6252 otherButtonTitles:nil
6255 [alert setContext:@"urlerror"];
6258 UIAlertView *alert = [[[UIAlertView alloc]
6259 initWithTitle:UCLocalize("NOT_REPOSITORY")
6260 message:UCLocalize("NOT_REPOSITORY_EX")
6262 cancelButtonTitle:UCLocalize("OK")
6263 otherButtonTitles:nil
6266 [alert setContext:@"trivial"];
6270 [delegate_ setStatusBarShowsProgress:NO];
6271 [delegate_ removeProgressHUD:hud_];
6281 if (error_ != nil) {
6288 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6289 switch ([response statusCode]) {
6295 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6296 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6298 error_ = [error retain];
6299 [self _endConnection:connection];
6302 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6303 [self _endConnection:connection];
6306 - (NSString *) title { return UCLocalize("SOURCES"); }
6308 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6309 NSMutableURLRequest *request = [NSMutableURLRequest
6310 requestWithURL:[NSURL URLWithString:href]
6311 cachePolicy:NSURLRequestUseProtocolCachePolicy
6312 timeoutInterval:120.0
6315 [request setHTTPMethod:method];
6317 if (Machine_ != NULL)
6318 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6319 if (UniqueID_ != nil)
6320 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6322 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6324 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6327 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6328 NSString *context([alert context]);
6330 if ([context isEqualToString:@"source"]) {
6333 NSString *href = [[alert textField] text];
6335 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6337 if (![href hasSuffix:@"/"])
6338 href_ = [href stringByAppendingString:@"/"];
6341 href_ = [href_ retain];
6343 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6344 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6345 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6346 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6350 // XXX: this is stupid
6351 hud_ = [[delegate_ addProgressHUD] retain];
6352 [hud_ setText:UCLocalize("VERIFYING_URL")];
6361 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6362 } else if ([context isEqualToString:@"trivial"])
6363 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6364 else if ([context isEqualToString:@"urlerror"])
6365 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6366 else if ([context isEqualToString:@"warning"]) {
6381 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6385 - (id) initWithDatabase:(Database *)database {
6386 if ((self = [super init]) != nil) {
6387 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6388 [self updateButtonsForEditingStatus:NO animated:NO];
6390 database_ = database;
6391 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6393 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6394 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6395 [[self view] addSubview:list_];
6397 [list_ setDataSource:self];
6398 [list_ setDelegate:self];
6404 - (void) reloadData {
6406 if (!list.ReadMainList())
6409 [sources_ removeAllObjects];
6410 [sources_ addObjectsFromArray:[database_ sources]];
6412 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6415 int count([sources_ count]);
6417 for (int i = 0; i != count; i++) {
6418 if ([[sources_ objectAtIndex:i] record] == nil)
6423 [list_ setEditing:NO];
6424 [self updateButtonsForEditingStatus:NO animated:NO];
6428 - (void) showAddSourcePrompt {
6429 UIAlertView *alert = [[[UIAlertView alloc]
6430 initWithTitle:UCLocalize("ENTER_APT_URL")
6433 cancelButtonTitle:UCLocalize("CANCEL")
6434 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6437 [alert setContext:@"source"];
6438 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6440 [alert setNumberOfRows:1];
6441 [alert addTextFieldWithValue:@"http://" label:@""];
6443 UITextInputTraits *traits = [[alert textField] textInputTraits];
6444 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6445 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6446 [traits setKeyboardType:UIKeyboardTypeURL];
6447 // XXX: UIReturnKeyDone
6448 [traits setReturnKeyType:UIReturnKeyNext];
6453 - (void) addButtonClicked {
6454 [self showAddSourcePrompt];
6457 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6458 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6459 initWithTitle:UCLocalize("ADD")
6460 style:UIBarButtonItemStylePlain
6462 action:@selector(addButtonClicked)
6463 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6465 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6466 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6467 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6469 action:@selector(editButtonClicked)
6470 ] autorelease] animated:animated];
6472 if (IsWildcat_ && !editing)
6473 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6474 initWithTitle:UCLocalize("SETTINGS")
6475 style:UIBarButtonItemStylePlain
6477 action:@selector(settingsButtonClicked)
6481 - (void) settingsButtonClicked {
6482 [delegate_ showSettings];
6485 - (void) editButtonClicked {
6486 [list_ setEditing:![list_ isEditing] animated:YES];
6488 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6494 /* Installed Controller {{{ */
6495 @interface InstalledController : FilteredPackageController {
6499 - (id) initWithDatabase:(Database *)database;
6501 - (void) updateRoleButton;
6502 - (void) queueStatusDidChange;
6506 @implementation InstalledController
6512 - (NSString *) title { return UCLocalize("INSTALLED"); }
6514 - (id) initWithDatabase:(Database *)database {
6515 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6516 [self updateRoleButton];
6517 [self queueStatusDidChange];
6522 - (void) queueButtonClicked {
6527 - (void) queueStatusDidChange {
6531 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6532 initWithTitle:UCLocalize("QUEUE")
6533 style:UIBarButtonItemStyleDone
6535 action:@selector(queueButtonClicked)
6538 [[self navigationItem] setLeftBarButtonItem:nil];
6544 - (void) reloadData {
6545 [packages_ reloadData];
6548 - (void) updateRoleButton {
6549 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6550 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6551 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6552 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6554 action:@selector(roleButtonClicked)
6558 - (void) roleButtonClicked {
6559 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6560 [packages_ reloadData];
6563 [self updateRoleButton];
6566 - (void) setDelegate:(id)delegate {
6567 [super setDelegate:delegate];
6568 [packages_ setDelegate:delegate];
6573 /* Section Controller {{{ */
6574 @interface CYSectionController : FilteredPackageController {
6577 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6581 @implementation CYSectionController
6587 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6591 title = UCLocalize("ALL_PACKAGES");
6592 } else if (![name isEqual:@""]) {
6593 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6595 title = UCLocalize("NO_SECTION");
6598 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6602 - (void) reloadData {
6603 [packages_ reloadData];
6606 - (void) setDelegate:(id)delegate {
6607 [super setDelegate:delegate];
6608 [packages_ setDelegate:delegate];
6614 /* Home Controller {{{ */
6615 @interface HomeController : CYBrowserController {
6619 @implementation HomeController
6621 + (BOOL)shouldHideNavigationBar {
6625 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6626 [super _setMoreHeaders:request];
6629 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6630 if (UniqueID_ != nil)
6631 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6633 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6636 - (void) aboutButtonClicked {
6637 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6639 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6640 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6641 [alert setCancelButtonIndex:0];
6644 @"Copyright (C) 2008-2010\n"
6645 "Jay Freeman (saurik)\n"
6646 "saurik@saurik.com\n"
6647 "http://www.saurik.com/"
6653 - (void) viewWillAppear:(BOOL)animated {
6654 [super viewWillAppear:animated];
6656 if ([[self class] shouldHideNavigationBar])
6657 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6660 - (void) viewWillDisappear:(BOOL)animated {
6661 [super viewWillDisappear:animated];
6663 if ([[self class] shouldHideNavigationBar])
6664 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6668 if ((self = [super init]) != nil) {
6669 [self loadURL:[NSURL URLWithString:CydiaURL(@"")]];
6671 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6672 initWithTitle:UCLocalize("ABOUT")
6673 style:UIBarButtonItemStylePlain
6675 action:@selector(aboutButtonClicked)
6682 /* Manage Controller {{{ */
6683 @interface ManageController : CYBrowserController {
6686 - (void) queueStatusDidChange;
6689 @implementation ManageController
6692 if ((self = [super init]) != nil) {
6693 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6695 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6697 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6698 initWithTitle:UCLocalize("SETTINGS")
6699 style:UIBarButtonItemStylePlain
6701 action:@selector(settingsButtonClicked)
6704 [self queueStatusDidChange];
6708 - (void) settingsButtonClicked {
6709 [delegate_ showSettings];
6713 - (void) queueButtonClicked {
6717 - (void) applyLoadingTitle {
6718 // No "Loading" title.
6721 - (void) applyRightButton {
6726 - (void) queueStatusDidChange {
6728 if (!IsWildcat_ && Queuing_) {
6729 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6730 initWithTitle:UCLocalize("QUEUE")
6731 style:UIBarButtonItemStyleDone
6733 action:@selector(queueButtonClicked)
6736 [[self navigationItem] setRightBarButtonItem:nil];
6741 - (bool) isLoading {
6748 /* Refresh Bar {{{ */
6749 @interface RefreshBar : UINavigationBar {
6750 UIProgressIndicator *indicator_;
6751 UITextLabel *prompt_;
6752 UIProgressBar *progress_;
6753 UINavigationButton *cancel_;
6758 @implementation RefreshBar
6761 [indicator_ release];
6763 [progress_ release];
6768 - (void) positionViews {
6769 CGRect frame = [cancel_ frame];
6770 frame.size = [cancel_ sizeThatFits:frame.size];
6771 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6772 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6773 [cancel_ setFrame:frame];
6775 CGSize prgsize = {75, 100};
6777 [self frame].size.width - prgsize.width - 10,
6778 ([self frame].size.height - prgsize.height) / 2
6780 [progress_ setFrame:prgrect];
6782 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6783 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6784 CGRect indrect = {{indoffset, indoffset}, indsize};
6785 [indicator_ setFrame:indrect];
6787 CGSize prmsize = {215, indsize.height + 4};
6789 indoffset * 2 + indsize.width,
6790 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6792 [prompt_ setFrame:prmrect];
6795 - (void)setFrame:(CGRect)frame {
6796 [super setFrame:frame];
6798 [self positionViews];
6801 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6802 if ((self = [super initWithFrame:frame])) {
6803 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6805 [self setBarStyle:UIBarStyleBlack];
6807 UIBarStyle barstyle([self _barStyle:NO]);
6808 bool ugly(barstyle == UIBarStyleDefault);
6810 UIProgressIndicatorStyle style = ugly ?
6811 UIProgressIndicatorStyleMediumBrown :
6812 UIProgressIndicatorStyleMediumWhite;
6814 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6815 [indicator_ setStyle:style];
6816 [indicator_ startAnimation];
6817 [self addSubview:indicator_];
6819 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6820 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6821 [prompt_ setBackgroundColor:[UIColor clearColor]];
6822 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6823 [self addSubview:prompt_];
6825 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6826 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6827 [progress_ setStyle:0];
6828 [self addSubview:progress_];
6830 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6831 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6832 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6833 [cancel_ setBarStyle:barstyle];
6835 [self positionViews];
6840 [cancel_ removeFromSuperview];
6844 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6845 [progress_ setProgress:0];
6846 [self addSubview:cancel_];
6850 [cancel_ removeFromSuperview];
6853 - (void) setPrompt:(NSString *)prompt {
6854 [prompt_ setText:prompt];
6857 - (void) setProgress:(float)progress {
6858 [progress_ setProgress:progress];
6864 @class CYNavigationController;
6866 /* Cydia Tab Bar Controller {{{ */
6867 @interface CYTabBarController : UITabBarController <
6870 _transient Database *database_;
6871 RefreshBar *refreshbar_;
6875 // XXX: ok, "updatedelegate_"?...
6876 _transient NSObject<CydiaDelegate> *updatedelegate_;
6881 - (void) dropBar:(BOOL)animated;
6882 - (void) beginUpdate;
6883 - (void) raiseBar:(BOOL)animated;
6888 @implementation CYTabBarController
6890 - (void) reloadData {
6891 size_t count([[self viewControllers] count]);
6892 for (size_t i(0); i != count; ++i) {
6893 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6898 - (id) initWithDatabase:(Database *)database {
6899 if ((self = [super init]) != nil) {
6900 database_ = database;
6902 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6903 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6905 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6909 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6910 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
6913 - (void) setUpdate:(NSDate *)date {
6917 - (void) beginUpdate {
6918 [refreshbar_ start];
6921 [updatedelegate_ retainNetworkActivityIndicator];
6925 detachNewThreadSelector:@selector(performUpdate)
6931 - (void) performUpdate { _pooled
6933 status.setDelegate(self);
6934 [database_ updateWithStatus:status];
6937 performSelectorOnMainThread:@selector(completeUpdate)
6943 - (void) stopUpdateWithSelector:(SEL)selector {
6945 [updatedelegate_ releaseNetworkActivityIndicator];
6947 [self raiseBar:YES];
6950 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6953 - (void) completeUpdate {
6956 [self stopUpdateWithSelector:@selector(reloadData)];
6959 - (void) cancelUpdate {
6960 [self stopUpdateWithSelector:@selector(updateData)];
6963 - (void) cancelPressed {
6964 [self cancelUpdate];
6971 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6972 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6975 - (void) startProgress {
6978 - (void) setProgressTitle:(NSString *)title {
6980 performSelectorOnMainThread:@selector(_setProgressTitle:)
6986 - (bool) isCancelling:(size_t)received {
6990 - (void) setProgressPercent:(float)percent {
6992 performSelectorOnMainThread:@selector(_setProgressPercent:)
6993 withObject:[NSNumber numberWithFloat:percent]
6998 - (void) addProgressOutput:(NSString *)output {
7000 performSelectorOnMainThread:@selector(_addProgressOutput:)
7006 - (void) _setProgressTitle:(NSString *)title {
7007 [refreshbar_ setPrompt:title];
7010 - (void) _setProgressPercent:(NSNumber *)percent {
7011 [refreshbar_ setProgress:[percent floatValue]];
7014 - (void) _addProgressOutput:(NSString *)output {
7017 - (void) setUpdateDelegate:(id)delegate {
7018 updatedelegate_ = delegate;
7021 - (CGFloat) statusBarHeight {
7022 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7023 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7025 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7029 - (UIView *) transitionView {
7030 if ([self respondsToSelector:@selector(_transitionView)])
7031 return [self _transitionView];
7033 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7036 - (void) dropBar:(BOOL)animated {
7041 UIView *transition([self transitionView]);
7042 [[self view] addSubview:refreshbar_];
7044 CGRect barframe([refreshbar_ frame]);
7046 if (false) // XXX: _UIApplicationLinkedOnOrAfter(4)
7047 barframe.origin.y = [self statusBarHeight];
7049 barframe.origin.y = 0;
7051 [refreshbar_ setFrame:barframe];
7054 [UIView beginAnimations:nil context:NULL];
7056 CGRect viewframe = [transition frame];
7057 viewframe.origin.y += barframe.size.height;
7058 viewframe.size.height -= barframe.size.height;
7059 [transition setFrame:viewframe];
7062 [UIView commitAnimations];
7064 // Ensure bar has the proper width for our view, it might have changed
7065 barframe.size.width = viewframe.size.width;
7066 [refreshbar_ setFrame:barframe];
7068 // XXX: fix Apple's layout bug
7069 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7072 - (void) raiseBar:(BOOL)animated {
7077 UIView *transition([self transitionView]);
7078 [refreshbar_ removeFromSuperview];
7080 CGRect barframe([refreshbar_ frame]);
7083 [UIView beginAnimations:nil context:NULL];
7085 CGRect viewframe = [transition frame];
7086 viewframe.origin.y -= barframe.size.height;
7087 viewframe.size.height += barframe.size.height;
7088 [transition setFrame:viewframe];
7091 [UIView commitAnimations];
7093 // XXX: fix Apple's layout bug
7094 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7098 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7099 // XXX: fix Apple's layout bug
7100 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7104 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7105 bool dropped(dropped_);
7110 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7115 // XXX: fix Apple's layout bug
7116 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7119 - (void) statusBarFrameChanged:(NSNotification *)notification {
7127 [refreshbar_ release];
7128 [[NSNotificationCenter defaultCenter] removeObserver:self];
7135 /* Cydia Navigation Controller {{{ */
7136 @interface CYNavigationController : UINavigationController {
7137 _transient Database *database_;
7138 _transient id<UINavigationControllerDelegate> delegate_;
7141 - (id) initWithDatabase:(Database *)database;
7142 - (void) reloadData;
7147 @implementation CYNavigationController
7149 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7150 // Inherit autorotation settings for modal parents.
7151 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
7152 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
7153 } else if ([self parentViewController]) {
7154 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
7156 return [super shouldAutorotateToInterfaceOrientation:orientation];
7164 - (void) reloadData {
7165 size_t count([[self viewControllers] count]);
7166 for (size_t i(0); i != count; ++i) {
7167 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
7172 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
7173 delegate_ = delegate;
7176 - (id) initWithDatabase:(Database *)database {
7177 if ((self = [super init]) != nil) {
7178 database_ = database;
7184 /* Cydia:// Protocol {{{ */
7185 @interface CydiaURLProtocol : NSURLProtocol {
7190 @implementation CydiaURLProtocol
7192 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7193 NSURL *url([request URL]);
7196 NSString *scheme([[url scheme] lowercaseString]);
7197 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
7202 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7206 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7207 id<NSURLProtocolClient> client([self client]);
7209 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7211 NSData *data(UIImagePNGRepresentation(icon));
7213 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7214 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7215 [client URLProtocol:self didLoadData:data];
7216 [client URLProtocolDidFinishLoading:self];
7220 - (void) startLoading {
7221 id<NSURLProtocolClient> client([self client]);
7222 NSURLRequest *request([self request]);
7224 NSURL *url([request URL]);
7225 NSString *href([url absoluteString]);
7227 NSString *path([href substringFromIndex:8]);
7228 NSRange slash([path rangeOfString:@"/"]);
7231 if (slash.location == NSNotFound) {
7235 command = [path substringToIndex:slash.location];
7236 path = [path substringFromIndex:(slash.location + 1)];
7239 Database *database([Database sharedInstance]);
7241 if ([command isEqualToString:@"package-icon"]) {
7244 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7245 Package *package([database packageWithName:path]);
7248 UIImage *icon([package icon]);
7249 [self _returnPNGWithImage:icon forRequest:request];
7250 } else if ([command isEqualToString:@"source-icon"]) {
7253 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7254 NSString *source(Simplify(path));
7255 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7257 icon = [UIImage applicationImageNamed:@"unknown.png"];
7258 [self _returnPNGWithImage:icon forRequest:request];
7259 } else if ([command isEqualToString:@"uikit-image"]) {
7262 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7263 UIImage *icon(_UIImageWithName(path));
7264 [self _returnPNGWithImage:icon forRequest:request];
7265 } else if ([command isEqualToString:@"section-icon"]) {
7268 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7269 NSString *section(Simplify(path));
7270 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7272 icon = [UIImage applicationImageNamed:@"unknown.png"];
7273 [self _returnPNGWithImage:icon forRequest:request];
7275 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7279 - (void) stopLoading {
7285 /* Section Controller {{{ */
7286 @interface SectionController : FilteredPackageController {
7289 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7293 @implementation SectionController
7299 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7303 title = UCLocalize("ALL_PACKAGES");
7304 } else if (![name isEqual:@""]) {
7305 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7307 title = UCLocalize("NO_SECTION");
7310 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7314 - (void) reloadData {
7315 [packages_ reloadData];
7318 - (void) setDelegate:(id)delegate {
7319 [super setDelegate:delegate];
7320 [packages_ setDelegate:delegate];
7325 /* Sections Controller {{{ */
7326 @interface SectionsController : CYViewController <
7327 UITableViewDataSource,
7330 _transient Database *database_;
7331 NSMutableArray *sections_;
7332 NSMutableArray *filtered_;
7338 - (id) initWithDatabase:(Database *)database;
7339 - (void) reloadData;
7342 - (void) editButtonClicked;
7346 @implementation SectionsController
7349 [list_ setDataSource:nil];
7350 [list_ setDelegate:nil];
7352 [sections_ release];
7353 [filtered_ release];
7355 [accessory_ release];
7359 - (void) setEditing:(BOOL)editing {
7360 if ((editing_ = editing))
7363 [delegate_ updateData];
7365 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7366 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
7367 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
7370 - (void) viewDidAppear:(BOOL)animated {
7371 [super viewDidAppear:animated];
7372 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7375 - (void) viewWillDisappear:(BOOL)animated {
7376 [super viewWillDisappear:animated];
7377 if (editing_) [self setEditing:NO];
7380 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7381 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7385 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7386 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7389 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7393 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7394 static NSString *reuseIdentifier = @"SectionCell";
7396 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7398 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7400 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7405 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7409 Section *section = [self sectionAtIndexPath:indexPath];
7411 SectionController *controller = [[[SectionController alloc]
7412 initWithDatabase:database_
7413 section:[section name]
7415 [controller setDelegate:delegate_];
7417 [[self navigationController] pushViewController:controller animated:YES];
7420 - (id) initWithDatabase:(Database *)database {
7421 if ((self = [super init]) != nil) {
7422 database_ = database;
7424 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7426 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7427 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7429 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7430 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7431 [list_ setRowHeight:45.0f];
7432 [[self view] addSubview:list_];
7434 [list_ setDataSource:self];
7435 [list_ setDelegate:self];
7441 - (void) reloadData {
7442 NSArray *packages = [database_ packages];
7444 [sections_ removeAllObjects];
7445 [filtered_ removeAllObjects];
7447 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7450 for (Package *package in packages) {
7451 NSString *name([package section]);
7452 NSString *key(name == nil ? @"" : name);
7456 _profile(SectionsView$reloadData$Section)
7457 section = [sections objectForKey:key];
7458 if (section == nil) {
7459 _profile(SectionsView$reloadData$Section$Allocate)
7460 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
7461 [sections setObject:section forKey:key];
7466 [section addToCount];
7468 _profile(SectionsView$reloadData$Filter)
7469 if (![package valid] || ![package visible])
7477 [sections_ addObjectsFromArray:[sections allValues]];
7479 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7481 for (Section *section in sections_) {
7482 size_t count([section row]);
7486 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7487 [section setCount:count];
7488 [filtered_ addObject:section];
7491 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7492 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
7493 style:UIBarButtonItemStylePlain
7495 action:@selector(editButtonClicked)
7496 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7502 - (void) resetView {
7504 [self editButtonClicked];
7507 - (void)editButtonClicked {
7508 [self setEditing:!editing_];
7511 - (UIView *) accessoryView {
7518 /* Changes Controller {{{ */
7519 @interface ChangesController : CYViewController <
7520 UITableViewDataSource,
7523 _transient Database *database_;
7525 CFMutableArrayRef packages_;
7526 NSMutableArray *sections_;
7529 BOOL hasSentFirstLoad_;
7532 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
7533 - (void) reloadData;
7537 @implementation ChangesController
7540 [list_ setDelegate:nil];
7541 [list_ setDataSource:nil];
7543 CFRelease(packages_);
7545 [sections_ release];
7550 - (void) viewDidAppear:(BOOL)animated {
7551 [super viewDidAppear:animated];
7552 if (!hasSentFirstLoad_) {
7553 hasSentFirstLoad_ = YES;
7554 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7556 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7560 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7561 NSInteger count([sections_ count]);
7562 return count == 0 ? 1 : count;
7565 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7566 if ([sections_ count] == 0)
7568 return [[sections_ objectAtIndex:section] name];
7571 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7572 if ([sections_ count] == 0)
7574 return [[sections_ objectAtIndex:section] count];
7577 - (Package *) packageAtIndex:(NSUInteger)index {
7578 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7581 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7582 @synchronized (database_) {
7583 if ([database_ era] != era_)
7586 NSUInteger sectionIndex([path section]);
7587 if (sectionIndex >= [sections_ count])
7589 Section *section([sections_ objectAtIndex:sectionIndex]);
7590 NSInteger row([path row]);
7591 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7594 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7595 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7597 cell = [[[PackageCell alloc] init] autorelease];
7598 [cell setPackage:[self packageAtIndexPath:path]];
7602 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7603 Package *package([self packageAtIndexPath:path]);
7604 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_] autorelease]);
7605 [view setDelegate:delegate_];
7606 [view setPackage:package];
7607 [[self navigationController] pushViewController:view animated:YES];
7611 - (void) refreshButtonClicked {
7612 [delegate_ beginUpdate];
7613 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7616 - (void) upgradeButtonClicked {
7617 [delegate_ distUpgrade];
7620 - (NSString *) title { return UCLocalize("CHANGES"); }
7622 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7623 if ((self = [super init]) != nil) {
7624 database_ = database;
7625 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7627 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7629 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7631 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7632 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7633 [list_ setRowHeight:73.0f];
7634 [[self view] addSubview:list_];
7636 [list_ setDataSource:self];
7637 [list_ setDelegate:self];
7639 delegate_ = delegate;
7643 - (void) _reloadPackages:(NSArray *)packages {
7644 CFRelease(packages_);
7645 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7648 _profile(ChangesController$_reloadPackages$Filter)
7649 for (Package *package in packages)
7650 if ([package upgradableAndEssential:YES] || [package visible])
7651 CFArrayAppendValue(packages_, package);
7654 _profile(ChangesController$_reloadPackages$radixSort)
7655 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7660 - (void) reloadData {
7661 @synchronized (database_) {
7662 era_ = [database_ era];
7663 NSArray *packages = [database_ packages];
7665 [sections_ removeAllObjects];
7668 UIProgressHUD *hud([delegate_ addProgressHUD]);
7669 [hud setText:UCLocalize("LOADING")];
7670 //NSLog(@"HUD:%@::%@", delegate_, hud);
7671 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7672 [delegate_ removeProgressHUD:hud];
7674 [self _reloadPackages:packages];
7677 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7678 Section *ignored = nil;
7679 Section *section = nil;
7683 bool unseens = false;
7685 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7687 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7688 Package *package = [self packageAtIndex:offset];
7690 BOOL uae = [package upgradableAndEssential:YES];
7694 time_t seen([package seen]);
7696 if (section == nil || last != seen) {
7700 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7703 _profile(ChangesController$reloadData$Allocate)
7704 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7705 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7706 [sections_ addObject:section];
7710 [section addToCount];
7711 } else if ([package ignored]) {
7712 if (ignored == nil) {
7713 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7715 [ignored addToCount];
7718 [upgradable addToCount];
7723 CFRelease(formatter);
7726 Section *last = [sections_ lastObject];
7727 size_t count = [last count];
7728 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7729 [sections_ removeLastObject];
7732 if ([ignored count] != 0)
7733 [sections_ insertObject:ignored atIndex:0];
7735 [sections_ insertObject:upgradable atIndex:0];
7740 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7741 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7742 style:UIBarButtonItemStylePlain
7744 action:@selector(upgradeButtonClicked)
7747 if (![delegate_ updating])
7748 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7749 initWithTitle:UCLocalize("REFRESH")
7750 style:UIBarButtonItemStylePlain
7752 action:@selector(refreshButtonClicked)
7760 /* Search Controller {{{ */
7761 @interface SearchController : FilteredPackageController <
7764 UISearchBar *search_;
7767 - (id) initWithDatabase:(Database *)database;
7768 - (void) setSearchTerm:(NSString *)term;
7769 - (void) reloadData;
7773 @implementation SearchController
7780 - (void) setSearchTerm:(NSString *)searchTerm {
7781 [search_ setText:searchTerm];
7784 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7785 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7786 [search_ resignFirstResponder];
7790 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7791 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7795 - (id) initWithDatabase:(Database *)database {
7796 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7799 - (void)viewDidAppear:(BOOL)animated {
7800 [super viewDidAppear:animated];
7802 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7803 [search_ layoutSubviews];
7804 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7806 UITextField *textField;
7807 if ([search_ respondsToSelector:@selector(searchField)])
7808 textField = [search_ searchField];
7810 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7812 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7813 [search_ setDelegate:self];
7814 [textField setEnablesReturnKeyAutomatically:NO];
7815 [[self navigationItem] setTitleView:textField];
7819 - (void) _reloadData {
7822 - (void) reloadData {
7823 _profile(SearchController$reloadData)
7824 [packages_ reloadData];
7827 [packages_ resetCursor];
7830 - (void) didSelectPackage:(Package *)package {
7831 [search_ resignFirstResponder];
7832 [super didSelectPackage:package];
7837 /* Settings Controller {{{ */
7838 @interface PackageSettingsController : CYViewController <
7839 UITableViewDataSource,
7842 _transient Database *database_;
7845 UITableView *table_;
7846 UISwitch *subscribedSwitch_;
7847 UISwitch *ignoredSwitch_;
7848 UITableViewCell *subscribedCell_;
7849 UITableViewCell *ignoredCell_;
7852 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7856 @implementation PackageSettingsController
7860 if (package_ != nil)
7863 [subscribedSwitch_ release];
7864 [ignoredSwitch_ release];
7865 [subscribedCell_ release];
7866 [ignoredCell_ release];
7871 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7872 if (package_ == nil)
7878 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7879 if (package_ == nil)
7885 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7886 return UCLocalize("CHANGE_PACKAGE_SETTINGS");
7889 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7890 return UCLocalize("SHOW_ALL_CHANGES_EX");
7893 - (void) onSubscribed:(id)control {
7894 bool value([control isOn]);
7895 if (package_ == nil)
7897 if ([package_ setSubscribed:value])
7898 [delegate_ updateData];
7901 - (void) onIgnored:(id)control {
7902 // TODO: set Held state - possibly call out to dpkg, etc.
7905 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7906 if (package_ == nil)
7909 switch ([indexPath row]) {
7910 case 0: return subscribedCell_;
7911 case 1: return ignoredCell_;
7919 - (NSString *) title { return UCLocalize("SETTINGS"); }
7921 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7922 if ((self = [super init])) {
7923 database_ = database;
7924 name_ = [package retain];
7926 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7928 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7929 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7930 [[self view] addSubview:table_];
7932 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7933 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7934 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7936 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7937 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7938 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7939 // Disable this switch, since it only reflects (not modifies) the ignored state.
7940 [ignoredSwitch_ setUserInteractionEnabled:NO];
7942 subscribedCell_ = [[UITableViewCell alloc] init];
7943 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7944 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7945 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7947 ignoredCell_ = [[UITableViewCell alloc] init];
7948 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7949 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7950 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7951 // FIXME: Ignored state is not saved.
7952 [ignoredCell_ setUserInteractionEnabled:NO];
7954 [table_ setDataSource:self];
7955 [table_ setDelegate:self];
7960 - (void) reloadData {
7961 if (package_ != nil)
7962 [package_ autorelease];
7963 package_ = [database_ packageWithName:name_];
7964 if (package_ != nil) {
7966 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7967 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7970 [table_ reloadData];
7975 /* Signature Controller {{{ */
7976 @interface SignatureController : CYBrowserController {
7977 _transient Database *database_;
7981 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7985 @implementation SignatureController
7992 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7994 [super webView:view didClearWindowObject:window forFrame:frame];
7997 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7998 if ((self = [super init]) != nil) {
7999 database_ = database;
8000 package_ = [package retain];
8005 - (void) reloadData {
8006 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
8012 /* Role Controller {{{ */
8013 @interface CYSettingsController : CYViewController <
8014 UITableViewDataSource,
8017 _transient Database *database_;
8018 // XXX: ok, "roledelegate_"?...
8019 _transient id roledelegate_;
8020 UITableView *table_;
8021 UISegmentedControl *segment_;
8025 - (void) showDoneButton;
8026 - (void) resizeSegmentedControl;
8030 @implementation CYSettingsController
8034 [container_ release];
8039 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8040 if ((self = [super init])) {
8041 database_ = database;
8042 roledelegate_ = delegate;
8044 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8046 NSArray *items = [NSArray arrayWithObjects:
8048 UCLocalize("HACKER"),
8049 UCLocalize("DEVELOPER"),
8051 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8052 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8053 [container_ addSubview:segment_];
8056 if ([Role_ isEqualToString:@"User"]) index = 0;
8057 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8058 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8060 [segment_ setSelectedSegmentIndex:index];
8061 [self showDoneButton];
8064 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8065 [self resizeSegmentedControl];
8067 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8068 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8069 [table_ setDelegate:self];
8070 [table_ setDataSource:self];
8071 [[self view] addSubview:table_];
8072 [table_ reloadData];
8076 - (void) resizeSegmentedControl {
8077 CGFloat width = [[self view] frame].size.width;
8078 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8081 - (void) viewWillAppear:(BOOL)animated {
8082 [super viewWillAppear:animated];
8084 [self resizeSegmentedControl];
8087 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8088 [self resizeSegmentedControl];
8091 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8092 [self resizeSegmentedControl];
8096 NSString *role(nil);
8098 switch ([segment_ selectedSegmentIndex]) {
8099 case 0: role = @"User"; break;
8100 case 1: role = @"Hacker"; break;
8101 case 2: role = @"Developer"; break;
8106 if (![role isEqualToString:Role_]) {
8107 bool rolling(Role_ == nil);
8110 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8114 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8118 [roledelegate_ loadData];
8120 [roledelegate_ updateData];
8124 - (void) segmentChanged:(UISegmentedControl *)control {
8125 [self showDoneButton];
8128 - (void) saveAndClose {
8131 [[self navigationItem] setRightBarButtonItem:nil];
8132 [[self navigationController] dismissModalViewControllerAnimated:YES];
8135 - (void) doneButtonClicked {
8136 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8137 [spinner startAnimating];
8138 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8139 [[self navigationItem] setRightBarButtonItem:spinItem];
8141 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8144 - (void) showDoneButton {
8145 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8146 initWithTitle:UCLocalize("DONE")
8147 style:UIBarButtonItemStyleDone
8149 action:@selector(doneButtonClicked)
8150 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8153 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8154 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8158 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8162 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8163 return nil; // This method is required by the protocol.
8166 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8168 return UCLocalize("ROLE_EX");
8170 return [NSString stringWithFormat:
8171 @"%@: %@\n%@: %@\n%@: %@",
8172 UCLocalize("USER"), UCLocalize("USER_EX"),
8173 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8174 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8179 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8180 return section == 3 ? 44.0f : 0;
8183 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8184 return section == 3 ? container_ : nil;
8189 /* Stash Controller {{{ */
8190 @interface CYStashController : CYViewController {
8191 // XXX: just delete these things
8192 _transient UIActivityIndicatorView *spinner_;
8193 _transient UILabel *status_;
8194 _transient UILabel *caption_;
8198 @implementation CYStashController
8200 if ((self = [super init])) {
8201 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8203 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8204 CGRect spinrect = [spinner_ frame];
8205 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8206 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8207 [spinner_ setFrame:spinrect];
8208 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8209 [[self view] addSubview:spinner_];
8210 [spinner_ startAnimating];
8213 captrect.size.width = [[self view] frame].size.width;
8214 captrect.size.height = 40.0f;
8215 captrect.origin.x = 0;
8216 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8217 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8218 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8219 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8220 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8221 [caption_ setTextColor:[UIColor whiteColor]];
8222 [caption_ setBackgroundColor:[UIColor clearColor]];
8223 [caption_ setShadowColor:[UIColor blackColor]];
8224 [caption_ setTextAlignment:UITextAlignmentCenter];
8225 [[self view] addSubview:caption_];
8228 statusrect.size.width = [[self view] frame].size.width;
8229 statusrect.size.height = 30.0f;
8230 statusrect.origin.x = 0;
8231 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8232 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8233 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8234 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8235 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8236 [status_ setTextColor:[UIColor whiteColor]];
8237 [status_ setBackgroundColor:[UIColor clearColor]];
8238 [status_ setShadowColor:[UIColor blackColor]];
8239 [status_ setTextAlignment:UITextAlignmentCenter];
8240 [[self view] addSubview:status_];
8244 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
8245 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
8250 @interface Cydia : UIApplication <
8251 ConfirmationControllerDelegate,
8252 ProgressControllerDelegate,
8254 UINavigationControllerDelegate,
8255 UITabBarControllerDelegate
8257 // XXX: evaluate all fields for _transient
8260 CYTabBarController *tabbar_;
8262 NSMutableArray *essential_;
8263 NSMutableArray *broken_;
8265 Database *database_;
8272 CYStashController *stash_;
8277 - (void) setPage:(CYViewController *)page;
8282 @implementation Cydia
8284 - (void) beginUpdate {
8285 [tabbar_ beginUpdate];
8289 return [tabbar_ updating];
8293 if ([broken_ count] != 0) {
8294 int count = [broken_ count];
8296 UIAlertView *alert = [[[UIAlertView alloc]
8297 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8298 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8300 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8301 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8304 [alert setContext:@"fixhalf"];
8306 } else if (!Ignored_ && [essential_ count] != 0) {
8307 int count = [essential_ count];
8309 UIAlertView *alert = [[[UIAlertView alloc]
8310 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8311 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8313 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8314 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8317 [alert setContext:@"upgrade"];
8322 - (void) _saveConfig {
8328 NSString *error(nil);
8330 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8332 NSError *error(nil);
8333 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8334 NSLog(@"failure to save metadata data: %@", error);
8339 NSLog(@"failure to serialize metadata: %@", error);
8344 // Navigation controller for the queuing badge.
8345 - (CYNavigationController *) queueNavigationController {
8346 NSArray *controllers = [tabbar_ viewControllers];
8347 return [controllers objectAtIndex:3];
8350 - (void) _updateData {
8353 [tabbar_ reloadData];
8355 CYNavigationController *navigation = [self queueNavigationController];
8357 id queuedelegate = nil;
8358 if ([[navigation viewControllers] count] > 0)
8359 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8361 [queuedelegate queueStatusDidChange];
8362 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8365 - (void) _refreshIfPossible {
8366 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8368 bool recently = false;
8369 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8370 if (update != nil) {
8371 NSTimeInterval interval([update timeIntervalSinceNow]);
8372 if (interval <= 0 && interval > -(15*60))
8376 // Don't automatic refresh if:
8377 // - We already refreshed recently.
8378 // - We already auto-refreshed this launch.
8379 // - Auto-refresh is disabled.
8380 if (recently || loaded_ || ManualRefresh) {
8381 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8383 // If we are cancelling due to ManualRefresh or a recent refresh
8384 // we need to make sure it knows it's already loaded.
8388 // We are going to load, so remember that.
8392 SCNetworkReachabilityFlags flags; {
8393 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8394 SCNetworkReachabilityGetFlags(reachability, &flags);
8395 CFRelease(reachability);
8398 // XXX: this elaborate mess is what Apple is using to determine this? :(
8399 // XXX: do we care if the user has to intervene? maybe that's ok?
8401 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8402 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8403 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8404 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8405 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8406 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8410 // If we can reach the server, auto-refresh!
8412 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8417 - (void) refreshIfPossible {
8418 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8421 - (void) _reloadData {
8422 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8423 [hud setText:UCLocalize("RELOADING_DATA")];
8425 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8428 [self removeProgressHUD:hud];
8432 [essential_ removeAllObjects];
8433 [broken_ removeAllObjects];
8435 NSArray *packages([database_ packages]);
8436 for (Package *package in packages) {
8438 [broken_ addObject:package];
8439 if ([package upgradableAndEssential:NO]) {
8440 if ([package essential])
8441 [essential_ addObject:package];
8446 NSLog(@"changes:#%u", changes);
8448 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8451 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8452 [changesItem setBadgeValue:badge];
8453 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8454 [self setApplicationIconBadgeNumber:changes];
8457 [changesItem setBadgeValue:nil];
8458 [changesItem setAnimatedBadge:NO];
8459 [self setApplicationIconBadgeNumber:0];
8464 [self refreshIfPossible];
8467 - (void) updateData {
8476 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8477 _assert(file != NULL);
8479 for (NSString *key in [Sources_ allKeys]) {
8480 NSDictionary *source([Sources_ objectForKey:key]);
8482 fprintf(file, "%s %s %s\n",
8483 [[source objectForKey:@"Type"] UTF8String],
8484 [[source objectForKey:@"URI"] UTF8String],
8485 [[source objectForKey:@"Distribution"] UTF8String]
8493 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8494 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8496 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8497 [tabbar_ presentModalViewController:navigation animated:YES];
8500 detachNewThreadSelector:@selector(update_)
8503 title:UCLocalize("UPDATING_SOURCES")
8507 - (void) reloadData {
8508 @synchronized (self) {
8514 pkgProblemResolver *resolver = [database_ resolver];
8516 resolver->InstallProtect();
8517 if (!resolver->Resolve(true))
8522 if (![database_ prepare])
8525 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8526 [page setDelegate:self];
8527 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8528 [confirm_ setDelegate:self];
8531 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8532 [tabbar_ presentModalViewController:confirm_ animated:YES];
8538 @synchronized (self) {
8543 - (void) clearPackage:(Package *)package {
8544 @synchronized (self) {
8551 - (void) installPackages:(NSArray *)packages {
8552 @synchronized (self) {
8553 for (Package *package in packages)
8560 - (void) installPackage:(Package *)package {
8561 @synchronized (self) {
8568 - (void) removePackage:(Package *)package {
8569 @synchronized (self) {
8576 - (void) distUpgrade {
8577 @synchronized (self) {
8578 if (![database_ upgrade])
8585 @synchronized (self) {
8590 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8593 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8595 if (navigation != nil) {
8596 [navigation pushViewController:progress animated:YES];
8598 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8600 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8601 [tabbar_ presentModalViewController:navigation animated:YES];
8605 detachNewThreadSelector:@selector(perform)
8608 title:UCLocalize("RUNNING")
8614 - (void) progressControllerIsComplete:(ProgressController *)progress {
8619 - (void) setPage:(CYViewController *)page {
8620 [page setDelegate:self];
8622 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8623 [navController setViewControllers:[NSArray arrayWithObject:page]];
8624 for (CYNavigationController *page in [tabbar_ viewControllers])
8625 if (page != navController)
8626 [page setViewControllers:nil];
8629 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8630 CYNavigationController *controller = (CYNavigationController *) viewController;
8632 if ([[controller viewControllers] count] == 0) {
8633 int index = [tabbar_ selectedIndex];
8634 CYViewController *root = nil;
8637 root = [[[HomeController alloc] init] autorelease];
8638 else if (index == 1)
8639 root = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
8640 else if (index == 2)
8641 root = [[[ChangesController alloc] initWithDatabase:database_ delegate:self] autorelease];
8645 root = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8646 else if (index == 4)
8647 root = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8648 else if (index == 5)
8649 root = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8652 root = [[[ManageController alloc] init] autorelease];
8653 else if (index == 4)
8654 root = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8657 [root setDelegate:self];
8660 [controller setViewControllers:[NSArray arrayWithObject:root]];
8664 - (void) showSettings {
8665 CYSettingsController *role = [[[CYSettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8666 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8668 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8669 [tabbar_ presentModalViewController:nav animated:YES];
8672 - (void) retainNetworkActivityIndicator {
8673 if (activity_++ == 0)
8674 [self setNetworkActivityIndicatorVisible:YES];
8677 - (void) releaseNetworkActivityIndicator {
8678 if (--activity_ == 0)
8679 [self setNetworkActivityIndicatorVisible:NO];
8682 - (void) setPackageController:(CYPackageController *)view {
8684 [view setPackage:nil];
8688 - (void) cancelAndClear:(bool)clear {
8689 @synchronized (self) {
8701 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8702 NSString *context([alert context]);
8704 if ([context isEqualToString:@"fixhalf"]) {
8705 if (button == [alert firstOtherButtonIndex]) {
8706 @synchronized (self) {
8707 for (Package *broken in broken_) {
8710 NSString *id = [broken id];
8711 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8712 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8713 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8714 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8720 } else if (button == [alert cancelButtonIndex]) {
8721 [broken_ removeAllObjects];
8725 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8726 } else if ([context isEqualToString:@"upgrade"]) {
8727 if (button == [alert firstOtherButtonIndex]) {
8728 @synchronized (self) {
8729 for (Package *essential in essential_)
8730 [essential install];
8735 } else if (button == [alert firstOtherButtonIndex] + 1) {
8737 } else if (button == [alert cancelButtonIndex]) {
8741 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8745 - (void) system:(NSString *)command { _pooled
8747 system([command UTF8String]);
8751 - (void) applicationWillSuspend {
8753 [super applicationWillSuspend];
8756 - (BOOL) isSafeToSuspend {
8757 // Use external process status API internally.
8758 // This is probably a really bad idea.
8759 // XXX: what is the point of this? does this solve anything at all?
8760 uint64_t status = 0;
8762 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8763 notify_get_state(notify_token, &status);
8764 notify_cancel(notify_token);
8767 return locked_ == 0 && status == 0;
8770 - (void) applicationSuspend:(__GSEvent *)event {
8771 if ([self isSafeToSuspend])
8772 [super applicationSuspend:event];
8775 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8776 if ([self isSafeToSuspend])
8777 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8780 - (void) _setSuspended:(BOOL)value {
8781 if ([self isSafeToSuspend])
8782 [super _setSuspended:value];
8785 - (UIProgressHUD *) addProgressHUD {
8786 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8787 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8789 [window_ setUserInteractionEnabled:NO];
8792 UIViewController *target = tabbar_;
8793 while ([target modalViewController] != nil) target = [target modalViewController];
8794 [[target view] addSubview:hud];
8800 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8802 [hud removeFromSuperview];
8803 [window_ setUserInteractionEnabled:YES];
8807 - (CYViewController *) pageForPackage:(NSString *)name {
8808 if (Package *package = [database_ packageWithName:name]) {
8809 CYPackageController *view = [[[CYPackageController alloc] initWithDatabase:database_] autorelease];
8810 [view setPackage:package];
8813 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8814 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8815 CYBrowserController *browser = [[[CYBrowserController alloc] init] autorelease];
8816 [browser loadURL:url];
8821 - (CYViewController *) pageForURL:(NSURL *)url {
8822 NSString *scheme([[url scheme] lowercaseString]);
8823 if ([[url absoluteString] length] <= [scheme length] + 3)
8825 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
8826 NSArray *components([path pathComponents]);
8828 if ([scheme isEqualToString:@"apptapp"] && [components count] && [[components objectAtIndex:0] isEqualToString:@"package"])
8829 return [self pageForPackage:[components objectAtIndex:1]];
8831 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
8834 NSString *base([components objectAtIndex:0]);
8836 if ([components count] == 1) {
8837 if ([base isEqualToString:@"storage"]) {
8838 CYBrowserController *browser = [[[CYBrowserController alloc] init] autorelease];
8839 [browser loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]]];
8843 if ([base isEqualToString:@"sources"]) {
8844 SourcesController *source = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8848 if ([base isEqualToString:@"home"]) {
8849 HomeController *home = [[[HomeController alloc] init] autorelease];
8853 if ([base isEqualToString:@"sections"]) {
8854 SectionsController *sections = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
8858 if ([base isEqualToString:@"search"]) {
8859 SearchController *search = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8863 if ([base isEqualToString:@"changes"]) {
8864 ChangesController *changes = [[[ChangesController alloc] initWithDatabase:database_ delegate:self] autorelease];
8868 if ([base isEqualToString:@"installed"]) {
8869 InstalledController *installed = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8872 } else if ([components count] == 2) {
8873 NSString *argument = [components objectAtIndex:1];
8875 if ([base isEqualToString:@"package"]) {
8876 CYViewController *package = [self pageForPackage:argument];
8880 if ([base isEqualToString:@"search"]) {
8881 SearchController *search = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8882 [search setSearchTerm:argument];
8886 if ([base isEqualToString:@"sections"]) {
8887 if ([argument isEqualToString:@"all"])
8889 SectionController *section = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
8890 [section setDelegate:self];
8894 if ([base isEqualToString:@"sources"]) {
8895 if ([argument isEqualToString:@"add"]) {
8896 SourcesController *source = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8897 [source showAddSourcePrompt];
8900 // XXX: Create page of the source specfified.
8904 if ([base isEqualToString:@"url"]) {
8905 CYBrowserController *browser = [[[CYBrowserController alloc] init] autorelease];
8906 [browser loadURL:[NSURL URLWithString:argument]];
8910 if ([base isEqualToString:@"launch"]) {
8911 [self launchApplicationWithIdentifier:argument suspended:NO];
8913 } else if ([components count] == 3) {
8914 NSString *arg1 = [components objectAtIndex:1];
8915 NSString *arg2 = [components objectAtIndex:2];
8917 if ([base isEqualToString:@"package"]) {
8918 if ([arg2 isEqualToString:@"settings"]) {
8919 return [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
8920 } else if ([arg2 isEqualToString:@"signature"]) {
8921 return [[[SignatureController alloc] initWithDatabase:database_ package:arg1] autorelease];
8922 } else if ([arg2 isEqualToString:@"files"]) {
8923 if (Package *package = [database_ packageWithName:arg1]) {
8924 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8925 [files setPackage:package];
8935 - (BOOL) openCydiaURL:(NSURL *)url {
8936 CYViewController *page([self pageForURL:url]);
8939 [self setPage:page];
8944 - (void) applicationOpenURL:(NSURL *)url {
8945 [super applicationOpenURL:url];
8947 if (!loaded_) starturl_ = [url retain];
8948 else [self openCydiaURL:url];
8951 - (void) applicationWillResignActive:(UIApplication *)application {
8952 // Stop refreshing if you get a phone call or lock the device.
8953 if ([tabbar_ updating])
8954 [tabbar_ cancelUpdate];
8956 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8957 [super applicationWillResignActive:application];
8960 - (void) addStashController {
8962 stash_ = [[CYStashController alloc] init];
8963 [window_ addSubview:[stash_ view]];
8966 - (void) removeStashController {
8967 [[stash_ view] removeFromSuperview];
8973 [self setIdleTimerDisabled:YES];
8975 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8976 [self setStatusBarShowsProgress:YES];
8977 UpdateExternalStatus(1);
8979 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8981 UpdateExternalStatus(0);
8982 [self setStatusBarShowsProgress:NO];
8984 [self removeStashController];
8986 if (ExecFork() == 0) {
8987 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8988 perror("launchctl stop");
8992 - (void) setupViewControllers {
8993 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8994 [tabbar_ setDelegate:self];
8996 NSMutableArray *items([NSMutableArray arrayWithObjects:
8997 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
8998 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
8999 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9000 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9004 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9005 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9007 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9010 NSMutableArray *controllers([NSMutableArray array]);
9011 for (UITabBarItem *item in items) {
9012 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9013 [controller setTabBarItem:item];
9014 [controllers addObject:controller];
9016 [tabbar_ setViewControllers:controllers];
9018 [tabbar_ setUpdateDelegate:self];
9019 [window_ addSubview:[tabbar_ view]];
9022 - (void)showEmulatedLoadingControllerInView:(UIView *)view {
9023 static CYEmulatedLoadingController *fake = [[CYEmulatedLoadingController alloc] init];
9025 [view addSubview:[fake view]];
9027 [[fake view] removeFromSuperview];
9031 - (void) applicationDidFinishLaunching:(id)unused {
9035 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9036 [self setApplicationSupportsShakeToEdit:NO];
9038 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9039 initWithMemoryCapacity:524288
9040 diskCapacity:10485760
9041 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9044 [CYBrowserController _initialize];
9046 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9048 Font12_ = [[UIFont systemFontOfSize:12] retain];
9049 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9050 Font14_ = [[UIFont systemFontOfSize:14] retain];
9051 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9052 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9054 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9055 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9057 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9058 [window_ orderFront:self];
9059 [window_ makeKey:self];
9060 [window_ setHidden:NO];
9063 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9064 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9065 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9066 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9067 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9068 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9069 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9070 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9071 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9074 [self addStashController];
9075 // XXX: this would be much cleaner as a yieldToSelector:
9076 // that way the removeStashController could happen right here inline
9077 // we also could no longer require the useless stash_ field anymore
9078 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9082 database_ = [Database sharedInstance];
9084 [window_ setUserInteractionEnabled:NO];
9085 [self showEmulatedLoadingControllerInView:window_];
9087 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9094 [self showSettings];
9101 [self setupViewControllers];
9102 [self showEmulatedLoadingControllerInView:nil];
9103 [window_ setUserInteractionEnabled:YES];
9105 // Show the home page.
9106 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:0];
9107 [navigation setViewControllers:[NSArray arrayWithObject:[[[HomeController alloc] init] autorelease]]];
9109 // (Try to) show the startup URL.
9110 if (starturl_ != nil) {
9111 [self openCydiaURL:starturl_];
9112 [starturl_ release];
9117 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9118 if (item != nil && IsWildcat_) {
9119 [sheet showFromBarButtonItem:item animated:YES];
9121 [sheet showInView:window_];
9128 id Alloc_(id self, SEL selector) {
9129 id object = alloc_(self, selector);
9130 lprintf("[%s]A-%p\n", self->isa->name, object);
9135 id Dealloc_(id self, SEL selector) {
9136 id object = dealloc_(self, selector);
9137 lprintf("[%s]D-%p\n", self->isa->name, object);
9141 Class $WebDefaultUIKitDelegate;
9143 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9144 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9145 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9146 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9149 static NSNumber *shouldPlayKeyboardSounds;
9153 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9155 case 1104: // Keyboard Button Clicked
9156 case 1105: // Keyboard Delete Repeated
9157 if (shouldPlayKeyboardSounds == nil) {
9158 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9159 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9162 if (![shouldPlayKeyboardSounds boolValue])
9166 _UIHardware$_playSystemSound$(self, _cmd, sound);
9170 int main(int argc, char *argv[]) { _pooled
9173 if (Class $UIDevice = objc_getClass("UIDevice")) {
9174 UIDevice *device([$UIDevice currentDevice]);
9175 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9179 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9181 /* Library Hacks {{{ */
9182 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9184 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9185 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9186 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9187 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9188 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9191 $UIHardware = objc_getClass("UIHardware");
9192 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9193 if (UIHardware$_playSystemSound$ != NULL) {
9194 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9195 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9198 /* Set Locale {{{ */
9199 Locale_ = CFLocaleCopyCurrent();
9200 Languages_ = [NSLocale preferredLanguages];
9201 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9202 //NSLog(@"%@", [Languages_ description]);
9205 if (Languages_ == nil || [Languages_ count] == 0)
9206 // XXX: consider just setting to C and then falling through?
9209 lang = [[Languages_ objectAtIndex:0] UTF8String];
9210 setenv("LANG", lang, true);
9213 //std::setlocale(LC_ALL, lang);
9214 NSLog(@"Setting Language: %s", lang);
9217 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9219 /* Parse Arguments {{{ */
9220 bool substrate(false);
9226 for (int argi(1); argi != argc; ++argi)
9227 if (strcmp(argv[argi], "--") == 0) {
9229 argv[argi] = argv[0];
9235 for (int argi(1); argi != arge; ++argi)
9236 if (strcmp(args[argi], "--substrate") == 0)
9239 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9243 App_ = [[NSBundle mainBundle] bundlePath];
9244 Home_ = NSHomeDirectory();
9250 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9251 alloc_ = alloc->method_imp;
9252 alloc->method_imp = (IMP) &Alloc_;*/
9254 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9255 dealloc_ = dealloc->method_imp;
9256 dealloc->method_imp = (IMP) &Dealloc_;*/
9258 /* System Information {{{ */
9262 size = sizeof(maxproc);
9263 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9264 perror("sysctlbyname(\"kern.maxproc\", ?)");
9265 else if (maxproc < 64) {
9267 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9268 perror("sysctlbyname(\"kern.maxproc\", #)");
9271 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9272 char *osversion = new char[size];
9273 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9274 perror("sysctlbyname(\"kern.osversion\", ?)");
9276 System_ = [NSString stringWithUTF8String:osversion];
9278 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9279 char *machine = new char[size];
9280 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9281 perror("sysctlbyname(\"hw.machine\", ?)");
9285 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9286 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9287 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9288 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9292 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9293 NSData *data((NSData *) ecid);
9294 size_t length([data length]);
9295 uint8_t bytes[length];
9296 [data getBytes:bytes];
9297 char string[length * 2 + 1];
9298 for (size_t i(0); i != length; ++i)
9299 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9300 ChipID_ = [NSString stringWithUTF8String:string];
9304 IOObjectRelease(service);
9308 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9310 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9311 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9312 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9314 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9315 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9316 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9318 if (mcc != NULL && mnc != NULL)
9319 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9326 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9327 Build_ = [system objectForKey:@"ProductBuildVersion"];
9328 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9329 Product_ = [info objectForKey:@"SafariProductVersion"];
9330 Safari_ = [info objectForKey:@"CFBundleVersion"];
9333 /* Load Database {{{ */
9335 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9337 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9339 if (Metadata_ == NULL)
9340 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9342 Settings_ = [Metadata_ objectForKey:@"Settings"];
9344 Packages_ = [Metadata_ objectForKey:@"Packages"];
9345 Sections_ = [Metadata_ objectForKey:@"Sections"];
9346 Sources_ = [Metadata_ objectForKey:@"Sources"];
9348 Token_ = [Metadata_ objectForKey:@"Token"];
9351 if (Settings_ != nil)
9352 Role_ = [Settings_ objectForKey:@"Role"];
9354 if (Sections_ == nil) {
9355 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9356 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9359 if (Sources_ == nil) {
9360 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9361 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9366 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9369 if (Packages_ != nil) {
9370 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9372 [Metadata_ removeObjectForKey:@"Packages"];
9377 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9379 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9380 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9381 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9382 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9383 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9384 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9386 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9388 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9389 unlink("/tmp/.cydia.fw");
9391 } else if (access("/User", F_OK) != 0 || version < 2) {
9394 system("/usr/libexec/cydia/firmware.sh");
9398 _assert([[NSFileManager defaultManager]
9399 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9400 withIntermediateDirectories:YES
9405 if (access("/tmp/cydia.chk", F_OK) == 0) {
9406 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9407 _assert(errno == ENOENT);
9408 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9409 _assert(errno == ENOENT);
9412 /* APT Initialization {{{ */
9413 _assert(pkgInitConfig(*_config));
9414 _assert(pkgInitSystem(*_config, _system));
9417 _config->Set("APT::Acquire::Translation", lang);
9419 // XXX: this timeout might be important :(
9420 //_config->Set("Acquire::http::Timeout", 15);
9422 _config->Set("Acquire::http::MaxParallel", 3);
9424 /* Color Choices {{{ */
9425 space_ = CGColorSpaceCreateDeviceRGB();
9427 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9428 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9429 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9430 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9431 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9432 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9433 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9434 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9435 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9437 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9438 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9440 /* UIKit Configuration {{{ */
9441 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9442 if ($GSFontSetUseLegacyFontMetrics != NULL)
9443 $GSFontSetUseLegacyFontMetrics(YES);
9445 // XXX: I have a feeling this was important
9446 //UIKeyboardDisableAutomaticAppearance();
9449 Colon_ = UCLocalize("COLON_DELIMITED");
9450 Elision_ = UCLocalize("ELISION");
9451 Error_ = UCLocalize("ERROR");
9452 Warning_ = UCLocalize("WARNING");
9455 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9457 CGColorSpaceRelease(space_);