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>
111 #include <mach-o/nlist.h>
121 #include <Cytore.hpp>
123 #include "UICaboodle/BrowserView.h"
125 #include "substrate.h"
132 #define _timestamp ({ \
134 gettimeofday(&tv, NULL); \
135 tv.tv_sec * 1000000 + tv.tv_usec; \
138 typedef std::vector<class ProfileTime *> TimeList;
148 ProfileTime(const char *name) :
152 times_.push_back(this);
155 void AddTime(uint64_t time) {
162 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
174 ProfileTimer(ProfileTime &time) :
181 time_.AddTime(_timestamp - start_);
186 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
188 std::cerr << "========" << std::endl;
191 #define _profile(name) { \
192 static ProfileTime name(#name); \
193 ProfileTimer _ ## name(name);
198 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
200 #define CYPoolStart() \
201 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
203 #define CYPoolEnd() \
207 // Hash Functions/Structures {{{
208 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
216 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
218 void NSLogPoint(const char *fix, const CGPoint &point) {
219 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
222 void NSLogRect(const char *fix, const CGRect &rect) {
223 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
226 static _finline NSString *CydiaURL(NSString *path) {
228 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
229 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
230 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
231 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
232 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
233 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
236 static _finline void UpdateExternalStatus(uint64_t newStatus) {
238 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
239 notify_set_state(notify_token, newStatus);
240 notify_cancel(notify_token);
242 notify_post("com.saurik.Cydia.status");
245 /* [NSObject yieldToSelector:(withObject:)] {{{*/
246 @interface NSObject (Cydia)
247 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
248 - (id) yieldToSelector:(SEL)selector;
251 @implementation NSObject (Cydia)
256 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
257 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
258 id object([[context objectAtIndex:1] nonretainedObjectValue]);
259 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
261 /* XXX: deal with exceptions */
262 id value([self performSelector:selector withObject:object]);
264 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
265 [context removeAllObjects];
266 if ([signature methodReturnLength] != 0 && value != nil)
267 [context addObject:value];
272 performSelectorOnMainThread:@selector(doNothing)
278 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
279 /*return [self performSelector:selector withObject: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;
1015 static const int ButtonBarWidth_ = 60;
1016 static const int ButtonBarHeight_ = 48;
1017 static const float KeyboardTime_ = 0.3f;
1020 static NSArray *Finishes_;
1022 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1023 #define NotifyConfig_ "/etc/notify.conf"
1025 static bool Queuing_;
1027 static CYColor Blue_;
1028 static CYColor Blueish_;
1029 static CYColor Black_;
1030 static CYColor Off_;
1031 static CYColor White_;
1032 static CYColor Gray_;
1033 static CYColor Green_;
1034 static CYColor Purple_;
1035 static CYColor Purplish_;
1037 static UIColor *InstallingColor_;
1038 static UIColor *RemovingColor_;
1040 static NSString *App_;
1041 static NSString *Home_;
1043 static BOOL Advanced_;
1044 static BOOL Ignored_;
1046 static UIFont *Font12_;
1047 static UIFont *Font12Bold_;
1048 static UIFont *Font14_;
1049 static UIFont *Font18Bold_;
1050 static UIFont *Font22Bold_;
1052 static const char *Machine_ = NULL;
1053 static NSString *System_ = nil;
1054 static NSString *SerialNumber_ = nil;
1055 static NSString *ChipID_ = nil;
1056 static NSString *Token_ = nil;
1057 static NSString *UniqueID_ = nil;
1058 static NSString *PLMN_ = nil;
1059 static NSString *Build_ = nil;
1060 static NSString *Product_ = nil;
1061 static NSString *Safari_ = nil;
1063 static CFLocaleRef Locale_;
1064 static NSArray *Languages_;
1065 static CGColorSpaceRef space_;
1067 static NSDictionary *SectionMap_;
1068 static NSMutableDictionary *Metadata_;
1069 static _transient NSMutableDictionary *Settings_;
1070 static _transient NSString *Role_;
1071 static _transient NSMutableDictionary *Packages_;
1072 static _transient NSMutableDictionary *Sections_;
1073 static _transient NSMutableDictionary *Sources_;
1074 static bool Changed_;
1077 static bool IsWildcat_;
1080 /* Display Helpers {{{ */
1081 inline float Interpolate(float begin, float end, float fraction) {
1082 return (end - begin) * fraction + begin;
1085 /* XXX: localize this! */
1086 NSString *SizeString(double size) {
1087 bool negative = size < 0;
1092 while (size > 1024) {
1097 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1099 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1102 static _finline const char *StripVersion_(const char *version) {
1103 const char *colon(strchr(version, ':'));
1104 return colon == NULL ? version : colon + 1;
1107 NSString *LocalizeSection(NSString *section) {
1108 static Pcre title_r("^(.*?) \\((.*)\\)$");
1109 if (title_r(section)) {
1110 NSString *parent(title_r[1]);
1111 NSString *child(title_r[2]);
1113 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1114 LocalizeSection(parent),
1115 LocalizeSection(child)
1119 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1122 NSString *Simplify(NSString *title) {
1123 const char *data = [title UTF8String];
1124 size_t size = [title length];
1126 static Pcre square_r("^\\[(.*)\\]$");
1127 if (square_r(data, size))
1128 return Simplify(square_r[1]);
1130 static Pcre paren_r("^\\((.*)\\)$");
1131 if (paren_r(data, size))
1132 return Simplify(paren_r[1]);
1134 static Pcre title_r("^(.*?) \\((.*)\\)$");
1135 if (title_r(data, size))
1136 return Simplify(title_r[1]);
1142 NSString *GetLastUpdate() {
1143 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1146 return UCLocalize("NEVER_OR_UNKNOWN");
1148 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1149 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1151 CFRelease(formatter);
1153 return [(NSString *) formatted autorelease];
1156 bool isSectionVisible(NSString *section) {
1157 NSDictionary *metadata([Sections_ objectForKey:section]);
1158 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1159 return hidden == nil || ![hidden boolValue];
1164 /* Delegate Prototypes {{{ */
1168 @interface NSObject (ProgressDelegate)
1171 @protocol ProgressDelegate
1172 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1173 - (void) setProgressTitle:(NSString *)title;
1174 - (void) setProgressPercent:(float)percent;
1175 - (void) startProgress;
1176 - (void) addProgressOutput:(NSString *)output;
1177 - (bool) isCancelling:(size_t)received;
1180 @protocol ConfigurationDelegate
1181 - (void) repairWithSelector:(SEL)selector;
1182 - (void) setConfigurationData:(NSString *)data;
1185 @class PackageController;
1187 @protocol CydiaDelegate
1188 - (void) setPackageController:(PackageController *)view;
1189 - (void) clearPackage:(Package *)package;
1190 - (void) installPackage:(Package *)package;
1191 - (void) installPackages:(NSArray *)packages;
1192 - (void) removePackage:(Package *)package;
1193 - (void) beginUpdate;
1195 - (void) distUpgrade;
1197 - (void) updateData;
1199 - (void) showSettings;
1200 - (UIProgressHUD *) addProgressHUD;
1201 - (BOOL) hudIsShowing;
1202 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1203 - (CYViewController *) pageForPackage:(NSString *)name;
1204 - (PackageController *) packageController;
1205 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1209 /* Status Delegation {{{ */
1211 public pkgAcquireStatus
1214 _transient NSObject<ProgressDelegate> *delegate_;
1222 void setDelegate(id delegate) {
1223 delegate_ = delegate;
1226 NSObject<ProgressDelegate> *getDelegate() const {
1230 virtual bool MediaChange(std::string media, std::string drive) {
1234 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1237 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1238 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1239 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1242 virtual void Done(pkgAcquire::ItemDesc &item) {
1245 virtual void Fail(pkgAcquire::ItemDesc &item) {
1247 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1248 item.Owner->Status == pkgAcquire::Item::StatDone
1252 std::string &error(item.Owner->ErrorText);
1256 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1257 NSArray *fields([description componentsSeparatedByString:@" "]);
1258 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1260 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1261 withObject:[NSArray arrayWithObjects:
1262 [NSString stringWithUTF8String:error.c_str()],
1269 virtual bool Pulse(pkgAcquire *Owner) {
1270 bool value = pkgAcquireStatus::Pulse(Owner);
1273 double(CurrentBytes + CurrentItems) /
1274 double(TotalBytes + TotalItems)
1277 [delegate_ setProgressPercent:percent];
1278 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1281 virtual void Start() {
1282 [delegate_ startProgress];
1285 virtual void Stop() {
1289 /* Progress Delegation {{{ */
1294 _transient id<ProgressDelegate> delegate_;
1298 virtual void Update() {
1299 /*if (abs(Percent - percent_) > 2)
1300 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1304 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1305 [delegate_ setProgressPercent:(Percent / 100)];*/
1315 void setDelegate(id delegate) {
1316 delegate_ = delegate;
1319 id getDelegate() const {
1323 virtual void Done() {
1325 //[delegate_ setProgressPercent:1];
1330 /* Database Interface {{{ */
1331 typedef std::map< unsigned long, _H<Source> > SourceMap;
1333 @interface Database : NSObject {
1339 pkgCacheFile cache_;
1340 pkgDepCache::Policy *policy_;
1341 pkgRecords *records_;
1342 pkgProblemResolver *resolver_;
1343 pkgAcquire *fetcher_;
1345 SPtr<pkgPackageManager> manager_;
1346 pkgSourceList *list_;
1349 CFMutableArrayRef packages_;
1351 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1360 + (Database *) sharedInstance;
1363 - (void) _readCydia:(NSNumber *)fd;
1364 - (void) _readStatus:(NSNumber *)fd;
1365 - (void) _readOutput:(NSNumber *)fd;
1369 - (Package *) packageWithName:(NSString *)name;
1371 - (pkgCacheFile &) cache;
1372 - (pkgDepCache::Policy *) policy;
1373 - (pkgRecords *) records;
1374 - (pkgProblemResolver *) resolver;
1375 - (pkgAcquire &) fetcher;
1376 - (pkgSourceList &) list;
1377 - (NSArray *) packages;
1378 - (NSArray *) sources;
1379 - (void) reloadData;
1387 - (void) updateWithStatus:(Status &)status;
1389 - (void) setDelegate:(id)delegate;
1390 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1393 /* Delegate Helpers {{{ */
1394 @implementation NSObject (ProgressDelegate)
1396 - (void) _setProgressErrorPackage:(NSArray *)args {
1397 [self performSelector:@selector(setProgressError:forPackage:)
1398 withObject:[args objectAtIndex:0]
1399 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1403 - (void) _setProgressErrorTitle:(NSArray *)args {
1404 [self performSelector:@selector(setProgressError:withTitle:)
1405 withObject:[args objectAtIndex:0]
1406 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1410 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1411 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1412 withObject:[NSArray arrayWithObjects:error, title, nil]
1417 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1418 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1420 [self performSelector:@selector(setProgressError:withTitle:)
1422 withObject:(package == nil ? id : [package name])
1429 // Cytore Definitions {{{
1430 struct PackageValue :
1433 Cytore::Offset<PackageValue> next_;
1435 uint32_t index_ : 23;
1436 uint32_t subscribed_ : 1;
1452 Cytore::Offset<PackageValue> packages_[1 << 16];
1455 static Cytore::File<MetaValue> MetaFile_;
1457 // Cytore Helper Functions {{{
1458 static PackageValue *PackageFind(const char *name, size_t length) {
1459 SplitHash nhash = { hashlittle(name, length) };
1461 PackageValue *metadata;
1463 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1464 offset: if (offset->IsNull()) {
1465 *offset = MetaFile_.New<PackageValue>(length + 1);
1466 metadata = &MetaFile_.Get(*offset);
1468 memcpy(metadata->name_, name, length + 1);
1469 metadata->nhash_ = nhash.u16[1];
1471 metadata = &MetaFile_.Get(*offset);
1473 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1474 offset = &metadata->next_;
1482 static void PackageImport(const void *key, const void *value, void *context) {
1484 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1485 NSLog(@"failed to import package %@", key);
1489 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1490 NSDictionary *package((NSDictionary *) value);
1492 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1493 if ([subscribed boolValue])
1494 metadata->subscribed_ = true;
1496 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1497 time_t time([date timeIntervalSince1970]);
1498 if (metadata->first_ > time || metadata->first_ == 0)
1499 metadata->first_ = time;
1502 if (NSDate *date = [package objectForKey:@"LastSeen"]) {
1503 time_t time([date timeIntervalSince1970]);
1504 if (metadata->last_ < time || metadata->last_ == 0) {
1505 metadata->last_ = time;
1508 } else if (metadata->last_ == 0) last: {
1509 NSString *version([package objectForKey:@"LastVersion"]);
1510 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1511 size_t length(strlen(buffer));
1512 uint16_t vhash(hashlittle(buffer, length));
1514 size_t capped(std::min<size_t>(8, length));
1515 char *latest(buffer + length - capped);
1517 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1518 metadata->vhash_ = vhash;
1524 /* Source Class {{{ */
1525 @interface Source : NSObject {
1526 CYString depiction_;
1527 CYString description_;
1533 CYString distribution_;
1538 NSString *authority_;
1540 CYString defaultIcon_;
1542 NSDictionary *record_;
1546 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1548 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1550 - (NSString *) depictionForPackage:(NSString *)package;
1551 - (NSString *) supportForPackage:(NSString *)package;
1553 - (NSDictionary *) record;
1557 - (NSString *) distribution;
1558 - (NSString *) type;
1560 - (NSString *) host;
1562 - (NSString *) name;
1563 - (NSString *) description;
1564 - (NSString *) label;
1565 - (NSString *) origin;
1566 - (NSString *) version;
1568 - (NSString *) defaultIcon;
1572 @implementation Source
1576 distribution_.clear();
1579 description_.clear();
1585 defaultIcon_.clear();
1587 if (record_ != nil) {
1597 if (authority_ != nil) {
1598 [authority_ release];
1604 // XXX: this is a very inefficient way to call these deconstructors
1609 + (NSArray *) _attributeKeys {
1610 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1613 - (NSArray *) attributeKeys {
1614 return [[self class] _attributeKeys];
1617 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1618 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1621 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1624 trusted_ = index->IsTrusted();
1626 uri_.set(pool, index->GetURI());
1627 distribution_.set(pool, index->GetDist());
1628 type_.set(pool, index->GetType());
1630 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1631 if (dindex != NULL) {
1633 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1636 pkgTagFile tags(&fd);
1638 pkgTagSection section;
1645 {"default-icon", &defaultIcon_},
1646 {"depiction", &depiction_},
1647 {"description", &description_},
1649 {"origin", &origin_},
1650 {"support", &support_},
1651 {"version", &version_},
1654 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1655 const char *start, *end;
1657 if (section.Find(names[i].name_, start, end)) {
1658 CYString &value(*names[i].value_);
1659 value.set(pool, start, end - start);
1665 record_ = [Sources_ objectForKey:[self key]];
1667 record_ = [record_ retain];
1669 NSURL *url([NSURL URLWithString:uri_]);
1673 host_ = [[host_ lowercaseString] retain];
1678 authority_ = [url path];
1680 if (authority_ != nil)
1681 authority_ = [authority_ retain];
1684 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1685 if ((self = [super init]) != nil) {
1686 [self setMetaIndex:index inPool:pool];
1690 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1691 NSDictionary *lhr = [self record];
1692 NSDictionary *rhr = [source record];
1695 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1697 NSString *lhs = [self name];
1698 NSString *rhs = [source name];
1700 if ([lhs length] != 0 && [rhs length] != 0) {
1701 unichar lhc = [lhs characterAtIndex:0];
1702 unichar rhc = [rhs characterAtIndex:0];
1704 if (isalpha(lhc) && !isalpha(rhc))
1705 return NSOrderedAscending;
1706 else if (!isalpha(lhc) && isalpha(rhc))
1707 return NSOrderedDescending;
1710 return [lhs compare:rhs options:LaxCompareOptions_];
1713 - (NSString *) depictionForPackage:(NSString *)package {
1714 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1717 - (NSString *) supportForPackage:(NSString *)package {
1718 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1721 - (NSDictionary *) record {
1729 - (NSString *) uri {
1733 - (NSString *) distribution {
1734 return distribution_;
1737 - (NSString *) type {
1741 - (NSString *) key {
1742 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1745 - (NSString *) host {
1749 - (NSString *) name {
1750 return origin_.empty() ? authority_ : origin_;
1753 - (NSString *) description {
1754 return description_;
1757 - (NSString *) label {
1758 return label_.empty() ? authority_ : label_;
1761 - (NSString *) origin {
1765 - (NSString *) version {
1769 - (NSString *) defaultIcon {
1770 return defaultIcon_;
1775 /* Relationship Class {{{ */
1776 @interface Relationship : NSObject {
1781 - (NSString *) type;
1783 - (NSString *) name;
1787 @implementation Relationship
1795 - (NSString *) type {
1803 - (NSString *) name {
1810 /* Package Class {{{ */
1811 struct ParsedPackage {
1816 CYString depiction_;
1826 @interface Package : NSObject {
1828 uint32_t essential_ : 1;
1829 uint32_t obsolete_ : 1;
1830 uint32_t ignored_ : 1;
1834 _transient Database *database_;
1836 pkgCache::VerIterator version_;
1837 pkgCache::PkgIterator iterator_;
1838 pkgCache::VerFileIterator file_;
1844 CYString installed_;
1847 _transient NSString *section$_;
1851 PackageValue *metadata_;
1852 ParsedPackage *parsed_;
1854 NSMutableArray *tags_;
1858 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1859 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1861 - (pkgCache::PkgIterator) iterator;
1864 - (NSString *) section;
1865 - (NSString *) simpleSection;
1867 - (NSString *) longSection;
1868 - (NSString *) shortSection;
1872 - (Address *) maintainer;
1874 - (NSString *) longDescription;
1875 - (NSString *) shortDescription;
1878 - (PackageValue *) metadata;
1881 - (bool) subscribed;
1882 - (bool) setSubscribed:(bool)subscribed;
1886 - (NSString *) latest;
1887 - (NSString *) installed;
1888 - (BOOL) uninstalled;
1891 - (BOOL) upgradableAndEssential:(BOOL)essential;
1894 - (BOOL) unfiltered;
1898 - (BOOL) halfConfigured;
1899 - (BOOL) halfInstalled;
1901 - (NSString *) mode;
1904 - (NSString *) name;
1906 - (NSString *) homepage;
1907 - (NSString *) depiction;
1908 - (Address *) author;
1910 - (NSString *) support;
1912 - (NSArray *) files;
1913 - (NSArray *) warnings;
1914 - (NSArray *) applications;
1916 - (Source *) source;
1917 - (NSString *) role;
1919 - (BOOL) matches:(NSString *)text;
1921 - (bool) hasSupportingRole;
1922 - (BOOL) hasTag:(NSString *)tag;
1923 - (NSString *) primaryPurpose;
1924 - (NSArray *) purposes;
1925 - (bool) isCommercial;
1927 - (void) setIndex:(size_t)index;
1929 - (CYString &) cyname;
1931 - (uint32_t) compareBySection:(NSArray *)sections;
1936 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1937 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1938 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1939 - (bool) isVisibleInSection:(NSString *)section;
1940 - (bool) isVisibleInSource:(Source *)source;
1944 uint32_t PackageChangesRadix(Package *self, void *) {
1949 uint32_t timestamp : 30;
1950 uint32_t ignored : 1;
1951 uint32_t upgradable : 1;
1955 bool upgradable([self upgradableAndEssential:YES]);
1956 value.bits.upgradable = upgradable ? 1 : 0;
1959 value.bits.timestamp = 0;
1960 value.bits.ignored = [self ignored] ? 0 : 1;
1961 value.bits.upgradable = 1;
1963 value.bits.timestamp = [self seen] >> 2;
1964 value.bits.ignored = 0;
1965 value.bits.upgradable = 0;
1968 return _not(uint32_t) - value.key;
1971 _finline static void Stifle(uint8_t &value) {
1974 uint32_t PackagePrefixRadix(Package *self, void *context) {
1975 size_t offset(reinterpret_cast<size_t>(context));
1976 CYString &name([self cyname]);
1978 size_t size(name.size());
1981 char *text(name.data());
1984 if (!isdigit(text[0]))
1988 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)
2095 + (NSString *) webScriptNameForSelector:(SEL)selector {
2096 if (selector == @selector(hasTag:))
2102 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2103 return [self webScriptNameForSelector:selector] == nil;
2106 + (NSArray *) _attributeKeys {
2107 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];
2110 - (NSArray *) attributeKeys {
2111 return [[self class] _attributeKeys];
2114 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2115 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2119 if (parsed_ != NULL)
2121 @synchronized (database_) {
2122 if ([database_ era] != era_ || file_.end())
2125 ParsedPackage *parsed(new ParsedPackage);
2128 _profile(Package$parse)
2129 pkgRecords::Parser *parser;
2131 _profile(Package$parse$Lookup)
2132 parser = &[database_ records]->Lookup(file_);
2137 _profile(Package$parse$Find)
2142 {"icon", &parsed->icon_},
2143 {"depiction", &parsed->depiction_},
2144 {"homepage", &parsed->homepage_},
2145 {"website", &website},
2146 {"bugs", &parsed->bugs_},
2147 {"support", &parsed->support_},
2148 {"sponsor", &parsed->sponsor_},
2149 {"author", &parsed->author_},
2152 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2153 const char *start, *end;
2155 if (parser->Find(names[i].name_, start, end)) {
2156 CYString &value(*names[i].value_);
2157 _profile(Package$parse$Value)
2158 value.set(pool_, start, end - start);
2164 _profile(Package$parse$Tagline)
2165 const char *start, *end;
2166 if (parser->ShortDesc(start, end)) {
2167 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2170 while (stop != start && stop[-1] == '\r')
2172 parsed->tagline_.set(pool_, start, stop - start);
2176 _profile(Package$parse$Retain)
2177 if (parsed->homepage_.empty())
2178 parsed->homepage_ = website;
2179 if (parsed->homepage_ == parsed->depiction_)
2180 parsed->homepage_.clear();
2185 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2186 if ((self = [super init]) != nil) {
2187 _profile(Package$initWithVersion)
2190 database_ = database;
2191 era_ = [database era];
2195 pkgCache::PkgIterator iterator(version.ParentPkg());
2196 iterator_ = iterator;
2198 _profile(Package$initWithVersion$Version)
2199 if (!version_.end())
2200 file_ = version_.FileList();
2202 pkgCache &cache([database_ cache]);
2203 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2207 _profile(Package$initWithVersion$Cache)
2208 id_.set(NULL, iterator.Name());
2209 name_.set(NULL, iterator.Display());
2211 latest_.set(NULL, StripVersion_(version_.VerStr()));
2213 pkgCache::VerIterator current(iterator.CurrentVer());
2215 installed_.set(NULL, StripVersion_(current.VerStr()));
2218 _profile(Package$initWithVersion$Lower)
2219 // XXX: do not use tolower() as this is not locale-specific? :(
2220 char *data(id_.data());
2221 for (size_t i(0), e(id_.size()); i != e; ++i)
2222 if ((data[i] & 0x20) == 0) {
2231 _profile(Package$initWithVersion$Tags)
2232 pkgCache::TagIterator tag(iterator.TagList());
2234 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2236 const char *name(tag.Name());
2237 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2239 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2240 role_ = (NSString *) CYStringCreate(name + 6);
2242 if (strncmp(name, "cydia::", 7) == 0) {
2243 if (strcmp(name + 7, "essential") == 0)
2245 else if (strcmp(name + 7, "obsolete") == 0)
2250 } while (!tag.end());
2254 _profile(Package$initWithVersion$Metadata)
2255 PackageValue *metadata(PackageFind(id_.data(), id_.size()));
2256 metadata_ = metadata;
2258 const char *latest(version_.VerStr());
2259 size_t length(strlen(latest));
2261 uint16_t vhash(hashlittle(latest, length));
2263 size_t capped(std::min<size_t>(8, length));
2264 latest = latest + length - capped;
2266 if (metadata->first_ == 0)
2267 metadata->first_ = now_;
2269 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2270 metadata->last_ = now_;
2271 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2272 metadata->vhash_ = vhash;
2273 } else if (metadata->last_ == 0)
2274 metadata->last_ = metadata->first_;
2277 _profile(Package$initWithVersion$Section)
2278 section_.set(NULL, iterator.Section());
2281 _profile(Package$initWithVersion$Flags)
2282 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2283 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2288 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2289 pkgCache::VerIterator version;
2291 _profile(Package$packageWithIterator$GetCandidateVer)
2292 version = [database policy]->GetCandidateVer(iterator);
2300 _profile(Package$packageWithIterator$Allocate)
2301 package = [Package allocWithZone:zone];
2304 _profile(Package$packageWithIterator$Initialize)
2306 initWithVersion:version
2313 _profile(Package$packageWithIterator$Autorelease)
2314 package = [package autorelease];
2320 - (pkgCache::PkgIterator) iterator {
2324 - (NSString *) section {
2325 if (section$_ == nil) {
2326 if (section_.empty())
2329 _profile(Package$section)
2330 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2331 NSString *name(section_);
2332 section$_ = [SectionMap_ objectForKey:name] ?: name;
2337 - (NSString *) simpleSection {
2338 if (NSString *section = [self section])
2339 return Simplify(section);
2344 - (NSString *) longSection {
2345 return LocalizeSection([self section]);
2348 - (NSString *) shortSection {
2349 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2352 - (NSString *) uri {
2355 pkgIndexFile *index;
2356 pkgCache::PkgFileIterator file(file_.File());
2357 if (![database_ list].FindIndex(file, index))
2359 return [NSString stringWithUTF8String:iterator_->Path];
2360 //return [NSString stringWithUTF8String:file.Site()];
2361 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2365 - (Address *) maintainer {
2366 @synchronized (database_) {
2367 if ([database_ era] != era_ || file_.end())
2370 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2371 const std::string &maintainer(parser->Maintainer());
2372 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2376 @synchronized (database_) {
2377 if ([database_ era] != era_ || version_.end())
2380 return version_->InstalledSize;
2383 - (NSString *) longDescription {
2384 @synchronized (database_) {
2385 if ([database_ era] != era_ || file_.end())
2388 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2389 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2391 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2392 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2393 if ([lines count] < 2)
2396 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2397 for (size_t i(1), e([lines count]); i != e; ++i) {
2398 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2399 [trimmed addObject:trim];
2402 return [trimmed componentsJoinedByString:@"\n"];
2405 - (NSString *) shortDescription {
2406 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2410 _profile(Package$index)
2411 CFStringRef name((CFStringRef) [self name]);
2412 if (CFStringGetLength(name) == 0)
2414 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2415 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2417 return toupper(character);
2421 - (PackageValue *) metadata {
2426 PackageValue *metadata([self metadata]);
2427 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2430 - (bool) subscribed {
2431 return [self metadata]->subscribed_;
2434 - (bool) setSubscribed:(bool)subscribed {
2435 PackageValue *metadata([self metadata]);
2436 if (metadata->subscribed_ == subscribed)
2438 metadata->subscribed_ = subscribed;
2446 - (NSString *) latest {
2450 - (NSString *) installed {
2454 - (BOOL) uninstalled {
2455 return installed_.empty();
2459 return !version_.end();
2462 - (BOOL) upgradableAndEssential:(BOOL)essential {
2463 _profile(Package$upgradableAndEssential)
2464 pkgCache::VerIterator current(iterator_.CurrentVer());
2466 return essential && essential_;
2468 return !version_.end() && version_ != current;
2472 - (BOOL) essential {
2477 return [database_ cache][iterator_].InstBroken();
2480 - (BOOL) unfiltered {
2481 _profile(Package$unfiltered$obsolete)
2486 _profile(Package$unfiltered$hasSupportingRole)
2487 if (![self hasSupportingRole])
2495 if (![self unfiltered])
2498 NSString *section([self section]);
2500 _profile(Package$visible$isSectionVisible)
2501 if (section != nil && !isSectionVisible(section))
2509 unsigned char current(iterator_->CurrentState);
2510 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2513 - (BOOL) halfConfigured {
2514 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2517 - (BOOL) halfInstalled {
2518 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2522 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2523 return state.Mode != pkgDepCache::ModeKeep;
2526 - (NSString *) mode {
2527 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2529 switch (state.Mode) {
2530 case pkgDepCache::ModeDelete:
2531 if ((state.iFlags & pkgDepCache::Purge) != 0)
2535 case pkgDepCache::ModeKeep:
2536 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2537 return @"REINSTALL";
2538 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2542 case pkgDepCache::ModeInstall:
2543 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2544 return @"REINSTALL";
2545 else*/ switch (state.Status) {
2547 return @"DOWNGRADE";
2553 return @"NEW_INSTALL";
2564 - (NSString *) name {
2565 return name_.empty() ? id_ : name_;
2568 - (UIImage *) icon {
2569 NSString *section = [self simpleSection];
2572 if (parsed_ != NULL)
2573 if (NSString *href = parsed_->icon_)
2574 if ([href hasPrefix:@"file:///"])
2575 // XXX: correct escaping
2576 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2577 if (icon == nil) if (section != nil)
2578 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2579 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2580 if ([dicon hasPrefix:@"file:///"])
2581 // XXX: correct escaping
2582 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2584 icon = [UIImage applicationImageNamed:@"unknown.png"];
2588 - (NSString *) homepage {
2589 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2592 - (NSString *) depiction {
2593 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2596 - (Address *) sponsor {
2597 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2600 - (Address *) author {
2601 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2604 - (NSString *) support {
2605 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2608 - (NSArray *) files {
2609 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2610 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2613 fin.open([path UTF8String]);
2618 while (std::getline(fin, line))
2619 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2624 - (NSArray *) warnings {
2625 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2626 const char *name(iterator_.Name());
2628 size_t length(strlen(name));
2629 if (length < 2) invalid:
2630 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2631 else for (size_t i(0); i != length; ++i)
2633 /* XXX: technically this is not allowed */
2634 (name[i] < 'A' || name[i] > 'Z') &&
2635 (name[i] < 'a' || name[i] > 'z') &&
2636 (name[i] < '0' || name[i] > '9') &&
2637 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2640 if (strcmp(name, "cydia") != 0) {
2643 bool _private = false;
2646 bool repository = [[self section] isEqualToString:@"Repositories"];
2648 if (NSArray *files = [self files])
2649 for (NSString *file in files)
2650 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2652 else if (!user && [file isEqualToString:@"/User"])
2654 else if (!_private && [file isEqualToString:@"/private"])
2656 else if (!stash && [file isEqualToString:@"/var/stash"])
2659 /* XXX: this is not sensitive enough. only some folders are valid. */
2660 if (cydia && !repository)
2661 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2663 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2665 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2667 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2670 return [warnings count] == 0 ? nil : warnings;
2673 - (NSArray *) applications {
2674 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2676 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2678 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2679 if (NSArray *files = [self files])
2680 for (NSString *file in files)
2681 if (application_r(file)) {
2682 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2683 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2684 if ([id isEqualToString:me])
2687 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2689 display = application_r[1];
2691 NSString *bundle([file stringByDeletingLastPathComponent]);
2692 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2693 if (icon == nil || [icon length] == 0)
2695 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2697 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2698 [applications addObject:application];
2700 [application addObject:id];
2701 [application addObject:display];
2702 [application addObject:url];
2705 return [applications count] == 0 ? nil : applications;
2708 - (Source *) source {
2709 if (source_ == nil) {
2710 @synchronized (database_) {
2711 if ([database_ era] != era_ || file_.end())
2712 source_ = (Source *) [NSNull null];
2714 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2718 return source_ == (Source *) [NSNull null] ? nil : source_;
2721 - (NSString *) role {
2725 - (BOOL) matches:(NSString *)text {
2731 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2732 if (range.location != NSNotFound)
2735 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2736 if (range.location != NSNotFound)
2739 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2740 if (range.location != NSNotFound)
2746 - (bool) hasSupportingRole {
2749 if ([role_ isEqualToString:@"enduser"])
2751 if ([Role_ isEqualToString:@"User"])
2753 if ([role_ isEqualToString:@"hacker"])
2755 if ([Role_ isEqualToString:@"Hacker"])
2757 if ([role_ isEqualToString:@"developer"])
2759 if ([Role_ isEqualToString:@"Developer"])
2764 - (BOOL) hasTag:(NSString *)tag {
2765 return tags_ == nil ? NO : [tags_ containsObject:tag];
2768 - (NSString *) primaryPurpose {
2769 for (NSString *tag in tags_)
2770 if ([tag hasPrefix:@"purpose::"])
2771 return [tag substringFromIndex:9];
2775 - (NSArray *) purposes {
2776 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2777 for (NSString *tag in tags_)
2778 if ([tag hasPrefix:@"purpose::"])
2779 [purposes addObject:[tag substringFromIndex:9]];
2780 return [purposes count] == 0 ? nil : purposes;
2783 - (bool) isCommercial {
2784 return [self hasTag:@"cydia::commercial"];
2787 - (void) setIndex:(size_t)index {
2788 if (metadata_->index_ != index)
2789 metadata_->index_ = index;
2792 - (CYString &) cyname {
2793 return name_.empty() ? id_ : name_;
2796 - (uint32_t) compareBySection:(NSArray *)sections {
2797 NSString *section([self section]);
2798 for (size_t i(0), e([sections count]); i != e; ++i) {
2799 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2803 return _not(uint32_t);
2807 @synchronized (database_) {
2808 pkgProblemResolver *resolver = [database_ resolver];
2809 resolver->Clear(iterator_);
2811 pkgCacheFile &cache([database_ cache]);
2812 cache->SetReInstall(iterator_, false);
2813 cache->MarkKeep(iterator_, false);
2817 @synchronized (database_) {
2818 pkgProblemResolver *resolver = [database_ resolver];
2819 resolver->Clear(iterator_);
2820 resolver->Protect(iterator_);
2822 pkgCacheFile &cache([database_ cache]);
2823 cache->SetReInstall(iterator_, false);
2824 cache->MarkInstall(iterator_, false);
2826 pkgDepCache::StateCache &state((*cache)[iterator_]);
2827 if (!state.Install())
2828 cache->SetReInstall(iterator_, true);
2832 @synchronized (database_) {
2833 pkgProblemResolver *resolver = [database_ resolver];
2834 resolver->Clear(iterator_);
2835 resolver->Remove(iterator_);
2836 resolver->Protect(iterator_);
2838 pkgCacheFile &cache([database_ cache]);
2839 cache->SetReInstall(iterator_, false);
2840 cache->MarkDelete(iterator_, true);
2843 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2844 _profile(Package$isUnfilteredAndSearchedForBy)
2847 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2848 value &= [self unfiltered];
2851 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2852 value &= [self matches:search];
2859 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2860 if ([search length] == 0)
2863 _profile(Package$isUnfilteredAndSelectedForBy)
2866 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2867 value &= [self unfiltered];
2870 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2871 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2878 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2879 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2882 - (bool) isVisibleInSection:(NSString *)name {
2883 NSString *section([self section]);
2887 section == nil && [name length] == 0 ||
2888 [name isEqualToString:section]
2889 ) && [self visible];
2892 - (bool) isVisibleInSource:(Source *)source {
2893 return [self source] == source && [self visible];
2898 /* Section Class {{{ */
2899 @interface Section : NSObject {
2904 NSString *localized_;
2907 - (NSComparisonResult) compareByLocalized:(Section *)section;
2908 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2909 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2910 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2911 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2912 - (NSString *) name;
2919 - (void) addToCount;
2921 - (void) setCount:(size_t)count;
2922 - (NSString *) localized;
2926 @implementation Section
2930 if (localized_ != nil)
2931 [localized_ release];
2935 - (NSComparisonResult) compareByLocalized:(Section *)section {
2936 NSString *lhs(localized_);
2937 NSString *rhs([section localized]);
2939 /*if ([lhs length] != 0 && [rhs length] != 0) {
2940 unichar lhc = [lhs characterAtIndex:0];
2941 unichar rhc = [rhs characterAtIndex:0];
2943 if (isalpha(lhc) && !isalpha(rhc))
2944 return NSOrderedAscending;
2945 else if (!isalpha(lhc) && isalpha(rhc))
2946 return NSOrderedDescending;
2949 return [lhs compare:rhs options:LaxCompareOptions_];
2952 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2953 if ((self = [self initWithName:name localize:NO]) != nil) {
2954 if (localized != nil)
2955 localized_ = [localized retain];
2959 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2960 return [self initWithName:name row:0 localize:localize];
2963 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2964 if ((self = [super init]) != nil) {
2965 name_ = [name retain];
2969 localized_ = [LocalizeSection(name_) retain];
2973 /* XXX: localize the index thingees */
2974 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2975 if ((self = [super init]) != nil) {
2976 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2982 - (NSString *) name {
3002 - (void) addToCount {
3006 - (void) setCount:(size_t)count {
3010 - (NSString *) localized {
3017 static NSString *Colon_;
3018 static NSString *Elision_;
3019 static NSString *Error_;
3020 static NSString *Warning_;
3022 /* Database Implementation {{{ */
3023 @implementation Database
3025 + (Database *) sharedInstance {
3026 static Database *instance;
3027 if (instance == nil)
3028 instance = [[Database alloc] init];
3036 - (void) releasePackages {
3037 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3038 CFArrayRemoveAllValues(packages_);
3042 // XXX: actually implement this thing
3044 [self releasePackages];
3045 apr_pool_destroy(pool_);
3046 NSRecycleZone(zone_);
3050 - (void) _readCydia:(NSNumber *)fd { _pooled
3051 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3052 std::istream is(&ib);
3055 static Pcre finish_r("^finish:([^:]*)$");
3057 while (std::getline(is, line)) {
3058 const char *data(line.c_str());
3059 size_t size = line.size();
3060 lprintf("C:%s\n", data);
3062 if (finish_r(data, size)) {
3063 NSString *finish = finish_r[1];
3064 int index = [Finishes_ indexOfObject:finish];
3065 if (index != INT_MAX && index > Finish_)
3073 - (void) _readStatus:(NSNumber *)fd { _pooled
3074 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3075 std::istream is(&ib);
3078 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3079 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3081 while (std::getline(is, line)) {
3082 const char *data(line.c_str());
3083 size_t size(line.size());
3084 lprintf("S:%s\n", data);
3086 if (conffile_r(data, size)) {
3087 [delegate_ setConfigurationData:conffile_r[1]];
3088 } else if (strncmp(data, "status: ", 8) == 0) {
3089 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3090 [delegate_ setProgressTitle:string];
3091 } else if (pmstatus_r(data, size)) {
3092 std::string type([pmstatus_r[1] UTF8String]);
3093 NSString *id = pmstatus_r[2];
3095 float percent([pmstatus_r[3] floatValue]);
3096 [delegate_ setProgressPercent:(percent / 100)];
3098 NSString *string = pmstatus_r[4];
3100 if (type == "pmerror")
3101 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3102 withObject:[NSArray arrayWithObjects:string, id, nil]
3105 else if (type == "pmstatus") {
3106 [delegate_ setProgressTitle:string];
3107 } else if (type == "pmconffile")
3108 [delegate_ setConfigurationData:string];
3110 lprintf("E:unknown pmstatus\n");
3112 lprintf("E:unknown status\n");
3118 - (void) _readOutput:(NSNumber *)fd { _pooled
3119 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3120 std::istream is(&ib);
3123 while (std::getline(is, line)) {
3124 lprintf("O:%s\n", line.c_str());
3125 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3135 - (Package *) packageWithName:(NSString *)name {
3136 @synchronized (self) {
3137 if (static_cast<pkgDepCache *>(cache_) == NULL)
3139 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3140 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3144 if ((self = [super init]) != nil) {
3151 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3152 apr_pool_create(&pool_, NULL);
3154 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3158 _assert(pipe(fds) != -1);
3161 _config->Set("APT::Keep-Fds::", cydiafd_);
3162 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3165 detachNewThreadSelector:@selector(_readCydia:)
3167 withObject:[NSNumber numberWithInt:fds[0]]
3170 _assert(pipe(fds) != -1);
3174 detachNewThreadSelector:@selector(_readStatus:)
3176 withObject:[NSNumber numberWithInt:fds[0]]
3179 _assert(pipe(fds) != -1);
3180 _assert(dup2(fds[0], 0) != -1);
3181 _assert(close(fds[0]) != -1);
3183 input_ = fdopen(fds[1], "a");
3185 _assert(pipe(fds) != -1);
3186 _assert(dup2(fds[1], 1) != -1);
3187 _assert(close(fds[1]) != -1);
3190 detachNewThreadSelector:@selector(_readOutput:)
3192 withObject:[NSNumber numberWithInt:fds[0]]
3197 - (pkgCacheFile &) cache {
3201 - (pkgDepCache::Policy *) policy {
3205 - (pkgRecords *) records {
3209 - (pkgProblemResolver *) resolver {
3213 - (pkgAcquire &) fetcher {
3217 - (pkgSourceList &) list {
3221 - (NSArray *) packages {
3222 return (NSArray *) packages_;
3225 - (NSArray *) sources {
3226 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3227 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3228 [sources addObject:i->second];
3232 - (NSArray *) issues {
3233 if (cache_->BrokenCount() == 0)
3236 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3238 for (Package *package in [self packages]) {
3239 if (![package broken])
3241 pkgCache::PkgIterator pkg([package iterator]);
3243 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3244 [entry addObject:[package name]];
3245 [issues addObject:entry];
3247 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3251 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3252 pkgCache::DepIterator start;
3253 pkgCache::DepIterator end;
3254 dep.GlobOr(start, end); // ++dep
3256 if (!cache_->IsImportantDep(end))
3258 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3261 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3262 [entry addObject:failure];
3263 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3265 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3266 if (Package *package = [self packageWithName:name])
3267 name = [package name];
3268 [failure addObject:name];
3270 pkgCache::PkgIterator target(start.TargetPkg());
3271 if (target->ProvidesList != 0)
3272 [failure addObject:@"?"];
3274 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3276 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3277 else if (!cache_[target].CandidateVerIter(cache_).end())
3278 [failure addObject:@"-"];
3279 else if (target->ProvidesList == 0)
3280 [failure addObject:@"!"];
3282 [failure addObject:@"%"];
3286 if (start.TargetVer() != 0)
3287 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3298 - (bool) popErrorWithTitle:(NSString *)title {
3300 std::string message;
3302 while (!_error->empty()) {
3304 bool warning(!_error->PopMessage(error));
3308 size_t size(error.size());
3309 if (size == 0 || error[size - 1] != '\n')
3311 error.resize(size - 1);
3313 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3315 if (!message.empty())
3320 if (fatal && !message.empty())
3321 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3326 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3327 return [self popErrorWithTitle:title] || !success;
3330 - (void) reloadData { CYPoolStart() {
3331 @synchronized (self) {
3334 [self releasePackages];
3355 apr_pool_clear(pool_);
3356 NSRecycleZone(zone_);
3358 int chk(creat("/tmp/cydia.chk", 0644));
3362 NSString *title(UCLocalize("DATABASE"));
3365 if (!cache_.Open(progress_, true)) { pop:
3367 bool warning(!_error->PopMessage(error));
3368 lprintf("cache_.Open():[%s]\n", error.c_str());
3370 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3371 [delegate_ repairWithSelector:@selector(configure)];
3372 else if (error == "The package lists or status file could not be parsed or opened.")
3373 [delegate_ repairWithSelector:@selector(update)];
3374 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3375 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3376 // else if (error == "The list of sources could not be read.")
3378 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3387 unlink("/tmp/cydia.chk");
3389 now_ = [[NSDate date] timeIntervalSince1970];
3391 policy_ = new pkgDepCache::Policy();
3392 records_ = new pkgRecords(cache_);
3393 resolver_ = new pkgProblemResolver(cache_);
3394 fetcher_ = new pkgAcquire(&status_);
3397 list_ = new pkgSourceList();
3398 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3401 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3402 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3406 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3409 if (cache_->BrokenCount() != 0) {
3410 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3413 if (cache_->BrokenCount() != 0) {
3414 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3418 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3422 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3423 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3424 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3425 // XXX: this could be more intelligent
3426 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3427 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3429 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3434 /*std::vector<Package *> packages;
3435 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3436 [packages_ release];
3441 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3442 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3443 //packages.push_back(package);
3444 CFArrayAppendValue(packages_, [package retain]);
3448 /*if (packages.empty())
3449 packages_ = [[NSArray alloc] init];
3451 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3454 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3455 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3456 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3464 /*if (!packages.empty())
3465 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3466 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3468 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3470 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3472 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3476 size_t count(CFArrayGetCount(packages_));
3477 for (size_t index(0); index != count; ++index)
3478 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3482 } } CYPoolEnd() _trace(); }
3485 @synchronized (self) {
3487 resolver_ = new pkgProblemResolver(cache_);
3489 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3490 if (!cache_[iterator].Keep()) {
3491 cache_->MarkKeep(iterator, false);
3492 cache_->SetReInstall(iterator, false);
3497 - (void) configure {
3498 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3499 system([dpkg UTF8String]);
3503 // XXX: I don't remember this condition
3508 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3510 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3512 if ([self popErrorWithTitle:title])
3516 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3519 public pkgArchiveCleaner
3522 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3527 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3534 fetcher_->Shutdown();
3536 pkgRecords records(cache_);
3538 lock_ = new FileFd();
3539 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3541 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3543 if ([self popErrorWithTitle:title])
3547 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3550 manager_ = (_system->CreatePM(cache_));
3551 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3558 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3560 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3562 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3564 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3565 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3568 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3573 bool failed = false;
3574 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3575 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3577 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3580 std::string uri = (*item)->DescURI();
3581 std::string error = (*item)->ErrorText;
3583 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3586 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3587 withObject:[NSArray arrayWithObjects:
3588 [NSString stringWithUTF8String:error.c_str()],
3600 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3602 if (_error->PendingError()) {
3607 if (result == pkgPackageManager::Failed) {
3612 if (result != pkgPackageManager::Completed) {
3617 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3619 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3621 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3622 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3625 if (![before isEqualToArray:after])
3630 NSString *title(UCLocalize("UPGRADE"));
3631 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3637 [self updateWithStatus:status_];
3640 - (void) updateWithStatus:(Status &)status {
3641 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3642 NSString *title(UCLocalize("REFRESHING_DATA"));
3645 if (!list.ReadMainList())
3646 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3649 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3650 if ([self popErrorWithTitle:title])
3653 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3654 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3655 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3657 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3661 - (void) setDelegate:(id)delegate {
3662 delegate_ = delegate;
3663 status_.setDelegate(delegate);
3664 progress_.setDelegate(delegate);
3667 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3668 SourceMap::const_iterator i(sources_.find(file->ID));
3669 return i == sources_.end() ? nil : i->second;
3675 /* Confirmation Controller {{{ */
3676 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3677 if (!iterator.end())
3678 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3679 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3681 pkgCache::PkgIterator package(dep.TargetPkg());
3684 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3692 /* Web Scripting {{{ */
3693 @interface CydiaObject : NSObject {
3695 _transient id delegate_;
3698 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3701 @implementation CydiaObject
3704 [indirect_ release];
3708 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3709 if ((self = [super init]) != nil) {
3710 indirect_ = [indirect retain];
3714 - (void) setDelegate:(id)delegate {
3715 delegate_ = delegate;
3718 + (NSArray *) _attributeKeys {
3719 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3722 - (NSArray *) attributeKeys {
3723 return [[self class] _attributeKeys];
3726 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3727 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3730 - (NSString *) device {
3731 return [[UIDevice currentDevice] uniqueIdentifier];
3734 #if 0 // XXX: implement!
3735 - (NSString *) mac {
3736 if (![indirect_ promptForSensitive:@"Mac Address"])
3740 - (NSString *) serial {
3741 if (![indirect_ promptForSensitive:@"Serial #"])
3745 - (NSString *) firewire {
3746 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3750 - (NSString *) imei {
3751 if (![indirect_ promptForSensitive:@"IMEI"])
3756 + (NSString *) webScriptNameForSelector:(SEL)selector {
3757 if (selector == @selector(close))
3759 else if (selector == @selector(getInstalledPackages))
3760 return @"getInstalledPackages";
3761 else if (selector == @selector(getPackageById:))
3762 return @"getPackageById";
3763 else if (selector == @selector(installPackages:))
3764 return @"installPackages";
3765 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3766 return @"setButtonImage";
3767 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3768 return @"setButtonTitle";
3769 else if (selector == @selector(setPopupHook:))
3770 return @"setPopupHook";
3771 else if (selector == @selector(setSpecial:))
3772 return @"setSpecial";
3773 else if (selector == @selector(setToken:))
3775 else if (selector == @selector(setViewportWidth:))
3776 return @"setViewportWidth";
3777 else if (selector == @selector(supports:))
3779 else if (selector == @selector(stringWithFormat:arguments:))
3781 else if (selector == @selector(localizedStringForKey:value:table:))
3783 else if (selector == @selector(du:))
3785 else if (selector == @selector(statfs:))
3791 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3792 return [self webScriptNameForSelector:selector] == nil;
3795 - (BOOL) supports:(NSString *)feature {
3796 return [feature isEqualToString:@"window.open"];
3799 - (NSArray *) getInstalledPackages {
3800 NSArray *packages([[Database sharedInstance] packages]);
3801 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3802 for (Package *package in packages)
3803 if ([package installed] != nil)
3804 [installed addObject:package];
3808 - (Package *) getPackageById:(NSString *)id {
3809 Package *package([[Database sharedInstance] packageWithName:id]);
3814 - (NSArray *) statfs:(NSString *)path {
3817 if (path == nil || statfs([path UTF8String], &stat) == -1)
3820 return [NSArray arrayWithObjects:
3821 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3822 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3823 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3827 - (NSNumber *) du:(NSString *)path {
3828 NSNumber *value(nil);
3831 _assert(pipe(fds) != -1);
3833 pid_t pid(ExecFork());
3835 _assert(dup2(fds[1], 1) != -1);
3836 _assert(close(fds[0]) != -1);
3837 _assert(close(fds[1]) != -1);
3838 /* XXX: this should probably not use du */
3839 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3844 _assert(close(fds[1]) != -1);
3846 if (FILE *du = fdopen(fds[0], "r")) {
3848 while (fgets(line, sizeof(line), du) != NULL) {
3849 size_t length(strlen(line));
3850 while (length != 0 && line[length - 1] == '\n')
3851 line[--length] = '\0';
3852 if (char *tab = strchr(line, '\t')) {
3854 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3859 } else _assert(close(fds[0]));
3863 if (waitpid(pid, &status, 0) == -1)
3866 else _assert(false);
3875 - (void) installPackages:(NSArray *)packages {
3876 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3879 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3880 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3883 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3884 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3887 - (void) setSpecial:(id)function {
3888 [indirect_ setSpecial:function];
3891 - (void) setToken:(NSString *)token {
3894 Token_ = [token retain];
3896 [Metadata_ setObject:Token_ forKey:@"Token"];
3900 - (void) setPopupHook:(id)function {
3901 [indirect_ setPopupHook:function];
3904 - (void) setViewportWidth:(float)width {
3905 [indirect_ setViewportWidth:width];
3908 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3909 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3910 unsigned count([arguments count]);
3912 for (unsigned i(0); i != count; ++i)
3913 values[i] = [arguments objectAtIndex:i];
3914 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3917 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3918 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3920 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3922 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3928 /* Cydia Browser Controller {{{ */
3929 @interface CYBrowserController : BrowserController {
3930 CydiaObject *cydia_;
3935 @implementation CYBrowserController
3942 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3945 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3946 [super webView:view didClearWindowObject:window forFrame:frame];
3948 WebDataSource *source([frame dataSource]);
3949 NSURLResponse *response([source response]);
3950 NSURL *url([response URL]);
3951 NSString *scheme([url scheme]);
3953 NSHTTPURLResponse *http;
3954 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3955 http = (NSHTTPURLResponse *) response;
3959 NSDictionary *headers([http allHeaderFields]);
3960 NSString *host([url host]);
3961 [self setHeaders:headers forHost:host];
3964 [host isEqualToString:@"cydia.saurik.com"] ||
3965 [host hasSuffix:@".cydia.saurik.com"] ||
3966 [scheme isEqualToString:@"file"]
3968 [window setValue:cydia_ forKey:@"cydia"];
3971 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3972 if (System_ != NULL)
3973 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3974 if (Machine_ != NULL)
3975 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3977 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3979 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3982 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3983 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3984 [self _setMoreHeaders:copy];
3988 - (void) setDelegate:(id)delegate {
3989 [super setDelegate:delegate];
3990 [cydia_ setDelegate:delegate];
3994 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3995 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3997 WebView *webview([[webview_ _documentView] webView]);
3999 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4001 NSString *application = package == nil ? @"Cydia" : [NSString
4002 stringWithFormat:@"Cydia/%@",
4007 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4009 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4010 if (Product_ != nil)
4011 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4013 [webview setApplicationNameForUserAgent:application];
4020 /* Confirmation {{{ */
4021 @protocol ConfirmationControllerDelegate
4022 - (void) cancelAndClear:(bool)clear;
4023 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4027 @interface ConfirmationController : CYBrowserController {
4028 _transient Database *database_;
4029 UIAlertView *essential_;
4036 - (id) initWithDatabase:(Database *)database;
4040 @implementation ConfirmationController
4047 if (essential_ != nil)
4048 [essential_ release];
4052 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4053 NSString *context([alert context]);
4055 if ([context isEqualToString:@"remove"]) {
4056 if (button == [alert cancelButtonIndex]) {
4057 [self dismissModalViewControllerAnimated:YES];
4058 } else if (button == [alert firstOtherButtonIndex]) {
4061 [delegate_ confirmWithNavigationController:[self navigationController]];
4064 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4065 } else if ([context isEqualToString:@"unable"]) {
4066 [self dismissModalViewControllerAnimated:YES];
4067 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4069 [super alertView:alert clickedButtonAtIndex:button];
4073 - (void) _doContinue {
4074 [self dismissModalViewControllerAnimated:YES];
4075 [delegate_ cancelAndClear:NO];
4078 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4079 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4083 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4084 [super webView:view didClearWindowObject:window forFrame:frame];
4085 [window setValue:changes_ forKey:@"changes"];
4086 [window setValue:issues_ forKey:@"issues"];
4087 [window setValue:sizes_ forKey:@"sizes"];
4088 [window setValue:self forKey:@"queue"];
4091 - (id) initWithDatabase:(Database *)database {
4092 if ((self = [super init]) != nil) {
4093 database_ = database;
4095 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4097 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4098 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4099 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4100 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4101 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4105 pkgDepCache::Policy *policy([database_ policy]);
4107 pkgCacheFile &cache([database_ cache]);
4108 NSArray *packages = [database_ packages];
4109 for (Package *package in packages) {
4110 pkgCache::PkgIterator iterator = [package iterator];
4111 pkgDepCache::StateCache &state(cache[iterator]);
4113 NSString *name([package name]);
4115 if (state.NewInstall())
4116 [installing addObject:name];
4117 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4118 [reinstalling addObject:name];
4119 else if (state.Upgrade())
4120 [upgrading addObject:name];
4121 else if (state.Downgrade())
4122 [downgrading addObject:name];
4123 else if (state.Delete()) {
4124 if ([package essential])
4126 [removing addObject:name];
4129 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4130 substrate_ |= DepSubstrate(iterator.CurrentVer());
4135 else if (Advanced_) {
4136 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4138 essential_ = [[UIAlertView alloc]
4139 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4140 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4142 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4143 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4146 [essential_ setContext:@"remove"];
4148 essential_ = [[UIAlertView alloc]
4149 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4150 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4152 cancelButtonTitle:UCLocalize("OKAY")
4153 otherButtonTitles:nil
4156 [essential_ setContext:@"unable"];
4159 changes_ = [[NSArray alloc] initWithObjects:
4167 issues_ = [database_ issues];
4169 issues_ = [issues_ retain];
4171 sizes_ = [[NSArray alloc] initWithObjects:
4172 SizeString([database_ fetcher].FetchNeeded()),
4173 SizeString([database_ fetcher].PartialPresent()),
4176 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4178 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4179 initWithTitle:UCLocalize("CANCEL")
4180 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4181 style:UIBarButtonItemStylePlain
4183 action:@selector(cancelButtonClicked)
4188 - (void) applyRightButton {
4189 #if !AlwaysReload && !IgnoreInstall
4190 if (issues_ == nil && ![self isLoading])
4191 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4192 initWithTitle:UCLocalize("CONFIRM")
4193 style:UIBarButtonItemStylePlain
4195 action:@selector(confirmButtonClicked)
4198 [super applyRightButton];
4200 [[self navigationItem] setRightBarButtonItem:nil];
4204 - (void) cancelButtonClicked {
4205 [self dismissModalViewControllerAnimated:YES];
4206 [delegate_ cancelAndClear:YES];
4210 - (void) confirmButtonClicked {
4214 if (essential_ != nil)
4219 [delegate_ confirmWithNavigationController:[self navigationController]];
4227 /* Progress Data {{{ */
4228 @interface ProgressData : NSObject {
4230 // XXX: should these really both be _transient?
4231 _transient id target_;
4232 _transient id object_;
4235 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4242 @implementation ProgressData
4244 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4245 if ((self = [super init]) != nil) {
4246 selector_ = selector;
4266 /* Progress Controller {{{ */
4267 @interface ProgressController : CYViewController <
4268 ConfigurationDelegate,
4271 _transient Database *database_;
4272 UIProgressBar *progress_;
4273 UITextView *output_;
4274 UITextLabel *status_;
4275 UIPushButton *close_;
4277 SHA1SumValue springlist_;
4278 SHA1SumValue notifyconf_;
4282 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4284 - (void) _retachThread;
4285 - (void) _detachNewThreadData:(ProgressData *)data;
4286 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4292 @protocol ProgressControllerDelegate
4293 - (void) progressControllerIsComplete:(ProgressController *)sender;
4296 @implementation ProgressController
4299 [database_ setDelegate:nil];
4300 [progress_ release];
4309 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4310 if ((self = [super init]) != nil) {
4311 database_ = database;
4312 [database_ setDelegate:self];
4313 delegate_ = delegate;
4315 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4317 progress_ = [[UIProgressBar alloc] init];
4318 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4319 [progress_ setStyle:0];
4321 status_ = [[UITextLabel alloc] init];
4322 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4323 [status_ setColor:[UIColor whiteColor]];
4324 [status_ setBackgroundColor:[UIColor clearColor]];
4325 [status_ setCentersHorizontally:YES];
4326 //[status_ setFont:font];
4328 output_ = [[UITextView alloc] init];
4330 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4331 //[output_ setTextFont:@"Courier New"];
4332 [output_ setFont:[[output_ font] fontWithSize:12]];
4333 [output_ setTextColor:[UIColor whiteColor]];
4334 [output_ setBackgroundColor:[UIColor clearColor]];
4335 [output_ setMarginTop:0];
4336 [output_ setAllowsRubberBanding:YES];
4337 [output_ setEditable:NO];
4338 [[self view] addSubview:output_];
4340 close_ = [[UIPushButton alloc] init];
4341 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4342 [close_ setAutosizesToFit:NO];
4343 [close_ setDrawsShadow:YES];
4344 [close_ setStretchBackground:YES];
4345 [close_ setEnabled:YES];
4346 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4347 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4348 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4349 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4353 - (void) positionViews {
4354 CGRect bounds = [[self view] bounds];
4355 CGSize prgsize = [UIProgressBar defaultSize];
4358 (bounds.size.width - prgsize.width) / 2,
4359 bounds.size.height - prgsize.height - 20
4362 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4364 [progress_ setFrame:prgrect];
4365 [status_ setFrame:CGRectMake(
4367 bounds.size.height - prgsize.height - 50,
4368 bounds.size.width - 20,
4371 [output_ setFrame:CGRectMake(
4374 bounds.size.width - 20,
4375 bounds.size.height - 62
4377 [close_ setFrame:CGRectMake(
4378 (bounds.size.width - closewidth) / 2,
4379 bounds.size.height - prgsize.height - 50,
4385 - (void) viewWillAppear:(BOOL)animated {
4386 [super viewDidAppear:animated];
4387 [[self navigationItem] setHidesBackButton:YES];
4388 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4390 [self positionViews];
4393 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4394 [self positionViews];
4397 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4398 NSString *context([alert context]);
4400 if ([context isEqualToString:@"conffile"]) {
4401 FILE *input = [database_ input];
4402 if (button == [alert cancelButtonIndex])
4403 fprintf(input, "N\n");
4404 else if (button == [alert firstOtherButtonIndex])
4405 fprintf(input, "Y\n");
4410 - (void) closeButtonPushed {
4413 UpdateExternalStatus(0);
4417 [self dismissModalViewControllerAnimated:YES];
4421 [delegate_ terminateWithSuccess];
4422 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4423 [delegate_ suspendWithAnimation:YES];
4425 [delegate_ suspend];*/
4429 system("launchctl stop com.apple.SpringBoard");
4433 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4442 - (void) _retachThread {
4443 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4445 [[self view] addSubview:close_];
4446 [progress_ removeFromSuperview];
4447 [status_ removeFromSuperview];
4449 [database_ popErrorWithTitle:title_];
4450 [delegate_ progressControllerIsComplete:self];
4454 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4457 MMap mmap(file, MMap::ReadOnly);
4459 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4460 if (!(notifyconf_ == sha1.Result()))
4467 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4470 MMap mmap(file, MMap::ReadOnly);
4472 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4473 if (!(springlist_ == sha1.Result()))
4479 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4480 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4481 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4482 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4483 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4486 system("su -c /usr/bin/uicache mobile");
4488 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4490 [delegate_ setStatusBarShowsProgress:NO];
4493 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4494 [[data target] performSelector:[data selector] withObject:[data object]];
4495 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4498 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4499 UpdateExternalStatus(1);
4506 title_ = [title retain];
4508 [[self navigationItem] setTitle:title_];
4510 [status_ setText:nil];
4511 [output_ setText:@""];
4512 [progress_ setProgress:0];
4514 [close_ removeFromSuperview];
4515 [[self view] addSubview:progress_];
4516 [[self view] addSubview:status_];
4518 [delegate_ setStatusBarShowsProgress:YES];
4523 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4526 MMap mmap(file, MMap::ReadOnly);
4528 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4529 notifyconf_ = sha1.Result();
4535 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4538 MMap mmap(file, MMap::ReadOnly);
4540 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4541 springlist_ = sha1.Result();
4546 detachNewThreadSelector:@selector(_detachNewThreadData:)
4548 withObject:[[[ProgressData alloc]
4549 initWithSelector:selector
4556 - (void) repairWithSelector:(SEL)selector {
4558 detachNewThreadSelector:selector
4561 title:UCLocalize("REPAIRING")
4565 - (void) setConfigurationData:(NSString *)data {
4567 performSelectorOnMainThread:@selector(_setConfigurationData:)
4573 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4574 CYActionSheet *sheet([[[CYActionSheet alloc]
4576 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4577 defaultButtonIndex:0
4580 [sheet setMessage:error];
4581 [sheet yieldToPopupAlertAnimated:YES];
4585 - (void) setProgressTitle:(NSString *)title {
4587 performSelectorOnMainThread:@selector(_setProgressTitle:)
4593 - (void) setProgressPercent:(float)percent {
4595 performSelectorOnMainThread:@selector(_setProgressPercent:)
4596 withObject:[NSNumber numberWithFloat:percent]
4601 - (void) startProgress {
4604 - (void) addProgressOutput:(NSString *)output {
4606 performSelectorOnMainThread:@selector(_addProgressOutput:)
4612 - (bool) isCancelling:(size_t)received {
4616 - (void) _setConfigurationData:(NSString *)data {
4617 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4619 if (!conffile_r(data)) {
4620 lprintf("E:invalid conffile\n");
4624 NSString *ofile = conffile_r[1];
4625 //NSString *nfile = conffile_r[2];
4627 UIAlertView *alert = [[[UIAlertView alloc]
4628 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4629 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4631 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4632 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4633 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4637 [alert setContext:@"conffile"];
4641 - (void) _setProgressTitle:(NSString *)title {
4642 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4643 for (size_t i(0), e([words count]); i != e; ++i) {
4644 NSString *word([words objectAtIndex:i]);
4645 if (Package *package = [database_ packageWithName:word])
4646 [words replaceObjectAtIndex:i withObject:[package name]];
4649 [status_ setText:[words componentsJoinedByString:@" "]];
4652 - (void) _setProgressPercent:(NSNumber *)percent {
4653 [progress_ setProgress:[percent floatValue]];
4656 - (void) _addProgressOutput:(NSString *)output {
4657 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4658 CGSize size = [output_ contentSize];
4659 CGRect rect = {{0, size.height}, {size.width, 0}};
4660 [output_ scrollRectToVisible:rect animated:YES];
4663 - (BOOL) isRunning {
4670 /* Cell Content View {{{ */
4671 @protocol ContentDelegate
4672 - (void) drawContentRect:(CGRect)rect;
4675 @interface ContentView : UIView {
4676 _transient id<ContentDelegate> delegate_;
4681 @implementation ContentView
4683 - (id) initWithFrame:(CGRect)frame {
4684 if ((self = [super initWithFrame:frame]) != nil) {
4685 [self setNeedsDisplayOnBoundsChange:YES];
4689 - (void) setDelegate:(id<ContentDelegate>)delegate {
4690 delegate_ = delegate;
4693 - (void) drawRect:(CGRect)rect {
4694 [super drawRect:rect];
4695 [delegate_ drawContentRect:rect];
4700 /* Cydia TableView Cell {{{ */
4701 @interface CYTableViewCell : UITableViewCell {
4702 ContentView *content_;
4708 @implementation CYTableViewCell
4715 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4716 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4718 if (view == content_) {
4719 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4720 highlighted_ = highlighted;
4723 [super _updateHighlightColorsForView:view highlighted:highlighted];
4726 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4727 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4728 highlighted_ = selected;
4730 [super setSelected:selected animated:animated];
4731 [content_ setNeedsDisplay];
4736 /* Package Cell {{{ */
4737 @interface PackageCell : CYTableViewCell <
4742 NSString *description_;
4750 - (PackageCell *) init;
4751 - (void) setPackage:(Package *)package;
4753 + (int) heightForPackage:(Package *)package;
4754 - (void) drawContentRect:(CGRect)rect;
4758 @implementation PackageCell
4760 - (void) clearPackage {
4771 if (description_ != nil) {
4772 [description_ release];
4776 if (source_ != nil) {
4781 if (badge_ != nil) {
4786 if (placard_ != nil) {
4796 [self clearPackage];
4800 - (PackageCell *) init {
4801 CGRect frame(CGRectMake(0, 0, 320, 74));
4802 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4803 UIView *content([self contentView]);
4804 CGRect bounds([content bounds]);
4806 content_ = [[ContentView alloc] initWithFrame:bounds];
4807 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4808 [content addSubview:content_];
4810 [content_ setDelegate:self];
4811 [content_ setOpaque:YES];
4815 - (void) _setBackgroundColor {
4817 if (NSString *mode = [package_ mode]) {
4818 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4819 color = remove ? RemovingColor_ : InstallingColor_;
4821 color = [UIColor whiteColor];
4823 [content_ setBackgroundColor:color];
4824 [self setNeedsDisplay];
4827 - (void) setPackage:(Package *)package {
4828 [self clearPackage];
4831 Source *source = [package source];
4833 icon_ = [[package icon] retain];
4834 name_ = [[package name] retain];
4837 description_ = [package longDescription];
4838 if (description_ == nil)
4839 description_ = [package shortDescription];
4840 if (description_ != nil)
4841 description_ = [description_ retain];
4843 commercial_ = [package isCommercial];
4845 package_ = [package retain];
4847 NSString *label = nil;
4848 bool trusted = false;
4850 if (source != nil) {
4851 label = [source label];
4852 trusted = [source trusted];
4853 } else if ([[package id] isEqualToString:@"firmware"])
4854 label = UCLocalize("APPLE");
4856 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4858 NSString *from(label);
4860 NSString *section = [package simpleSection];
4861 if (section != nil && ![section isEqualToString:label]) {
4862 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4863 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4866 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4867 source_ = [from retain];
4869 if (NSString *purpose = [package primaryPurpose])
4870 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4871 badge_ = [badge_ retain];
4873 if ([package installed] != nil)
4874 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4875 placard_ = [placard_ retain];
4877 [self _setBackgroundColor];
4878 [content_ setNeedsDisplay];
4881 - (void) drawContentRect:(CGRect)rect {
4882 bool highlighted(highlighted_);
4883 float width([self bounds].size.width);
4886 CGContextRef context(UIGraphicsGetCurrentContext());
4887 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4888 CGContextFillRect(context, rect);
4893 rect.size = [icon_ size];
4895 rect.size.width /= 2;
4896 rect.size.height /= 2;
4898 rect.origin.x = 25 - rect.size.width / 2;
4899 rect.origin.y = 25 - rect.size.height / 2;
4901 [icon_ drawInRect:rect];
4904 if (badge_ != nil) {
4905 CGSize size = [badge_ size];
4907 [badge_ drawAtPoint:CGPointMake(
4908 36 - size.width / 2,
4909 36 - size.height / 2
4917 UISetColor(commercial_ ? Purple_ : Black_);
4918 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4919 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4922 UISetColor(commercial_ ? Purplish_ : Gray_);
4923 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4925 if (placard_ != nil)
4926 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4929 + (int) heightForPackage:(Package *)package {
4935 /* Section Cell {{{ */
4936 @interface SectionCell : CYTableViewCell <
4948 - (void) setSection:(Section *)section editing:(BOOL)editing;
4952 @implementation SectionCell
4954 - (void) clearSection {
4955 if (basic_ != nil) {
4960 if (section_ != nil) {
4970 if (count_ != nil) {
4977 [self clearSection];
4983 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4984 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4985 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4986 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4987 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4989 UIView *content([self contentView]);
4990 CGRect bounds([content bounds]);
4992 content_ = [[ContentView alloc] initWithFrame:bounds];
4993 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4994 [content addSubview:content_];
4995 [content_ setBackgroundColor:[UIColor whiteColor]];
4997 [content_ setDelegate:self];
5001 - (void) onSwitch:(id)sender {
5002 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5003 if (metadata == nil) {
5004 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5005 [Sections_ setObject:metadata forKey:basic_];
5008 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5012 - (void) setSection:(Section *)section editing:(BOOL)editing {
5013 if (editing != editing_) {
5015 [switch_ removeFromSuperview];
5017 [self addSubview:switch_];
5021 [self clearSection];
5023 if (section == nil) {
5024 name_ = [UCLocalize("ALL_PACKAGES") retain];
5027 basic_ = [section name];
5029 basic_ = [basic_ retain];
5031 section_ = [section localized];
5032 if (section_ != nil)
5033 section_ = [section_ retain];
5035 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5036 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5039 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5042 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5043 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5045 [content_ setNeedsDisplay];
5048 - (void) setFrame:(CGRect)frame {
5049 [super setFrame:frame];
5051 CGRect rect([switch_ frame]);
5052 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5055 - (void) drawContentRect:(CGRect)rect {
5056 bool highlighted(highlighted_);
5058 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5063 float width(rect.size.width);
5069 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5071 CGSize size = [count_ sizeWithFont:Font14_];
5075 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5081 /* File Table {{{ */
5082 @interface FileTable : CYViewController <
5083 UITableViewDataSource,
5086 _transient Database *database_;
5089 NSMutableArray *files_;
5093 - (id) initWithDatabase:(Database *)database;
5094 - (void) setPackage:(Package *)package;
5098 @implementation FileTable
5101 if (package_ != nil)
5110 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5111 return files_ == nil ? 0 : [files_ count];
5114 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5118 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5119 static NSString *reuseIdentifier = @"Cell";
5121 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5123 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5124 [cell setFont:[UIFont systemFontOfSize:16]];
5126 [cell setText:[files_ objectAtIndex:indexPath.row]];
5127 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5132 - (id) initWithDatabase:(Database *)database {
5133 if ((self = [super init]) != nil) {
5134 database_ = database;
5136 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5138 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5140 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5141 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5142 [list_ setRowHeight:24.0f];
5143 [[self view] addSubview:list_];
5145 [list_ setDataSource:self];
5146 [list_ setDelegate:self];
5150 - (void) setPackage:(Package *)package {
5151 if (package_ != nil) {
5152 [package_ autorelease];
5161 [files_ removeAllObjects];
5163 if (package != nil) {
5164 package_ = [package retain];
5165 name_ = [[package id] retain];
5167 if (NSArray *files = [package files])
5168 [files_ addObjectsFromArray:files];
5170 if ([files_ count] != 0) {
5171 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5172 [files_ removeObjectAtIndex:0];
5173 [files_ sortUsingSelector:@selector(compareByPath:)];
5175 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5176 [stack addObject:@"/"];
5178 for (int i(0), e([files_ count]); i != e; ++i) {
5179 NSString *file = [files_ objectAtIndex:i];
5180 while (![file hasPrefix:[stack lastObject]])
5181 [stack removeLastObject];
5182 NSString *directory = [stack lastObject];
5183 [stack addObject:[file stringByAppendingString:@"/"]];
5184 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5185 ([stack count] - 2) * 3, "",
5186 [file substringFromIndex:[directory length]]
5195 - (void) reloadData {
5196 [self setPackage:[database_ packageWithName:name_]];
5201 /* Package Controller {{{ */
5202 @interface PackageController : CYBrowserController <
5203 UIActionSheetDelegate
5205 _transient Database *database_;
5209 NSMutableArray *buttons_;
5210 UIBarButtonItem *button_;
5213 - (id) initWithDatabase:(Database *)database;
5214 - (void) setPackage:(Package *)package;
5218 @implementation PackageController
5221 if (package_ != nil)
5235 if ([self retainCount] == 1)
5236 [delegate_ setPackageController:self];
5240 /* XXX: this is not safe at all... localization of /fail/ */
5241 - (void) _clickButtonWithName:(NSString *)name {
5242 if ([name isEqualToString:UCLocalize("CLEAR")])
5243 [delegate_ clearPackage:package_];
5244 else if ([name isEqualToString:UCLocalize("INSTALL")])
5245 [delegate_ installPackage:package_];
5246 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5247 [delegate_ installPackage:package_];
5248 else if ([name isEqualToString:UCLocalize("REMOVE")])
5249 [delegate_ removePackage:package_];
5250 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5251 [delegate_ installPackage:package_];
5252 else _assert(false);
5255 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5256 NSString *context([sheet context]);
5258 if ([context isEqualToString:@"modify"]) {
5259 if (button != [sheet cancelButtonIndex]) {
5260 NSString *buttonName = [buttons_ objectAtIndex:button];
5261 [self _clickButtonWithName:buttonName];
5264 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5268 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5269 [super webView:view didClearWindowObject:window forFrame:frame];
5270 [window setValue:package_ forKey:@"package"];
5273 - (bool) _allowJavaScriptPanel {
5278 - (void) _customButtonClicked {
5279 int count([buttons_ count]);
5284 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5286 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5287 [buttons addObjectsFromArray:buttons_];
5289 UIActionSheet *sheet = [[[UIActionSheet alloc]
5292 cancelButtonTitle:nil
5293 destructiveButtonTitle:nil
5294 otherButtonTitles:nil
5297 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5299 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5300 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5302 [sheet setContext:@"modify"];
5304 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5308 // We don't want to allow non-commercial packages to do custom things to the install button,
5309 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5310 - (void) customButtonClicked {
5312 [super customButtonClicked];
5314 [self _customButtonClicked];
5317 - (void) reloadButtonClicked {
5318 // Don't reload a package view by clicking the button.
5321 - (void) applyLoadingTitle {
5322 // Don't show "Loading" as the title. Ever.
5325 - (UIBarButtonItem *) rightButton {
5330 - (id) initWithDatabase:(Database *)database {
5331 if ((self = [super init]) != nil) {
5332 database_ = database;
5333 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5334 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5338 - (void) setPackage:(Package *)package {
5339 if (package_ != nil) {
5340 [package_ autorelease];
5349 [buttons_ removeAllObjects];
5351 if (package != nil) {
5354 package_ = [package retain];
5355 name_ = [[package id] retain];
5356 commercial_ = [package isCommercial];
5358 if ([package_ mode] != nil)
5359 [buttons_ addObject:UCLocalize("CLEAR")];
5360 if ([package_ source] == nil);
5361 else if ([package_ upgradableAndEssential:NO])
5362 [buttons_ addObject:UCLocalize("UPGRADE")];
5363 else if ([package_ uninstalled])
5364 [buttons_ addObject:UCLocalize("INSTALL")];
5366 [buttons_ addObject:UCLocalize("REINSTALL")];
5367 if (![package_ uninstalled])
5368 [buttons_ addObject:UCLocalize("REMOVE")];
5375 switch ([buttons_ count]) {
5376 case 0: title = nil; break;
5377 case 1: title = [buttons_ objectAtIndex:0]; break;
5378 default: title = UCLocalize("MODIFY"); break;
5381 button_ = [[UIBarButtonItem alloc]
5383 style:UIBarButtonItemStylePlain
5385 action:@selector(customButtonClicked)
5391 - (bool) isLoading {
5392 return commercial_ ? [super isLoading] : false;
5395 - (void) reloadData {
5396 [self setPackage:[database_ packageWithName:name_]];
5401 /* Package Table {{{ */
5402 @interface PackageTable : UIView <
5403 UITableViewDataSource,
5406 _transient Database *database_;
5407 NSMutableArray *packages_;
5408 NSMutableArray *sections_;
5410 NSMutableArray *index_;
5411 NSMutableDictionary *indices_;
5412 // XXX: this target_ seems to be delegate_. :(
5413 _transient id target_;
5415 // XXX: why do we even have this delegate_?
5416 _transient id delegate_;
5419 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5421 - (void) setDelegate:(id)delegate;
5423 - (void) reloadData;
5424 - (void) resetCursor;
5426 - (UITableView *) list;
5428 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5430 - (void) deselectWithAnimation:(BOOL)animated;
5434 @implementation PackageTable
5437 [packages_ release];
5438 [sections_ release];
5446 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5447 NSInteger count([sections_ count]);
5448 return count == 0 ? 1 : count;
5451 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5452 if ([sections_ count] == 0)
5454 return [[sections_ objectAtIndex:section] name];
5457 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5458 if ([sections_ count] == 0)
5460 return [[sections_ objectAtIndex:section] count];
5463 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5464 Section *section([sections_ objectAtIndex:[path section]]);
5465 NSInteger row([path row]);
5466 Package *package([packages_ objectAtIndex:([section row] + row)]);
5470 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5471 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5473 cell = [[[PackageCell alloc] init] autorelease];
5474 [cell setPackage:[self packageAtIndexPath:path]];
5478 - (void) deselectWithAnimation:(BOOL)animated {
5479 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5482 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5483 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5486 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5487 Package *package([self packageAtIndexPath:path]);
5488 package = [database_ packageWithName:[package id]];
5489 [target_ performSelector:action_ withObject:package];
5493 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5494 return [packages_ count] > 20 ? index_ : nil;
5497 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5501 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5502 if ((self = [super initWithFrame:frame]) != nil) {
5503 database_ = database;
5508 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5509 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5511 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5512 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5514 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5515 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5516 [list_ setRowHeight:73.0f];
5517 [self addSubview:list_];
5519 [list_ setDataSource:self];
5520 [list_ setDelegate:self];
5524 - (void) setDelegate:(id)delegate {
5525 delegate_ = delegate;
5528 - (bool) hasPackage:(Package *)package {
5532 - (void) reloadData {
5533 NSArray *packages = [database_ packages];
5535 [packages_ removeAllObjects];
5536 [sections_ removeAllObjects];
5538 _profile(PackageTable$reloadData$Filter)
5539 for (Package *package in packages)
5540 if ([self hasPackage:package])
5541 [packages_ addObject:package];
5544 [index_ removeAllObjects];
5545 [indices_ removeAllObjects];
5547 Section *section = nil;
5549 _profile(PackageTable$reloadData$Section)
5550 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5554 _profile(PackageTable$reloadData$Section$Package)
5555 package = [packages_ objectAtIndex:offset];
5556 index = [package index];
5559 if (section == nil || [section index] != index) {
5560 _profile(PackageTable$reloadData$Section$Allocate)
5561 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5564 [index_ addObject:[section name]];
5565 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5567 _profile(PackageTable$reloadData$Section$Add)
5568 [sections_ addObject:section];
5572 [section addToCount];
5576 _profile(PackageTable$reloadData$List)
5581 - (void) resetCursor {
5582 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5585 - (UITableView *) list {
5589 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5590 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5595 /* Filtered Package Table {{{ */
5596 @interface FilteredPackageTable : PackageTable {
5602 - (void) setObject:(id)object;
5603 - (void) setObject:(id)object forFilter:(SEL)filter;
5605 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5609 @implementation FilteredPackageTable
5617 - (void) setFilter:(SEL)filter {
5620 /* XXX: this is an unsafe optimization of doomy hell */
5621 Method method(class_getInstanceMethod([Package class], filter));
5622 _assert(method != NULL);
5623 imp_ = method_getImplementation(method);
5624 _assert(imp_ != NULL);
5627 - (void) setObject:(id)object {
5633 object_ = [object retain];
5636 - (void) setObject:(id)object forFilter:(SEL)filter {
5637 [self setFilter:filter];
5638 [self setObject:object];
5641 - (bool) hasPackage:(Package *)package {
5642 _profile(FilteredPackageTable$hasPackage)
5643 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5647 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5648 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5649 [self setFilter:filter];
5650 object_ = [object retain];
5658 /* Filtered Package Controller {{{ */
5659 @interface FilteredPackageController : CYViewController {
5660 _transient Database *database_;
5661 FilteredPackageTable *packages_;
5665 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5669 @implementation FilteredPackageController
5672 [packages_ release];
5678 - (void) viewDidAppear:(BOOL)animated {
5679 [super viewDidAppear:animated];
5680 [packages_ deselectWithAnimation:animated];
5683 - (void) didSelectPackage:(Package *)package {
5684 PackageController *view([delegate_ packageController]);
5685 [view setPackage:package];
5686 [view setDelegate:delegate_];
5687 [[self navigationController] pushViewController:view animated:YES];
5690 - (NSString *) title { return title_; }
5692 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5693 if ((self = [super init]) != nil) {
5694 database_ = database;
5695 title_ = [title copy];
5696 [[self navigationItem] setTitle:title_];
5698 packages_ = [[FilteredPackageTable alloc]
5699 initWithFrame:[[self view] bounds]
5702 action:@selector(didSelectPackage:)
5707 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5708 [[self view] addSubview:packages_];
5712 - (void) reloadData {
5713 [packages_ reloadData];
5716 - (void) setDelegate:(id)delegate {
5717 [super setDelegate:delegate];
5718 [packages_ setDelegate:delegate];
5725 /* Add Source Controller {{{ */
5726 @interface AddSourceController : CYViewController {
5727 _transient Database *database_;
5730 - (id) initWithDatabase:(Database *)database;
5734 @implementation AddSourceController
5736 - (id) initWithDatabase:(Database *)database {
5737 if ((self = [super init]) != nil) {
5738 database_ = database;
5744 /* Source Cell {{{ */
5745 @interface SourceCell : CYTableViewCell <
5750 NSString *description_;
5754 - (void) setSource:(Source *)source;
5758 @implementation SourceCell
5760 - (void) clearSource {
5763 [description_ release];
5772 - (void) setSource:(Source *)source {
5776 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5778 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5779 icon_ = [icon_ retain];
5781 origin_ = [[source name] retain];
5782 label_ = [[source uri] retain];
5783 description_ = [[source description] retain];
5785 [content_ setNeedsDisplay];
5793 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5794 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5795 UIView *content([self contentView]);
5796 CGRect bounds([content bounds]);
5798 content_ = [[ContentView alloc] initWithFrame:bounds];
5799 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5800 [content_ setBackgroundColor:[UIColor whiteColor]];
5801 [content addSubview:content_];
5803 [content_ setDelegate:self];
5804 [content_ setOpaque:YES];
5808 - (void) drawContentRect:(CGRect)rect {
5809 bool highlighted(highlighted_);
5810 float width(rect.size.width);
5813 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5820 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5824 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5828 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5833 /* Source Table {{{ */
5834 @interface SourceTable : CYViewController <
5835 UITableViewDataSource,
5838 _transient Database *database_;
5840 NSMutableArray *sources_;
5844 UIProgressHUD *hud_;
5847 //NSURLConnection *installer_;
5848 NSURLConnection *trivial_;
5849 NSURLConnection *trivial_bz2_;
5850 NSURLConnection *trivial_gz_;
5851 //NSURLConnection *automatic_;
5856 - (id) initWithDatabase:(Database *)database;
5858 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5862 @implementation SourceTable
5864 - (void) _releaseConnection:(NSURLConnection *)connection {
5865 if (connection != nil) {
5866 [connection cancel];
5867 //[connection setDelegate:nil];
5868 [connection release];
5880 //[self _releaseConnection:installer_];
5881 [self _releaseConnection:trivial_];
5882 [self _releaseConnection:trivial_gz_];
5883 [self _releaseConnection:trivial_bz2_];
5884 //[self _releaseConnection:automatic_];
5891 - (void) viewDidAppear:(BOOL)animated {
5892 [super viewDidAppear:animated];
5893 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5896 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5897 return offset_ == 0 ? 1 : 2;
5900 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5901 switch (section + (offset_ == 0 ? 1 : 0)) {
5902 case 0: return UCLocalize("ENTERED_BY_USER");
5903 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5909 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5910 int count = [sources_ count];
5912 case 0: return (offset_ == 0 ? count : offset_);
5913 case 1: return count - offset_;
5919 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5921 switch (indexPath.section) {
5922 case 0: idx = indexPath.row; break;
5923 case 1: idx = indexPath.row + offset_; break;
5927 return [sources_ objectAtIndex:idx];
5930 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5931 Source *source = [self sourceAtIndexPath:indexPath];
5932 return [source description] == nil ? 56 : 73;
5935 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5936 static NSString *cellIdentifier = @"SourceCell";
5938 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5939 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5940 [cell setSource:[self sourceAtIndexPath:indexPath]];
5945 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5946 return UITableViewCellAccessoryDisclosureIndicator;
5949 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5950 Source *source = [self sourceAtIndexPath:indexPath];
5952 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5953 initWithDatabase:database_
5954 title:[source label]
5955 filter:@selector(isVisibleInSource:)
5959 [packages setDelegate:delegate_];
5961 [[self navigationController] pushViewController:packages animated:YES];
5964 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5965 Source *source = [self sourceAtIndexPath:indexPath];
5966 return [source record] != nil;
5969 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5970 Source *source = [self sourceAtIndexPath:indexPath];
5971 [Sources_ removeObjectForKey:[source key]];
5972 [delegate_ syncData];
5976 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5979 @"./", @"Distribution",
5980 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5982 [delegate_ syncData];
5985 - (NSString *) getWarning {
5986 NSString *href(href_);
5987 NSRange colon([href rangeOfString:@"://"]);
5988 if (colon.location != NSNotFound)
5989 href = [href substringFromIndex:(colon.location + 3)];
5990 href = [href stringByAddingPercentEscapes];
5991 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5992 href = [href stringByCachingURLWithCurrentCDN];
5994 NSURL *url([NSURL URLWithString:href]);
5996 NSStringEncoding encoding;
5997 NSError *error(nil);
5999 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
6000 return [warning length] == 0 ? nil : warning;
6004 - (void) _endConnection:(NSURLConnection *)connection {
6005 // XXX: the memory management in this method is horribly awkward
6007 NSURLConnection **field = NULL;
6008 if (connection == trivial_)
6010 else if (connection == trivial_bz2_)
6011 field = &trivial_bz2_;
6012 else if (connection == trivial_gz_)
6013 field = &trivial_gz_;
6014 _assert(field != NULL);
6015 [connection release];
6020 trivial_bz2_ == nil &&
6026 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6029 UIAlertView *alert = [[[UIAlertView alloc]
6030 initWithTitle:UCLocalize("SOURCE_WARNING")
6033 cancelButtonTitle:UCLocalize("CANCEL")
6034 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6037 [alert setContext:@"warning"];
6038 [alert setNumberOfRows:1];
6042 } else if (error_ != nil) {
6043 UIAlertView *alert = [[[UIAlertView alloc]
6044 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6045 message:[error_ localizedDescription]
6047 cancelButtonTitle:UCLocalize("OK")
6048 otherButtonTitles:nil
6051 [alert setContext:@"urlerror"];
6054 UIAlertView *alert = [[[UIAlertView alloc]
6055 initWithTitle:UCLocalize("NOT_REPOSITORY")
6056 message:UCLocalize("NOT_REPOSITORY_EX")
6058 cancelButtonTitle:UCLocalize("OK")
6059 otherButtonTitles:nil
6062 [alert setContext:@"trivial"];
6066 [delegate_ setStatusBarShowsProgress:NO];
6067 [delegate_ removeProgressHUD:hud_];
6077 if (error_ != nil) {
6084 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6085 switch ([response statusCode]) {
6091 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6092 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6094 error_ = [error retain];
6095 [self _endConnection:connection];
6098 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6099 [self _endConnection:connection];
6102 - (NSString *) title { return UCLocalize("SOURCES"); }
6104 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6105 NSMutableURLRequest *request = [NSMutableURLRequest
6106 requestWithURL:[NSURL URLWithString:href]
6107 cachePolicy:NSURLRequestUseProtocolCachePolicy
6108 timeoutInterval:120.0
6111 [request setHTTPMethod:method];
6113 if (Machine_ != NULL)
6114 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6115 if (UniqueID_ != nil)
6116 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6118 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6120 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6123 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6124 NSString *context([alert context]);
6126 if ([context isEqualToString:@"source"]) {
6129 NSString *href = [[alert textField] text];
6131 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6133 if (![href hasSuffix:@"/"])
6134 href_ = [href stringByAppendingString:@"/"];
6137 href_ = [href_ retain];
6139 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6140 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6141 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6142 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6146 // XXX: this is stupid
6147 hud_ = [[delegate_ addProgressHUD] retain];
6148 [hud_ setText:UCLocalize("VERIFYING_URL")];
6157 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6158 } else if ([context isEqualToString:@"trivial"])
6159 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6160 else if ([context isEqualToString:@"urlerror"])
6161 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6162 else if ([context isEqualToString:@"warning"]) {
6177 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6181 - (id) initWithDatabase:(Database *)database {
6182 if ((self = [super init]) != nil) {
6183 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6184 [self updateButtonsForEditingStatus:NO animated:NO];
6186 database_ = database;
6187 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6189 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6190 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6191 [[self view] addSubview:list_];
6193 [list_ setDataSource:self];
6194 [list_ setDelegate:self];
6200 - (void) reloadData {
6202 if (!list.ReadMainList())
6205 [sources_ removeAllObjects];
6206 [sources_ addObjectsFromArray:[database_ sources]];
6208 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6211 int count([sources_ count]);
6213 for (int i = 0; i != count; i++) {
6214 if ([[sources_ objectAtIndex:i] record] == nil)
6219 [list_ setEditing:NO];
6220 [self updateButtonsForEditingStatus:NO animated:NO];
6224 - (void) addButtonClicked {
6225 /*[book_ pushPage:[[[AddSourceController alloc]
6230 UIAlertView *alert = [[[UIAlertView alloc]
6231 initWithTitle:UCLocalize("ENTER_APT_URL")
6234 cancelButtonTitle:UCLocalize("CANCEL")
6235 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6238 [alert setContext:@"source"];
6239 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6241 [alert setNumberOfRows:1];
6242 [alert addTextFieldWithValue:@"http://" label:@""];
6244 UITextInputTraits *traits = [[alert textField] textInputTraits];
6245 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6246 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6247 [traits setKeyboardType:UIKeyboardTypeURL];
6248 // XXX: UIReturnKeyDone
6249 [traits setReturnKeyType:UIReturnKeyNext];
6254 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6255 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6256 initWithTitle:UCLocalize("ADD")
6257 style:UIBarButtonItemStylePlain
6259 action:@selector(addButtonClicked)
6260 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6262 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6263 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6264 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6266 action:@selector(editButtonClicked)
6267 ] autorelease] animated:animated];
6269 if (IsWildcat_ && !editing)
6270 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6271 initWithTitle:UCLocalize("SETTINGS")
6272 style:UIBarButtonItemStylePlain
6274 action:@selector(settingsButtonClicked)
6278 - (void) settingsButtonClicked {
6279 [delegate_ showSettings];
6282 - (void) editButtonClicked {
6283 [list_ setEditing:![list_ isEditing] animated:YES];
6285 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6291 /* Installed Controller {{{ */
6292 @interface InstalledController : FilteredPackageController {
6296 - (id) initWithDatabase:(Database *)database;
6298 - (void) updateRoleButton;
6299 - (void) queueStatusDidChange;
6303 @implementation InstalledController
6309 - (NSString *) title { return UCLocalize("INSTALLED"); }
6311 - (id) initWithDatabase:(Database *)database {
6312 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6313 [self updateRoleButton];
6314 [self queueStatusDidChange];
6319 - (void) queueButtonClicked {
6324 - (void) queueStatusDidChange {
6328 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6329 initWithTitle:UCLocalize("QUEUE")
6330 style:UIBarButtonItemStyleDone
6332 action:@selector(queueButtonClicked)
6335 [[self navigationItem] setLeftBarButtonItem:nil];
6341 - (void) reloadData {
6342 [packages_ reloadData];
6345 - (void) updateRoleButton {
6346 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6347 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6348 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6349 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6351 action:@selector(roleButtonClicked)
6355 - (void) roleButtonClicked {
6356 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6357 [packages_ reloadData];
6360 [self updateRoleButton];
6363 - (void) setDelegate:(id)delegate {
6364 [super setDelegate:delegate];
6365 [packages_ setDelegate:delegate];
6371 /* Home Controller {{{ */
6372 @interface HomeController : CYBrowserController {
6377 @implementation HomeController
6379 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6380 [super _setMoreHeaders:request];
6383 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6384 if (UniqueID_ != nil)
6385 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6387 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6390 - (void) aboutButtonClicked {
6391 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6393 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6394 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6395 [alert setCancelButtonIndex:0];
6398 @"Copyright (C) 2008-2010\n"
6399 "Jay Freeman (saurik)\n"
6400 "saurik@saurik.com\n"
6401 "http://www.saurik.com/"
6407 - (void) viewWillAppear:(BOOL)animated {
6408 [super viewWillAppear:animated];
6409 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6412 - (void) viewWillDisappear:(BOOL)animated {
6413 [super viewWillDisappear:animated];
6414 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6418 if ((self = [super init]) != nil) {
6419 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6420 initWithTitle:UCLocalize("ABOUT")
6421 style:UIBarButtonItemStylePlain
6423 action:@selector(aboutButtonClicked)
6430 /* Manage Controller {{{ */
6431 @interface ManageController : CYBrowserController {
6434 - (void) queueStatusDidChange;
6437 @implementation ManageController
6440 if ((self = [super init]) != nil) {
6441 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6443 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6444 initWithTitle:UCLocalize("SETTINGS")
6445 style:UIBarButtonItemStylePlain
6447 action:@selector(settingsButtonClicked)
6450 [self queueStatusDidChange];
6454 - (void) settingsButtonClicked {
6455 [delegate_ showSettings];
6459 - (void) queueButtonClicked {
6463 - (void) applyLoadingTitle {
6464 // No "Loading" title.
6467 - (void) applyRightButton {
6472 - (void) queueStatusDidChange {
6474 if (!IsWildcat_ && Queuing_) {
6475 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6476 initWithTitle:UCLocalize("QUEUE")
6477 style:UIBarButtonItemStyleDone
6479 action:@selector(queueButtonClicked)
6482 [[self navigationItem] setRightBarButtonItem:nil];
6487 - (bool) isLoading {
6494 /* Refresh Bar {{{ */
6495 @interface RefreshBar : UINavigationBar {
6496 UIProgressIndicator *indicator_;
6497 UITextLabel *prompt_;
6498 UIProgressBar *progress_;
6499 UINavigationButton *cancel_;
6504 @implementation RefreshBar
6507 [indicator_ release];
6509 [progress_ release];
6514 - (void) positionViews {
6515 CGRect frame = [cancel_ frame];
6516 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6517 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6518 [cancel_ setFrame:frame];
6520 CGSize prgsize = {75, 100};
6522 [self frame].size.width - prgsize.width - 10,
6523 ([self frame].size.height - prgsize.height) / 2
6525 [progress_ setFrame:prgrect];
6527 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6528 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6529 CGRect indrect = {{indoffset, indoffset}, indsize};
6530 [indicator_ setFrame:indrect];
6532 CGSize prmsize = {215, indsize.height + 4};
6534 indoffset * 2 + indsize.width,
6535 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6537 [prompt_ setFrame:prmrect];
6540 - (void)setFrame:(CGRect)frame {
6541 [super setFrame:frame];
6543 [self positionViews];
6546 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6547 if ((self = [super initWithFrame:frame])) {
6548 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6550 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6551 [self setBarStyle:UIBarStyleBlack];
6553 UIBarStyle barstyle([self _barStyle:NO]);
6554 bool ugly(barstyle == UIBarStyleDefault);
6556 UIProgressIndicatorStyle style = ugly ?
6557 UIProgressIndicatorStyleMediumBrown :
6558 UIProgressIndicatorStyleMediumWhite;
6560 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6561 [indicator_ setStyle:style];
6562 [indicator_ startAnimation];
6563 [self addSubview:indicator_];
6565 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6566 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6567 [prompt_ setBackgroundColor:[UIColor clearColor]];
6568 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6569 [self addSubview:prompt_];
6571 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6572 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6573 [progress_ setStyle:0];
6574 [self addSubview:progress_];
6576 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6577 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6578 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6579 [cancel_ setBarStyle:barstyle];
6581 [self positionViews];
6586 [cancel_ removeFromSuperview];
6590 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6591 [progress_ setProgress:0];
6592 [self addSubview:cancel_];
6596 [cancel_ removeFromSuperview];
6599 - (void) setPrompt:(NSString *)prompt {
6600 [prompt_ setText:prompt];
6603 - (void) setProgress:(float)progress {
6604 [progress_ setProgress:progress];
6610 @class CYNavigationController;
6612 /* Cydia Tab Bar Controller {{{ */
6613 @interface CYTabBarController : UITabBarController {
6614 _transient Database *database_;
6619 @implementation CYTabBarController
6621 /* XXX: some logic should probably go here related to
6622 freeing the view controllers on tab change */
6624 - (void) reloadData {
6625 size_t count([[self viewControllers] count]);
6626 for (size_t i(0); i != count; ++i) {
6627 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6632 - (id) initWithDatabase:(Database *)database {
6633 if ((self = [super init]) != nil) {
6634 database_ = database;
6641 /* Cydia Navigation Controller {{{ */
6642 @interface CYNavigationController : UINavigationController {
6643 _transient Database *database_;
6644 _transient id<UINavigationControllerDelegate> delegate_;
6647 - (id) initWithDatabase:(Database *)database;
6648 - (void) reloadData;
6653 @implementation CYNavigationController
6655 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6656 // Inherit autorotation settings for modal parents.
6657 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6658 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6660 return [super shouldAutorotateToInterfaceOrientation:orientation];
6668 - (void) reloadData {
6669 size_t count([[self viewControllers] count]);
6670 for (size_t i(0); i != count; ++i) {
6671 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6676 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6677 delegate_ = delegate;
6680 - (id) initWithDatabase:(Database *)database {
6681 if ((self = [super init]) != nil) {
6682 database_ = database;
6688 /* Cydia:// Protocol {{{ */
6689 @interface CydiaURLProtocol : NSURLProtocol {
6694 @implementation CydiaURLProtocol
6696 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6697 NSURL *url([request URL]);
6700 NSString *scheme([[url scheme] lowercaseString]);
6701 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6706 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6710 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6711 id<NSURLProtocolClient> client([self client]);
6713 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6715 NSData *data(UIImagePNGRepresentation(icon));
6717 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6718 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6719 [client URLProtocol:self didLoadData:data];
6720 [client URLProtocolDidFinishLoading:self];
6724 - (void) startLoading {
6725 id<NSURLProtocolClient> client([self client]);
6726 NSURLRequest *request([self request]);
6728 NSURL *url([request URL]);
6729 NSString *href([url absoluteString]);
6731 NSString *path([href substringFromIndex:8]);
6732 NSRange slash([path rangeOfString:@"/"]);
6735 if (slash.location == NSNotFound) {
6739 command = [path substringToIndex:slash.location];
6740 path = [path substringFromIndex:(slash.location + 1)];
6743 Database *database([Database sharedInstance]);
6745 if ([command isEqualToString:@"package-icon"]) {
6748 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6749 Package *package([database packageWithName:path]);
6752 UIImage *icon([package icon]);
6753 [self _returnPNGWithImage:icon forRequest:request];
6754 } else if ([command isEqualToString:@"source-icon"]) {
6757 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6758 NSString *source(Simplify(path));
6759 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6761 icon = [UIImage applicationImageNamed:@"unknown.png"];
6762 [self _returnPNGWithImage:icon forRequest:request];
6763 } else if ([command isEqualToString:@"uikit-image"]) {
6766 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6767 UIImage *icon(_UIImageWithName(path));
6768 [self _returnPNGWithImage:icon forRequest:request];
6769 } else if ([command isEqualToString:@"section-icon"]) {
6772 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6773 NSString *section(Simplify(path));
6774 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6776 icon = [UIImage applicationImageNamed:@"unknown.png"];
6777 [self _returnPNGWithImage:icon forRequest:request];
6779 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6783 - (void) stopLoading {
6789 /* Sections Controller {{{ */
6790 @interface SectionsController : CYViewController <
6791 UITableViewDataSource,
6794 _transient Database *database_;
6795 NSMutableArray *sections_;
6796 NSMutableArray *filtered_;
6802 - (id) initWithDatabase:(Database *)database;
6803 - (void) reloadData;
6806 - (void) editButtonClicked;
6810 @implementation SectionsController
6813 [list_ setDataSource:nil];
6814 [list_ setDelegate:nil];
6816 [sections_ release];
6817 [filtered_ release];
6819 [accessory_ release];
6823 - (void) viewDidAppear:(BOOL)animated {
6824 [super viewDidAppear:animated];
6825 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6828 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6829 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6833 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6834 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6837 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6841 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6842 static NSString *reuseIdentifier = @"SectionCell";
6844 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6846 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6848 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6853 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6857 Section *section = [self sectionAtIndexPath:indexPath];
6858 NSString *name = [section name];
6861 if ([indexPath row] == 0) {
6864 title = UCLocalize("ALL_PACKAGES");
6867 name = [NSString stringWithString:name];
6868 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6871 title = UCLocalize("NO_SECTION");
6875 FilteredPackageController *table = [[[FilteredPackageController alloc]
6876 initWithDatabase:database_
6878 filter:@selector(isVisibleInSection:)
6882 [table setDelegate:delegate_];
6884 [[self navigationController] pushViewController:table animated:YES];
6887 - (NSString *) title { return UCLocalize("SECTIONS"); }
6889 - (id) initWithDatabase:(Database *)database {
6890 if ((self = [super init]) != nil) {
6891 database_ = database;
6893 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6895 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6896 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6898 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6899 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6900 [list_ setRowHeight:45.0f];
6901 [[self view] addSubview:list_];
6903 [list_ setDataSource:self];
6904 [list_ setDelegate:self];
6910 - (void) reloadData {
6911 NSArray *packages = [database_ packages];
6913 [sections_ removeAllObjects];
6914 [filtered_ removeAllObjects];
6916 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6919 for (Package *package in packages) {
6920 NSString *name([package section]);
6921 NSString *key(name == nil ? @"" : name);
6925 _profile(SectionsView$reloadData$Section)
6926 section = [sections objectForKey:key];
6927 if (section == nil) {
6928 _profile(SectionsView$reloadData$Section$Allocate)
6929 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6930 [sections setObject:section forKey:key];
6935 [section addToCount];
6937 _profile(SectionsView$reloadData$Filter)
6938 if (![package valid] || ![package visible])
6946 [sections_ addObjectsFromArray:[sections allValues]];
6948 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6950 for (Section *section in sections_) {
6951 size_t count([section row]);
6955 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6956 [section setCount:count];
6957 [filtered_ addObject:section];
6960 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6961 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
6962 style:UIBarButtonItemStylePlain
6964 action:@selector(editButtonClicked)
6965 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6971 - (void) resetView {
6973 [self editButtonClicked];
6976 - (void) editButtonClicked {
6977 if ((editing_ = !editing_))
6980 [delegate_ updateData];
6982 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6983 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6984 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6987 - (UIView *) accessoryView {
6993 /* Changes Controller {{{ */
6994 @interface ChangesController : CYViewController <
6995 UITableViewDataSource,
6998 _transient Database *database_;
6999 CFMutableArrayRef packages_;
7000 NSMutableArray *sections_;
7003 BOOL hasSentFirstLoad_;
7006 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
7007 - (void) reloadData;
7011 @implementation ChangesController
7014 [list_ setDelegate:nil];
7015 [list_ setDataSource:nil];
7017 CFRelease(packages_);
7019 [sections_ release];
7024 - (void) viewDidAppear:(BOOL)animated {
7025 [super viewDidAppear:animated];
7026 if (!hasSentFirstLoad_) {
7027 hasSentFirstLoad_ = YES;
7028 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7030 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7034 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7035 NSInteger count([sections_ count]);
7036 return count == 0 ? 1 : count;
7039 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7040 if ([sections_ count] == 0)
7042 return [[sections_ objectAtIndex:section] name];
7045 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7046 if ([sections_ count] == 0)
7048 return [[sections_ objectAtIndex:section] count];
7051 - (Package *) packageAtIndex:(NSUInteger)index {
7052 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7055 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7056 Section *section([sections_ objectAtIndex:[path section]]);
7057 NSInteger row([path row]);
7058 return [self packageAtIndex:([section row] + row)];
7061 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7062 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7064 cell = [[[PackageCell alloc] init] autorelease];
7065 [cell setPackage:[self packageAtIndexPath:path]];
7069 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7070 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7073 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7074 Package *package([self packageAtIndexPath:path]);
7075 PackageController *view([delegate_ packageController]);
7076 [view setDelegate:delegate_];
7077 [view setPackage:package];
7078 [[self navigationController] pushViewController:view animated:YES];
7082 - (void) refreshButtonClicked {
7083 [delegate_ beginUpdate];
7084 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7087 - (void) upgradeButtonClicked {
7088 [delegate_ distUpgrade];
7091 - (NSString *) title { return UCLocalize("CHANGES"); }
7093 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7094 if ((self = [super init]) != nil) {
7095 database_ = database;
7096 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7098 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7100 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7102 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7103 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7104 [list_ setRowHeight:73.0f];
7105 [[self view] addSubview:list_];
7107 [list_ setDataSource:self];
7108 [list_ setDelegate:self];
7110 delegate_ = delegate;
7114 - (void) _reloadPackages:(NSArray *)packages {
7116 for (Package *package in packages)
7117 if ([package upgradableAndEssential:YES] || [package visible])
7118 CFArrayAppendValue(packages_, package);
7121 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7125 - (void) reloadData {
7126 NSArray *packages = [database_ packages];
7128 CFArrayRemoveAllValues(packages_);
7130 [sections_ removeAllObjects];
7133 UIProgressHUD *hud([delegate_ addProgressHUD]);
7134 [hud setText:UCLocalize("LOADING")];
7135 //NSLog(@"HUD:%@::%@", delegate_, hud);
7136 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7137 [delegate_ removeProgressHUD:hud];
7139 [self _reloadPackages:packages];
7142 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7143 Section *ignored = nil;
7144 Section *section = nil;
7148 bool unseens = false;
7150 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7152 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7153 Package *package = [self packageAtIndex:offset];
7155 BOOL uae = [package upgradableAndEssential:YES];
7159 time_t seen([package seen]);
7161 if (section == nil || last != seen) {
7165 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7168 _profile(ChangesController$reloadData$Allocate)
7169 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7170 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7171 [sections_ addObject:section];
7175 [section addToCount];
7176 } else if ([package ignored]) {
7177 if (ignored == nil) {
7178 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7180 [ignored addToCount];
7183 [upgradable addToCount];
7188 CFRelease(formatter);
7191 Section *last = [sections_ lastObject];
7192 size_t count = [last count];
7193 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7194 [sections_ removeLastObject];
7197 if ([ignored count] != 0)
7198 [sections_ insertObject:ignored atIndex:0];
7200 [sections_ insertObject:upgradable atIndex:0];
7205 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7206 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7207 style:UIBarButtonItemStylePlain
7209 action:@selector(upgradeButtonClicked)
7212 if (![delegate_ updating])
7213 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7214 initWithTitle:UCLocalize("REFRESH")
7215 style:UIBarButtonItemStylePlain
7217 action:@selector(refreshButtonClicked)
7223 /* Search Controller {{{ */
7224 @interface SearchController : FilteredPackageController <
7227 UISearchBar *search_;
7230 - (id) initWithDatabase:(Database *)database;
7231 - (void) reloadData;
7235 @implementation SearchController
7242 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7243 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7244 [search_ resignFirstResponder];
7248 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7249 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7253 - (NSString *) title { return nil; }
7255 - (id) initWithDatabase:(Database *)database {
7256 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7259 - (void)viewDidAppear:(BOOL)animated {
7260 [super viewDidAppear:animated];
7262 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7263 [search_ layoutSubviews];
7264 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7265 UITextField *textField = [search_ searchField];
7266 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7267 [search_ setDelegate:self];
7268 [textField setEnablesReturnKeyAutomatically:NO];
7269 [[self navigationItem] setTitleView:textField];
7273 - (void) _reloadData {
7276 - (void) reloadData {
7277 _profile(SearchController$reloadData)
7278 [packages_ reloadData];
7281 [packages_ resetCursor];
7284 - (void) didSelectPackage:(Package *)package {
7285 [search_ resignFirstResponder];
7286 [super didSelectPackage:package];
7291 /* Settings Controller {{{ */
7292 @interface SettingsController : CYViewController <
7293 UITableViewDataSource,
7296 _transient Database *database_;
7299 UITableView *table_;
7300 UISwitch *subscribedSwitch_;
7301 UISwitch *ignoredSwitch_;
7302 UITableViewCell *subscribedCell_;
7303 UITableViewCell *ignoredCell_;
7306 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7310 @implementation SettingsController
7314 if (package_ != nil)
7317 [subscribedSwitch_ release];
7318 [ignoredSwitch_ release];
7319 [subscribedCell_ release];
7320 [ignoredCell_ release];
7325 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7326 if (package_ == nil)
7332 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7333 if (package_ == nil)
7339 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7340 return UCLocalize("SHOW_ALL_CHANGES_EX");
7343 - (void) onSubscribed:(id)control {
7344 bool value([control isOn]);
7345 if (package_ == nil)
7347 if ([package_ setSubscribed:value])
7348 [delegate_ updateData];
7351 - (void) onIgnored:(id)control {
7352 // TODO: set Held state - possibly call out to dpkg, etc.
7355 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7356 if (package_ == nil)
7359 switch ([indexPath row]) {
7360 case 0: return subscribedCell_;
7361 case 1: return ignoredCell_;
7369 - (NSString *) title { return UCLocalize("SETTINGS"); }
7371 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7372 if ((self = [super init])) {
7373 database_ = database;
7374 name_ = [package retain];
7376 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7378 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7379 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7380 [[self view] addSubview:table_];
7382 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7383 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7384 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7386 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7387 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7388 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7390 subscribedCell_ = [[UITableViewCell alloc] init];
7391 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7392 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7393 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7395 ignoredCell_ = [[UITableViewCell alloc] init];
7396 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7397 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7398 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7400 [table_ setDataSource:self];
7401 [table_ setDelegate:self];
7406 - (void) reloadData {
7407 if (package_ != nil)
7408 [package_ autorelease];
7409 package_ = [database_ packageWithName:name_];
7410 if (package_ != nil) {
7412 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7413 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7416 [table_ reloadData];
7421 /* Signature Controller {{{ */
7422 @interface SignatureController : CYBrowserController {
7423 _transient Database *database_;
7427 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7431 @implementation SignatureController
7438 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7440 [super webView:view didClearWindowObject:window forFrame:frame];
7443 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7444 if ((self = [super init]) != nil) {
7445 database_ = database;
7446 package_ = [package retain];
7451 - (void) reloadData {
7452 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7458 /* Role Controller {{{ */
7459 @interface RoleController : CYViewController <
7460 UITableViewDataSource,
7463 _transient Database *database_;
7464 // XXX: ok, "roledelegate_"?...
7465 _transient id roledelegate_;
7466 UITableView *table_;
7467 UISegmentedControl *segment_;
7471 - (void) showDoneButton;
7472 - (void) resizeSegmentedControl;
7476 @implementation RoleController
7480 [container_ release];
7485 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7486 if ((self = [super init])) {
7487 database_ = database;
7488 roledelegate_ = delegate;
7490 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7492 NSArray *items = [NSArray arrayWithObjects:
7494 UCLocalize("HACKER"),
7495 UCLocalize("DEVELOPER"),
7497 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7498 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7499 [container_ addSubview:segment_];
7502 if ([Role_ isEqualToString:@"User"]) index = 0;
7503 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7504 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7506 [segment_ setSelectedSegmentIndex:index];
7507 [self showDoneButton];
7510 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7511 [self resizeSegmentedControl];
7513 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7514 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7515 [table_ setDelegate:self];
7516 [table_ setDataSource:self];
7517 [[self view] addSubview:table_];
7518 [table_ reloadData];
7522 - (void) resizeSegmentedControl {
7523 CGFloat width = [[self view] frame].size.width;
7524 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7527 - (void) viewWillAppear:(BOOL)animated {
7528 [super viewWillAppear:animated];
7530 [self resizeSegmentedControl];
7533 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7534 [self resizeSegmentedControl];
7537 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7538 [self resizeSegmentedControl];
7542 NSString *role(nil);
7544 switch ([segment_ selectedSegmentIndex]) {
7545 case 0: role = @"User"; break;
7546 case 1: role = @"Hacker"; break;
7547 case 2: role = @"Developer"; break;
7552 if (![role isEqualToString:Role_]) {
7553 bool rolling(Role_ == nil);
7556 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7560 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7564 [roledelegate_ loadData];
7566 [roledelegate_ updateData];
7570 - (void) segmentChanged:(UISegmentedControl *)control {
7571 [self showDoneButton];
7574 - (void) saveAndClose {
7577 [[self navigationItem] setRightBarButtonItem:nil];
7578 [[self navigationController] dismissModalViewControllerAnimated:YES];
7581 - (void) doneButtonClicked {
7582 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7583 [spinner startAnimating];
7584 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7585 [[self navigationItem] setRightBarButtonItem:spinItem];
7587 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7590 - (void) showDoneButton {
7591 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7592 initWithTitle:UCLocalize("DONE")
7593 style:UIBarButtonItemStyleDone
7595 action:@selector(doneButtonClicked)
7596 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7599 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7600 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7604 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7608 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7609 return nil; // This method is required by the protocol.
7612 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7614 return UCLocalize("ROLE_EX");
7616 return [NSString stringWithFormat:
7617 @"%@: %@\n%@: %@\n%@: %@",
7618 UCLocalize("USER"), UCLocalize("USER_EX"),
7619 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7620 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7625 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7626 return section == 3 ? 44.0f : 0;
7629 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7630 return section == 3 ? container_ : nil;
7635 /* Stash Controller {{{ */
7636 @interface CYStashController : CYViewController {
7637 // XXX: just delete these things
7638 _transient UIActivityIndicatorView *spinner_;
7639 _transient UILabel *status_;
7640 _transient UILabel *caption_;
7644 @implementation CYStashController
7646 if ((self = [super init])) {
7647 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7649 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7650 CGRect spinrect = [spinner_ frame];
7651 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7652 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7653 [spinner_ setFrame:spinrect];
7654 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7655 [[self view] addSubview:spinner_];
7656 [spinner_ startAnimating];
7659 captrect.size.width = [[self view] frame].size.width;
7660 captrect.size.height = 40.0f;
7661 captrect.origin.x = 0;
7662 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7663 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7664 [caption_ setText:@"Initializing Filesystem"];
7665 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7666 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7667 [caption_ setTextColor:[UIColor whiteColor]];
7668 [caption_ setBackgroundColor:[UIColor clearColor]];
7669 [caption_ setShadowColor:[UIColor blackColor]];
7670 [caption_ setTextAlignment:UITextAlignmentCenter];
7671 [[self view] addSubview:caption_];
7674 statusrect.size.width = [[self view] frame].size.width;
7675 statusrect.size.height = 30.0f;
7676 statusrect.origin.x = 0;
7677 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7678 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7679 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7680 [status_ setText:@"(Cydia will exit when complete.)"];
7681 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7682 [status_ setTextColor:[UIColor whiteColor]];
7683 [status_ setBackgroundColor:[UIColor clearColor]];
7684 [status_ setShadowColor:[UIColor blackColor]];
7685 [status_ setTextAlignment:UITextAlignmentCenter];
7686 [[self view] addSubview:status_];
7690 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7691 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7696 /* Cydia Container {{{ */
7697 @interface CYContainer : UIViewController <ProgressDelegate> {
7698 _transient Database *database_;
7699 RefreshBar *refreshbar_;
7703 // XXX: ok, "updatedelegate_"?...
7704 _transient NSObject<CydiaDelegate> *updatedelegate_;
7705 // XXX: can't we query for this variable when we need it?
7706 _transient UITabBarController *root_;
7709 - (void) setTabBarController:(UITabBarController *)controller;
7711 - (void) dropBar:(BOOL)animated;
7712 - (void) beginUpdate;
7713 - (void) raiseBar:(BOOL)animated;
7718 @implementation CYContainer
7720 - (BOOL) _reallyWantsFullScreenLayout {
7724 // NOTE: UIWindow only sends the top controller these messages,
7725 // So we have to forward them on.
7727 - (void) viewDidAppear:(BOOL)animated {
7728 [super viewDidAppear:animated];
7729 [root_ viewDidAppear:animated];
7732 - (void) viewWillAppear:(BOOL)animated {
7733 [super viewWillAppear:animated];
7734 [root_ viewWillAppear:animated];
7737 - (void) viewDidDisappear:(BOOL)animated {
7738 [super viewDidDisappear:animated];
7739 [root_ viewDidDisappear:animated];
7742 - (void) viewWillDisappear:(BOOL)animated {
7743 [super viewWillDisappear:animated];
7744 [root_ viewWillDisappear:animated];
7747 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7748 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7751 - (void) setTabBarController:(UITabBarController *)controller {
7753 [[self view] addSubview:[root_ view]];
7756 - (void) setUpdate:(NSDate *)date {
7760 - (void) beginUpdate {
7762 [refreshbar_ start];
7767 detachNewThreadSelector:@selector(performUpdate)
7773 - (void) performUpdate { _pooled
7775 status.setDelegate(self);
7776 [database_ updateWithStatus:status];
7779 performSelectorOnMainThread:@selector(completeUpdate)
7785 - (void) completeUpdate {
7790 [self raiseBar:YES];
7792 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7795 - (void) cancelUpdate {
7797 [self raiseBar:YES];
7799 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7802 - (void) cancelPressed {
7803 [self cancelUpdate];
7810 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7811 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7814 - (void) startProgress {
7817 - (void) setProgressTitle:(NSString *)title {
7819 performSelectorOnMainThread:@selector(_setProgressTitle:)
7825 - (bool) isCancelling:(size_t)received {
7829 - (void) setProgressPercent:(float)percent {
7831 performSelectorOnMainThread:@selector(_setProgressPercent:)
7832 withObject:[NSNumber numberWithFloat:percent]
7837 - (void) addProgressOutput:(NSString *)output {
7839 performSelectorOnMainThread:@selector(_addProgressOutput:)
7845 - (void) _setProgressTitle:(NSString *)title {
7846 [refreshbar_ setPrompt:title];
7849 - (void) _setProgressPercent:(NSNumber *)percent {
7850 [refreshbar_ setProgress:[percent floatValue]];
7853 - (void) _addProgressOutput:(NSString *)output {
7856 - (void) setUpdateDelegate:(id)delegate {
7857 updatedelegate_ = delegate;
7860 - (CGFloat) statusBarHeight {
7861 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7862 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7864 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7868 - (void) dropBar:(BOOL)animated {
7873 [[self view] addSubview:refreshbar_];
7875 CGFloat sboffset = [self statusBarHeight];
7877 CGRect barframe = [refreshbar_ frame];
7878 barframe.origin.y = sboffset;
7879 [refreshbar_ setFrame:barframe];
7882 [UIView beginAnimations:nil context:NULL];
7883 CGRect viewframe = [[root_ view] frame];
7884 viewframe.origin.y += barframe.size.height + sboffset;
7885 viewframe.size.height -= barframe.size.height + sboffset;
7886 [[root_ view] setFrame:viewframe];
7888 [UIView commitAnimations];
7890 // Ensure bar has the proper width for our view, it might have changed
7891 barframe.size.width = viewframe.size.width;
7892 [refreshbar_ setFrame:barframe];
7894 // XXX: fix Apple's layout bug
7895 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7898 - (void) raiseBar:(BOOL)animated {
7903 [refreshbar_ removeFromSuperview];
7905 CGFloat sboffset = [self statusBarHeight];
7908 [UIView beginAnimations:nil context:NULL];
7909 CGRect barframe = [refreshbar_ frame];
7910 CGRect viewframe = [[root_ view] frame];
7911 viewframe.origin.y -= barframe.size.height + sboffset;
7912 viewframe.size.height += barframe.size.height + sboffset;
7913 [[root_ view] setFrame:viewframe];
7915 [UIView commitAnimations];
7917 // XXX: fix Apple's layout bug
7918 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7921 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7922 // XXX: fix Apple's layout bug
7923 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7926 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7932 // XXX: fix Apple's layout bug
7933 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7936 - (void) statusBarFrameChanged:(NSNotification *)notification {
7944 [refreshbar_ release];
7945 [[NSNotificationCenter defaultCenter] removeObserver:self];
7949 - (id) initWithDatabase:(Database *)database {
7950 if ((self = [super init]) != nil) {
7951 database_ = database;
7953 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7954 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7956 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7973 @interface Cydia : UIApplication <
7974 ConfirmationControllerDelegate,
7975 ProgressControllerDelegate,
7977 UINavigationControllerDelegate,
7978 UITabBarControllerDelegate
7980 // XXX: evaluate all fields for _transient
7983 CYContainer *container_;
7984 CYTabBarController *tabbar_;
7986 NSMutableArray *essential_;
7987 NSMutableArray *broken_;
7989 Database *database_;
7995 SectionsController *sections_;
7996 ChangesController *changes_;
7997 ManageController *manage_;
7998 SearchController *search_;
7999 SourceTable *sources_;
8000 InstalledController *installed_;
8003 CYStashController *stash_;
8008 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
8009 - (void) setPage:(CYViewController *)page;
8012 // XXX: I hate prototypes
8013 - (id) queueBadgeController;
8017 static _finline void _setHomePage(Cydia *self) {
8018 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
8021 @implementation Cydia
8023 - (void) beginUpdate {
8024 [container_ beginUpdate];
8028 return [container_ updating];
8031 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8036 if ([broken_ count] != 0) {
8037 int count = [broken_ count];
8039 UIAlertView *alert = [[[UIAlertView alloc]
8040 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8041 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8043 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8044 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8047 [alert setContext:@"fixhalf"];
8049 } else if (!Ignored_ && [essential_ count] != 0) {
8050 int count = [essential_ count];
8052 UIAlertView *alert = [[[UIAlertView alloc]
8053 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8054 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8056 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8057 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8060 [alert setContext:@"upgrade"];
8065 - (void) _saveConfig {
8071 NSString *error(nil);
8073 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8075 NSError *error(nil);
8076 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8077 NSLog(@"failure to save metadata data: %@", error);
8082 NSLog(@"failure to serialize metadata: %@", error);
8087 - (void) _updateData {
8090 /* XXX: this is just stupid */
8091 if (tag_ != 1 && sections_ != nil)
8092 [sections_ reloadData];
8093 if (tag_ != 2 && changes_ != nil)
8094 [changes_ reloadData];
8095 if (tag_ != 4 && search_ != nil)
8096 [search_ reloadData];
8098 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8100 [queueDelegate_ queueStatusDidChange];
8101 [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8104 - (int)indexOfTabWithTag:(int)tag {
8106 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8107 if ([[controller tabBarItem] tag] == tag)
8115 - (void) _refreshIfPossible {
8116 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8118 bool recently = false;
8119 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8120 if (update != nil) {
8121 NSTimeInterval interval([update timeIntervalSinceNow]);
8122 if (interval <= 0 && interval > -(15*60))
8126 // Don't automatic refresh if:
8127 // - We already refreshed recently.
8128 // - We already auto-refreshed this launch.
8129 // - Auto-refresh is disabled.
8130 if (recently || loaded_ || ManualRefresh) {
8131 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8133 // If we are cancelling due to ManualRefresh or a recent refresh
8134 // we need to make sure it knows it's already loaded.
8138 // We are going to load, so remember that.
8142 SCNetworkReachabilityFlags flags; {
8143 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8144 SCNetworkReachabilityGetFlags(reachability, &flags);
8145 CFRelease(reachability);
8148 // XXX: this elaborate mess is what Apple is using to determine this? :(
8149 // XXX: do we care if the user has to intervene? maybe that's ok?
8151 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8152 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8153 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8154 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8155 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8156 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8160 // If we can reach the server, auto-refresh!
8162 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8167 - (void) refreshIfPossible {
8168 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8171 - (void) _reloadData {
8172 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8173 [hud setText:UCLocalize("RELOADING_DATA")];
8175 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8178 [self removeProgressHUD:hud];
8182 [essential_ removeAllObjects];
8183 [broken_ removeAllObjects];
8185 NSArray *packages([database_ packages]);
8186 for (Package *package in packages) {
8188 [broken_ addObject:package];
8189 if ([package upgradableAndEssential:NO]) {
8190 if ([package essential])
8191 [essential_ addObject:package];
8196 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8198 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8199 [changesItem setBadgeValue:badge];
8200 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8202 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8203 [self setApplicationBadge:badge];
8205 [self setApplicationBadgeString:badge];
8207 [changesItem setBadgeValue:nil];
8208 [changesItem setAnimatedBadge:NO];
8210 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8211 [self removeApplicationBadge];
8212 else // XXX: maybe use setApplicationBadgeString also?
8213 [self setApplicationIconBadgeNumber:0];
8218 [self refreshIfPossible];
8221 - (void) updateData {
8230 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8231 _assert(file != NULL);
8233 for (NSString *key in [Sources_ allKeys]) {
8234 NSDictionary *source([Sources_ objectForKey:key]);
8236 fprintf(file, "%s %s %s\n",
8237 [[source objectForKey:@"Type"] UTF8String],
8238 [[source objectForKey:@"URI"] UTF8String],
8239 [[source objectForKey:@"Distribution"] UTF8String]
8247 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8248 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8250 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8251 [container_ presentModalViewController:navigation animated:YES];
8254 detachNewThreadSelector:@selector(update_)
8257 title:UCLocalize("UPDATING_SOURCES")
8261 - (void) reloadData {
8262 @synchronized (self) {
8268 pkgProblemResolver *resolver = [database_ resolver];
8270 resolver->InstallProtect();
8271 if (!resolver->Resolve(true))
8275 - (CGRect) popUpBounds {
8276 return [[tabbar_ view] bounds];
8280 if (![database_ prepare])
8283 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8284 [page setDelegate:self];
8285 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8286 [confirm_ setDelegate:self];
8289 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8290 [container_ presentModalViewController:confirm_ animated:YES];
8296 @synchronized (self) {
8301 - (void) clearPackage:(Package *)package {
8302 @synchronized (self) {
8309 - (void) installPackages:(NSArray *)packages {
8310 @synchronized (self) {
8311 for (Package *package in packages)
8318 - (void) installPackage:(Package *)package {
8319 @synchronized (self) {
8326 - (void) removePackage:(Package *)package {
8327 @synchronized (self) {
8334 - (void) distUpgrade {
8335 @synchronized (self) {
8336 if (![database_ upgrade])
8343 @synchronized (self) {
8348 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8351 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8353 if (navigation != nil) {
8354 [navigation pushViewController:progress animated:YES];
8356 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8358 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8359 [container_ presentModalViewController:navigation animated:YES];
8363 detachNewThreadSelector:@selector(perform)
8366 title:UCLocalize("RUNNING")
8370 - (void) progressControllerIsComplete:(ProgressController *)progress {
8374 - (void) setPage:(CYViewController *)page {
8375 [page setDelegate:self];
8377 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8378 [navController setViewControllers:[NSArray arrayWithObject:page]];
8379 for (CYNavigationController *page in [tabbar_ viewControllers])
8380 if (page != navController)
8381 [page setViewControllers:nil];
8384 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8385 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8386 [browser loadURL:url];
8390 - (SectionsController *) sectionsController {
8391 if (sections_ == nil)
8392 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8396 - (ChangesController *) changesController {
8397 if (changes_ == nil)
8398 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8402 - (ManageController *) manageController {
8403 if (manage_ == nil) {
8404 manage_ = (ManageController *) [[self
8405 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8406 withClass:[ManageController class]
8409 queueDelegate_ = manage_;
8414 - (SearchController *) searchController {
8416 search_ = [[SearchController alloc] initWithDatabase:database_];
8420 - (SourceTable *) sourcesController {
8421 if (sources_ == nil)
8422 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8426 - (InstalledController *) installedController {
8427 if (installed_ == nil) {
8428 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8430 queueDelegate_ = installed_;
8435 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8436 int tag = [[viewController tabBarItem] tag];
8438 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8440 } else if (tag_ == 1) {
8441 [[self sectionsController] resetView];
8445 case kCydiaTag: _setHomePage(self); break;
8447 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8448 case kChangesTag: [self setPage:[self changesController]]; break;
8449 case kManageTag: [self setPage:[self manageController]]; break;
8450 case kInstalledTag: [self setPage:[self installedController]]; break;
8451 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8452 case kSearchTag: [self setPage:[self searchController]]; break;
8460 - (void) showSettings {
8461 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8462 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8464 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8465 [container_ presentModalViewController:nav animated:YES];
8468 - (void) setPackageController:(PackageController *)view {
8470 [view setPackage:nil];
8474 - (PackageController *) _packageController {
8475 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8478 - (PackageController *) packageController {
8479 return [self _packageController];
8482 // Returns the navigation controller for the queuing badge.
8483 - (id) queueBadgeController {
8484 int index = [self indexOfTabWithTag:kManageTag];
8486 index = [self indexOfTabWithTag:kInstalledTag];
8488 return [[tabbar_ viewControllers] objectAtIndex:index];
8491 - (void) cancelAndClear:(bool)clear {
8492 @synchronized (self) {
8504 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8505 NSString *context([alert context]);
8507 if ([context isEqualToString:@"fixhalf"]) {
8508 if (button == [alert firstOtherButtonIndex]) {
8509 @synchronized (self) {
8510 for (Package *broken in broken_) {
8513 NSString *id = [broken id];
8514 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8515 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8516 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8517 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8523 } else if (button == [alert cancelButtonIndex]) {
8524 [broken_ removeAllObjects];
8528 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8529 } else if ([context isEqualToString:@"upgrade"]) {
8530 if (button == [alert firstOtherButtonIndex]) {
8531 @synchronized (self) {
8532 for (Package *essential in essential_)
8533 [essential install];
8538 } else if (button == [alert firstOtherButtonIndex] + 1) {
8540 } else if (button == [alert cancelButtonIndex]) {
8544 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8548 - (void) system:(NSString *)command { _pooled
8549 system([command UTF8String]);
8552 - (void) applicationWillSuspend {
8554 [super applicationWillSuspend];
8557 - (BOOL) hudIsShowing {
8558 return (hudcount_ > 0);
8561 - (void) applicationSuspend:(__GSEvent *)event {
8562 // Use external process status API internally.
8563 // This is probably a really bad idea.
8564 uint64_t status = 0;
8566 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8567 notify_get_state(notify_token, &status);
8568 notify_cancel(notify_token);
8571 if (![self hudIsShowing] && status == 0)
8572 [super applicationSuspend:event];
8575 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8576 if (![self hudIsShowing])
8577 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8580 - (void) _setSuspended:(BOOL)value {
8581 if (![self hudIsShowing])
8582 [super _setSuspended:value];
8585 - (UIProgressHUD *) addProgressHUD {
8586 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8587 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8589 [window_ setUserInteractionEnabled:NO];
8592 UIViewController *target = container_;
8593 while ([target modalViewController] != nil) target = [target modalViewController];
8594 [[target view] addSubview:hud];
8600 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8602 [hud removeFromSuperview];
8603 [window_ setUserInteractionEnabled:YES];
8607 - (CYViewController *) pageForPackage:(NSString *)name {
8608 if (Package *package = [database_ packageWithName:name]) {
8609 PackageController *view([self packageController]);
8610 [view setPackage:package];
8613 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8614 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8615 return [self _pageForURL:url withClass:[CYBrowserController class]];
8619 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8623 NSString *href([url absoluteString]);
8624 if ([href hasPrefix:@"apptapp://package/"])
8625 return [self pageForPackage:[href substringFromIndex:18]];
8627 NSString *scheme([[url scheme] lowercaseString]);
8628 if (![scheme isEqualToString:@"cydia"])
8630 NSString *path([url absoluteString]);
8631 if ([path length] < 8)
8633 path = [path substringFromIndex:8];
8634 if (![path hasPrefix:@"/"])
8635 path = [@"/" stringByAppendingString:path];
8637 if ([path isEqualToString:@"/add-source"])
8638 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8639 else if ([path isEqualToString:@"/storage"])
8640 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8641 else if ([path isEqualToString:@"/sources"])
8642 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8643 else if ([path isEqualToString:@"/packages"])
8644 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8645 else if ([path hasPrefix:@"/url/"])
8646 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8647 else if ([path hasPrefix:@"/launch/"])
8648 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8649 else if ([path hasPrefix:@"/package-settings/"])
8650 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8651 else if ([path hasPrefix:@"/package-signature/"])
8652 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8653 else if ([path hasPrefix:@"/package/"])
8654 return [self pageForPackage:[path substringFromIndex:9]];
8655 else if ([path hasPrefix:@"/files/"]) {
8656 NSString *name = [path substringFromIndex:7];
8658 if (Package *package = [database_ packageWithName:name]) {
8659 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8660 [files setPackage:package];
8668 - (BOOL) openCydiaURL:(NSURL *)url {
8669 CYViewController *page = nil;
8672 NSLog(@"open url: %@", url);
8674 if ((page = [self pageForURL:url hasTag:&tag])) {
8675 [self setPage:page];
8677 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8683 - (void) applicationOpenURL:(NSURL *)url {
8684 [super applicationOpenURL:url];
8685 NSLog(@"first: %@", url);
8686 if (!loaded_) starturl_ = [url retain];
8687 else [self openCydiaURL:url];
8690 - (void) applicationWillResignActive:(UIApplication *)application {
8691 // Stop refreshing if you get a phone call or lock the device.
8692 if ([container_ updating])
8693 [container_ cancelUpdate];
8695 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8696 [super applicationWillResignActive:application];
8699 - (void) addStashController {
8700 stash_ = [[CYStashController alloc] init];
8701 [window_ addSubview:[stash_ view]];
8704 - (void) removeStashController {
8705 [[stash_ view] removeFromSuperview];
8710 [self setIdleTimerDisabled:YES];
8712 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8713 [self setStatusBarShowsProgress:YES];
8714 UpdateExternalStatus(1);
8716 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8718 UpdateExternalStatus(0);
8719 [self setStatusBarShowsProgress:NO];
8721 [self removeStashController];
8723 if (ExecFork() == 0) {
8724 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8725 perror("launchctl stop");
8729 - (void) setupTabBarController {
8730 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8731 [tabbar_ setDelegate:self];
8733 NSMutableArray *items([NSMutableArray arrayWithObjects:
8734 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8735 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8736 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8737 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8741 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8742 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8744 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8747 NSMutableArray *controllers([NSMutableArray array]);
8749 for (UITabBarItem *item in items) {
8750 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8751 [controller setTabBarItem:item];
8752 [controllers addObject:controller];
8755 [tabbar_ setViewControllers:controllers];
8758 - (void) applicationDidFinishLaunching:(id)unused {
8760 [CYBrowserController _initialize];
8762 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8764 Font12_ = [[UIFont systemFontOfSize:12] retain];
8765 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8766 Font14_ = [[UIFont systemFontOfSize:14] retain];
8767 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8768 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8772 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8773 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8775 UIScreen *screen([UIScreen mainScreen]);
8777 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8778 [window_ orderFront:self];
8779 [window_ makeKey:self];
8780 [window_ setHidden:NO];
8783 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8784 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8785 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8786 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8787 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8788 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8789 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8790 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8791 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8794 [self addStashController];
8795 // XXX: this would be much cleaner as a yieldToSelector:
8796 // that way the removeStashController could happen right here inline
8797 // we also could no longer require the useless stash_ field anymore
8798 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8802 database_ = [Database sharedInstance];
8804 [self setupTabBarController];
8806 container_ = [[CYContainer alloc] initWithDatabase:database_];
8807 [container_ setUpdateDelegate:self];
8808 [container_ setTabBarController:tabbar_];
8809 [window_ addSubview:[container_ view]];
8811 // Show pinstripes while loading data.
8812 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8814 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8821 [self showSettings];
8825 [window_ setUserInteractionEnabled:NO];
8827 UIView *container = [[[UIView alloc] init] autorelease];
8828 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8830 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8831 [spinner startAnimating];
8832 [container addSubview:spinner];
8834 UILabel *label = [[[UILabel alloc] init] autorelease];
8835 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8836 [label setBackgroundColor:[UIColor clearColor]];
8837 [label setTextColor:[UIColor blackColor]];
8838 [label setShadowColor:[UIColor whiteColor]];
8839 [label setShadowOffset:CGSizeMake(0, 1)];
8840 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8841 [container addSubview:label];
8843 CGSize viewsize = [[tabbar_ view] frame].size;
8844 CGSize spinnersize = [spinner bounds].size;
8845 CGSize textsize = [[label text] sizeWithFont:[label font]];
8846 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8848 CGRect containrect = {
8849 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8850 CGSizeMake(bothwidth, spinnersize.height)
8853 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8861 [container setFrame:containrect];
8862 [spinner setFrame:spinrect];
8863 [label setFrame:textrect];
8864 [[container_ view] addSubview:container];
8869 // Show the initial page
8870 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
8871 [tabbar_ setSelectedIndex:0];
8875 [starturl_ release];
8878 [window_ setUserInteractionEnabled:YES];
8880 // XXX: does this actually slow anything down?
8881 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8882 [container removeFromSuperview];
8885 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8886 if (item != nil && IsWildcat_) {
8887 [sheet showFromBarButtonItem:item animated:YES];
8889 [sheet showInView:window_];
8896 id Alloc_(id self, SEL selector) {
8897 id object = alloc_(self, selector);
8898 lprintf("[%s]A-%p\n", self->isa->name, object);
8903 id Dealloc_(id self, SEL selector) {
8904 id object = dealloc_(self, selector);
8905 lprintf("[%s]D-%p\n", self->isa->name, object);
8909 Class $WebDefaultUIKitDelegate;
8911 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8912 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8913 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8914 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8917 static NSNumber *shouldPlayKeyboardSounds;
8921 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8923 case 1104: // Keyboard Button Clicked
8924 case 1105: // Keyboard Delete Repeated
8925 if (shouldPlayKeyboardSounds == nil) {
8926 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8927 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8930 if (![shouldPlayKeyboardSounds boolValue])
8934 _UIHardware$_playSystemSound$(self, _cmd, sound);
8938 int main(int argc, char *argv[]) { _pooled
8941 if (Class $UIDevice = objc_getClass("UIDevice")) {
8942 UIDevice *device([$UIDevice currentDevice]);
8943 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8947 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8949 /* Library Hacks {{{ */
8950 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8952 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8953 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8954 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8955 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8956 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8959 $UIHardware = objc_getClass("UIHardware");
8960 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8961 if (UIHardware$_playSystemSound$ != NULL) {
8962 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8963 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8966 /* Set Locale {{{ */
8967 Locale_ = CFLocaleCopyCurrent();
8968 Languages_ = [NSLocale preferredLanguages];
8969 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8970 //NSLog(@"%@", [Languages_ description]);
8973 if (Languages_ == nil || [Languages_ count] == 0)
8974 // XXX: consider just setting to C and then falling through?
8977 lang = [[Languages_ objectAtIndex:0] UTF8String];
8978 setenv("LANG", lang, true);
8981 //std::setlocale(LC_ALL, lang);
8982 NSLog(@"Setting Language: %s", lang);
8985 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8987 /* Parse Arguments {{{ */
8988 bool substrate(false);
8994 for (int argi(1); argi != argc; ++argi)
8995 if (strcmp(argv[argi], "--") == 0) {
8997 argv[argi] = argv[0];
9003 for (int argi(1); argi != arge; ++argi)
9004 if (strcmp(args[argi], "--substrate") == 0)
9007 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9011 App_ = [[NSBundle mainBundle] bundlePath];
9012 Home_ = NSHomeDirectory();
9018 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9019 alloc_ = alloc->method_imp;
9020 alloc->method_imp = (IMP) &Alloc_;*/
9022 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9023 dealloc_ = dealloc->method_imp;
9024 dealloc->method_imp = (IMP) &Dealloc_;*/
9026 /* System Information {{{ */
9030 size = sizeof(maxproc);
9031 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9032 perror("sysctlbyname(\"kern.maxproc\", ?)");
9033 else if (maxproc < 64) {
9035 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9036 perror("sysctlbyname(\"kern.maxproc\", #)");
9039 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9040 char *osversion = new char[size];
9041 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9042 perror("sysctlbyname(\"kern.osversion\", ?)");
9044 System_ = [NSString stringWithUTF8String:osversion];
9046 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9047 char *machine = new char[size];
9048 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9049 perror("sysctlbyname(\"hw.machine\", ?)");
9053 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9054 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9055 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9056 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9060 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9061 NSData *data((NSData *) ecid);
9062 size_t length([data length]);
9063 uint8_t bytes[length];
9064 [data getBytes:bytes];
9065 char string[length * 2 + 1];
9066 for (size_t i(0); i != length; ++i)
9067 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9068 ChipID_ = [NSString stringWithUTF8String:string];
9072 IOObjectRelease(service);
9076 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9078 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9079 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9080 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9082 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9083 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9084 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9086 if (mcc != NULL && mnc != NULL)
9087 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9094 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9095 Build_ = [system objectForKey:@"ProductBuildVersion"];
9096 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9097 Product_ = [info objectForKey:@"SafariProductVersion"];
9098 Safari_ = [info objectForKey:@"CFBundleVersion"];
9101 /* Load Database {{{ */
9103 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9105 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9107 if (Metadata_ == NULL)
9108 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9110 Settings_ = [Metadata_ objectForKey:@"Settings"];
9112 Packages_ = [Metadata_ objectForKey:@"Packages"];
9113 Sections_ = [Metadata_ objectForKey:@"Sections"];
9114 Sources_ = [Metadata_ objectForKey:@"Sources"];
9116 Token_ = [Metadata_ objectForKey:@"Token"];
9119 if (Settings_ != nil)
9120 Role_ = [Settings_ objectForKey:@"Role"];
9122 if (Sections_ == nil) {
9123 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9124 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9127 if (Sources_ == nil) {
9128 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9129 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9134 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9137 if (Packages_ != nil) {
9138 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9140 [Metadata_ removeObjectForKey:@"Packages"];
9145 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9147 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9148 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9149 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9150 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9151 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9152 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9154 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9156 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9157 unlink("/tmp/.cydia.fw");
9159 } else if (access("/User", F_OK) != 0 || version < 2) {
9162 system("/usr/libexec/cydia/firmware.sh");
9166 _assert([[NSFileManager defaultManager]
9167 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9168 withIntermediateDirectories:YES
9173 if (access("/tmp/cydia.chk", F_OK) == 0) {
9174 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9175 _assert(errno == ENOENT);
9176 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9177 _assert(errno == ENOENT);
9180 /* APT Initialization {{{ */
9181 _assert(pkgInitConfig(*_config));
9182 _assert(pkgInitSystem(*_config, _system));
9185 _config->Set("APT::Acquire::Translation", lang);
9187 // XXX: this timeout might be important :(
9188 //_config->Set("Acquire::http::Timeout", 15);
9190 _config->Set("Acquire::http::MaxParallel", 3);
9192 /* Color Choices {{{ */
9193 space_ = CGColorSpaceCreateDeviceRGB();
9195 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9196 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9197 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9198 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9199 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9200 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9201 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9202 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9203 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9205 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9206 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9208 /* UIKit Configuration {{{ */
9209 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9210 if ($GSFontSetUseLegacyFontMetrics != NULL)
9211 $GSFontSetUseLegacyFontMetrics(YES);
9213 // XXX: I have a feeling this was important
9214 //UIKeyboardDisableAutomaticAppearance();
9217 Colon_ = UCLocalize("COLON_DELIMITED");
9218 Elision_ = UCLocalize("ELISION");
9219 Error_ = UCLocalize("ERROR");
9220 Warning_ = UCLocalize("WARNING");
9223 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9225 CGColorSpaceRelease(space_);