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, ':'));
1105 version = colon + 1;
1109 NSString *LocalizeSection(NSString *section) {
1110 static Pcre title_r("^(.*?) \\((.*)\\)$");
1111 if (title_r(section)) {
1112 NSString *parent(title_r[1]);
1113 NSString *child(title_r[2]);
1115 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1116 LocalizeSection(parent),
1117 LocalizeSection(child)
1121 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1124 NSString *Simplify(NSString *title) {
1125 const char *data = [title UTF8String];
1126 size_t size = [title length];
1128 static Pcre square_r("^\\[(.*)\\]$");
1129 if (square_r(data, size))
1130 return Simplify(square_r[1]);
1132 static Pcre paren_r("^\\((.*)\\)$");
1133 if (paren_r(data, size))
1134 return Simplify(paren_r[1]);
1136 static Pcre title_r("^(.*?) \\((.*)\\)$");
1137 if (title_r(data, size))
1138 return Simplify(title_r[1]);
1144 NSString *GetLastUpdate() {
1145 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1148 return UCLocalize("NEVER_OR_UNKNOWN");
1150 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1151 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1153 CFRelease(formatter);
1155 return [(NSString *) formatted autorelease];
1158 bool isSectionVisible(NSString *section) {
1159 NSDictionary *metadata([Sections_ objectForKey:section]);
1160 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1161 return hidden == nil || ![hidden boolValue];
1166 /* Delegate Prototypes {{{ */
1170 @interface NSObject (ProgressDelegate)
1173 @protocol ProgressDelegate
1174 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1175 - (void) setProgressTitle:(NSString *)title;
1176 - (void) setProgressPercent:(float)percent;
1177 - (void) startProgress;
1178 - (void) addProgressOutput:(NSString *)output;
1179 - (bool) isCancelling:(size_t)received;
1182 @protocol ConfigurationDelegate
1183 - (void) repairWithSelector:(SEL)selector;
1184 - (void) setConfigurationData:(NSString *)data;
1187 @class PackageController;
1189 @protocol CydiaDelegate
1190 - (void) setPackageController:(PackageController *)view;
1191 - (void) clearPackage:(Package *)package;
1192 - (void) installPackage:(Package *)package;
1193 - (void) installPackages:(NSArray *)packages;
1194 - (void) removePackage:(Package *)package;
1195 - (void) beginUpdate;
1197 - (void) distUpgrade;
1199 - (void) updateData;
1201 - (void) showSettings;
1202 - (UIProgressHUD *) addProgressHUD;
1203 - (BOOL) hudIsShowing;
1204 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1205 - (CYViewController *) pageForPackage:(NSString *)name;
1206 - (PackageController *) packageController;
1207 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1211 /* Status Delegation {{{ */
1213 public pkgAcquireStatus
1216 _transient NSObject<ProgressDelegate> *delegate_;
1224 void setDelegate(id delegate) {
1225 delegate_ = delegate;
1228 NSObject<ProgressDelegate> *getDelegate() const {
1232 virtual bool MediaChange(std::string media, std::string drive) {
1236 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1239 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1240 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1241 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1244 virtual void Done(pkgAcquire::ItemDesc &item) {
1247 virtual void Fail(pkgAcquire::ItemDesc &item) {
1249 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1250 item.Owner->Status == pkgAcquire::Item::StatDone
1254 std::string &error(item.Owner->ErrorText);
1258 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1259 NSArray *fields([description componentsSeparatedByString:@" "]);
1260 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1262 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1263 withObject:[NSArray arrayWithObjects:
1264 [NSString stringWithUTF8String:error.c_str()],
1271 virtual bool Pulse(pkgAcquire *Owner) {
1272 bool value = pkgAcquireStatus::Pulse(Owner);
1275 double(CurrentBytes + CurrentItems) /
1276 double(TotalBytes + TotalItems)
1279 [delegate_ setProgressPercent:percent];
1280 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1283 virtual void Start() {
1284 [delegate_ startProgress];
1287 virtual void Stop() {
1291 /* Progress Delegation {{{ */
1296 _transient id<ProgressDelegate> delegate_;
1300 virtual void Update() {
1301 /*if (abs(Percent - percent_) > 2)
1302 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1306 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1307 [delegate_ setProgressPercent:(Percent / 100)];*/
1317 void setDelegate(id delegate) {
1318 delegate_ = delegate;
1321 id getDelegate() const {
1325 virtual void Done() {
1327 //[delegate_ setProgressPercent:1];
1332 /* Database Interface {{{ */
1333 typedef std::map< unsigned long, _H<Source> > SourceMap;
1335 @interface Database : NSObject {
1341 pkgCacheFile cache_;
1342 pkgDepCache::Policy *policy_;
1343 pkgRecords *records_;
1344 pkgProblemResolver *resolver_;
1345 pkgAcquire *fetcher_;
1347 SPtr<pkgPackageManager> manager_;
1348 pkgSourceList *list_;
1351 CFMutableArrayRef packages_;
1353 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1362 + (Database *) sharedInstance;
1365 - (void) _readCydia:(NSNumber *)fd;
1366 - (void) _readStatus:(NSNumber *)fd;
1367 - (void) _readOutput:(NSNumber *)fd;
1371 - (Package *) packageWithName:(NSString *)name;
1373 - (pkgCacheFile &) cache;
1374 - (pkgDepCache::Policy *) policy;
1375 - (pkgRecords *) records;
1376 - (pkgProblemResolver *) resolver;
1377 - (pkgAcquire &) fetcher;
1378 - (pkgSourceList &) list;
1379 - (NSArray *) packages;
1380 - (NSArray *) sources;
1381 - (void) reloadData;
1389 - (void) updateWithStatus:(Status &)status;
1391 - (void) setDelegate:(id)delegate;
1392 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1395 /* Delegate Helpers {{{ */
1396 @implementation NSObject (ProgressDelegate)
1398 - (void) _setProgressErrorPackage:(NSArray *)args {
1399 [self performSelector:@selector(setProgressError:forPackage:)
1400 withObject:[args objectAtIndex:0]
1401 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1405 - (void) _setProgressErrorTitle:(NSArray *)args {
1406 [self performSelector:@selector(setProgressError:withTitle:)
1407 withObject:[args objectAtIndex:0]
1408 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1412 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1413 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1414 withObject:[NSArray arrayWithObjects:error, title, nil]
1419 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1420 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1422 [self performSelector:@selector(setProgressError:withTitle:)
1424 withObject:(package == nil ? id : [package name])
1431 // Cytore Definitions {{{
1432 struct PackageValue :
1435 Cytore::Offset<void> reserved_;
1436 Cytore::Offset<PackageValue> next_;
1438 uint32_t index_ : 23;
1439 uint32_t subscribed_ : 1;
1455 Cytore::Offset<void> reserved_;
1456 Cytore::Offset<PackageValue> packages_[1 << 16];
1459 static Cytore::File<MetaValue> MetaFile_;
1461 // Cytore Helper Functions {{{
1462 static PackageValue *PackageFind(const char *name, size_t length) {
1463 SplitHash nhash = { hashlittle(name, length) };
1465 PackageValue *metadata;
1467 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1468 offset: if (offset->IsNull()) {
1469 *offset = MetaFile_.New<PackageValue>(length + 1);
1470 metadata = &MetaFile_.Get(*offset);
1472 memcpy(metadata->name_, name, length + 1);
1473 metadata->nhash_ = nhash.u16[1];
1475 metadata = &MetaFile_.Get(*offset);
1477 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1478 offset = &metadata->next_;
1486 static void PackageImport(const void *key, const void *value, void *context) {
1488 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1489 NSLog(@"failed to import package %@", key);
1493 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1494 NSDictionary *package((NSDictionary *) value);
1496 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1497 if ([subscribed boolValue])
1498 metadata->subscribed_ = true;
1500 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1501 time_t time([date timeIntervalSince1970]);
1502 if (metadata->first_ > time || metadata->first_ == 0)
1503 metadata->first_ = time;
1506 if (NSDate *date = [package objectForKey:@"LastSeen"]) {
1507 time_t time([date timeIntervalSince1970]);
1508 if (metadata->last_ < time || metadata->last_ == 0) {
1509 metadata->last_ = time;
1512 } else if (metadata->last_ == 0) last: {
1513 NSString *version([package objectForKey:@"LastVersion"]);
1514 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1515 size_t length(strlen(buffer));
1516 uint16_t vhash(hashlittle(buffer, length));
1518 size_t capped(std::min<size_t>(8, length));
1519 char *latest(buffer + length - capped);
1521 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1522 metadata->vhash_ = vhash;
1528 /* Source Class {{{ */
1529 @interface Source : NSObject {
1530 CYString depiction_;
1531 CYString description_;
1537 CYString distribution_;
1542 NSString *authority_;
1544 CYString defaultIcon_;
1546 NSDictionary *record_;
1550 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1552 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1554 - (NSString *) depictionForPackage:(NSString *)package;
1555 - (NSString *) supportForPackage:(NSString *)package;
1557 - (NSDictionary *) record;
1561 - (NSString *) distribution;
1562 - (NSString *) type;
1564 - (NSString *) host;
1566 - (NSString *) name;
1567 - (NSString *) description;
1568 - (NSString *) label;
1569 - (NSString *) origin;
1570 - (NSString *) version;
1572 - (NSString *) defaultIcon;
1576 @implementation Source
1580 distribution_.clear();
1583 description_.clear();
1589 defaultIcon_.clear();
1591 if (record_ != nil) {
1601 if (authority_ != nil) {
1602 [authority_ release];
1608 // XXX: this is a very inefficient way to call these deconstructors
1613 + (NSArray *) _attributeKeys {
1614 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1617 - (NSArray *) attributeKeys {
1618 return [[self class] _attributeKeys];
1621 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1622 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1625 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1628 trusted_ = index->IsTrusted();
1630 uri_.set(pool, index->GetURI());
1631 distribution_.set(pool, index->GetDist());
1632 type_.set(pool, index->GetType());
1634 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1635 if (dindex != NULL) {
1637 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1640 pkgTagFile tags(&fd);
1642 pkgTagSection section;
1649 {"default-icon", &defaultIcon_},
1650 {"depiction", &depiction_},
1651 {"description", &description_},
1653 {"origin", &origin_},
1654 {"support", &support_},
1655 {"version", &version_},
1658 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1659 const char *start, *end;
1661 if (section.Find(names[i].name_, start, end)) {
1662 CYString &value(*names[i].value_);
1663 value.set(pool, start, end - start);
1669 record_ = [Sources_ objectForKey:[self key]];
1671 record_ = [record_ retain];
1673 NSURL *url([NSURL URLWithString:uri_]);
1677 host_ = [[host_ lowercaseString] retain];
1682 authority_ = [url path];
1684 if (authority_ != nil)
1685 authority_ = [authority_ retain];
1688 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1689 if ((self = [super init]) != nil) {
1690 [self setMetaIndex:index inPool:pool];
1694 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1695 NSDictionary *lhr = [self record];
1696 NSDictionary *rhr = [source record];
1699 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1701 NSString *lhs = [self name];
1702 NSString *rhs = [source name];
1704 if ([lhs length] != 0 && [rhs length] != 0) {
1705 unichar lhc = [lhs characterAtIndex:0];
1706 unichar rhc = [rhs characterAtIndex:0];
1708 if (isalpha(lhc) && !isalpha(rhc))
1709 return NSOrderedAscending;
1710 else if (!isalpha(lhc) && isalpha(rhc))
1711 return NSOrderedDescending;
1714 return [lhs compare:rhs options:LaxCompareOptions_];
1717 - (NSString *) depictionForPackage:(NSString *)package {
1718 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1721 - (NSString *) supportForPackage:(NSString *)package {
1722 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1725 - (NSDictionary *) record {
1733 - (NSString *) uri {
1737 - (NSString *) distribution {
1738 return distribution_;
1741 - (NSString *) type {
1745 - (NSString *) key {
1746 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1749 - (NSString *) host {
1753 - (NSString *) name {
1754 return origin_.empty() ? authority_ : origin_;
1757 - (NSString *) description {
1758 return description_;
1761 - (NSString *) label {
1762 return label_.empty() ? authority_ : label_;
1765 - (NSString *) origin {
1769 - (NSString *) version {
1773 - (NSString *) defaultIcon {
1774 return defaultIcon_;
1779 /* Relationship Class {{{ */
1780 @interface Relationship : NSObject {
1785 - (NSString *) type;
1787 - (NSString *) name;
1791 @implementation Relationship
1799 - (NSString *) type {
1807 - (NSString *) name {
1814 /* Package Class {{{ */
1815 struct ParsedPackage {
1820 CYString depiction_;
1830 @interface Package : NSObject {
1834 pkgCache::VerIterator version_;
1835 pkgCache::PkgIterator iterator_;
1836 _transient Database *database_;
1837 pkgCache::VerFileIterator file_;
1840 ParsedPackage *parsed_;
1843 _transient NSString *section$_;
1848 CYString installed_;
1853 NSMutableArray *tags_;
1856 PackageValue *metadata_;
1861 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1862 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1864 - (pkgCache::PkgIterator) iterator;
1867 - (NSString *) section;
1868 - (NSString *) simpleSection;
1870 - (NSString *) longSection;
1871 - (NSString *) shortSection;
1875 - (Address *) maintainer;
1877 - (NSString *) longDescription;
1878 - (NSString *) shortDescription;
1881 - (PackageValue *) metadata;
1884 - (bool) subscribed;
1885 - (bool) setSubscribed:(bool)subscribed;
1889 - (NSString *) latest;
1890 - (NSString *) installed;
1891 - (BOOL) uninstalled;
1894 - (BOOL) upgradableAndEssential:(BOOL)essential;
1897 - (BOOL) unfiltered;
1901 - (BOOL) halfConfigured;
1902 - (BOOL) halfInstalled;
1904 - (NSString *) mode;
1907 - (NSString *) name;
1909 - (NSString *) homepage;
1910 - (NSString *) depiction;
1911 - (Address *) author;
1913 - (NSString *) support;
1915 - (NSArray *) files;
1916 - (NSArray *) warnings;
1917 - (NSArray *) applications;
1919 - (Source *) source;
1920 - (NSString *) role;
1922 - (BOOL) matches:(NSString *)text;
1924 - (bool) hasSupportingRole;
1925 - (BOOL) hasTag:(NSString *)tag;
1926 - (NSString *) primaryPurpose;
1927 - (NSArray *) purposes;
1928 - (bool) isCommercial;
1930 - (CYString &) cyname;
1932 - (uint32_t) compareBySection:(NSArray *)sections;
1937 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1938 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1939 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1940 - (bool) isVisibleInSection:(NSString *)section;
1941 - (bool) isVisibleInSource:(Source *)source;
1945 uint32_t PackageChangesRadix(Package *self, void *) {
1950 uint32_t timestamp : 30;
1951 uint32_t ignored : 1;
1952 uint32_t upgradable : 1;
1956 bool upgradable([self upgradableAndEssential:YES]);
1957 value.bits.upgradable = upgradable ? 1 : 0;
1960 value.bits.timestamp = 0;
1961 value.bits.ignored = [self ignored] ? 0 : 1;
1962 value.bits.upgradable = 1;
1964 value.bits.timestamp = [self seen] >> 2;
1965 value.bits.ignored = 0;
1966 value.bits.upgradable = 0;
1969 return _not(uint32_t) - value.key;
1972 _finline static void Stifle(uint8_t &value) {
1975 uint32_t PackagePrefixRadix(Package *self, void *context) {
1976 size_t offset(reinterpret_cast<size_t>(context));
1977 CYString &name([self cyname]);
1979 size_t size(name.size());
1982 char *text(name.data());
1985 if (!isdigit(text[0]))
1989 while (size != digits && isdigit(text[digits]))
1999 if (offset == 0 && zeros != 0) {
2000 memset(data, '0', zeros);
2001 memcpy(data + zeros, text, 4 - zeros);
2003 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2004 if (size <= offset - zeros)
2007 text += offset - zeros;
2008 size -= offset - zeros;
2011 memcpy(data, text, 4);
2013 memcpy(data, text, size);
2014 memset(data + size, 0, 4 - size);
2017 for (size_t i(0); i != 4; ++i)
2018 if (isalpha(data[i]))
2026 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2028 /* XXX: ntohl may be more honest */
2029 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2032 CYString &(*PackageName)(Package *self, SEL sel);
2034 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2035 _profile(PackageNameCompare)
2036 CYString &lhi(PackageName(lhs, @selector(cyname)));
2037 CYString &rhi(PackageName(rhs, @selector(cyname)));
2038 CFStringRef lhn(lhi), rhn(rhi);
2041 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2042 else if (rhn == NULL)
2043 return NSOrderedDescending;
2045 _profile(PackageNameCompare$NumbersLast)
2046 if (!lhi.empty() && !rhi.empty()) {
2047 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2048 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2049 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2050 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2051 return lha ? NSOrderedAscending : NSOrderedDescending;
2055 CFIndex length = CFStringGetLength(lhn);
2057 _profile(PackageNameCompare$Compare)
2058 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2063 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2064 return PackageNameCompare(*lhs, *rhs, context);
2067 struct PackageNameOrdering :
2068 std::binary_function<Package *, Package *, bool>
2070 _finline bool operator ()(Package *lhs, Package *rhs) const {
2071 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2075 @implementation Package
2077 - (NSString *) description {
2078 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2082 if (parsed_ != NULL)
2096 + (NSString *) webScriptNameForSelector:(SEL)selector {
2097 if (selector == @selector(hasTag:))
2103 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2104 return [self webScriptNameForSelector:selector] == nil;
2107 + (NSArray *) _attributeKeys {
2108 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];
2111 - (NSArray *) attributeKeys {
2112 return [[self class] _attributeKeys];
2115 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2116 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2120 if (parsed_ != NULL)
2122 @synchronized (database_) {
2123 if ([database_ era] != era_ || file_.end())
2126 ParsedPackage *parsed(new ParsedPackage);
2129 _profile(Package$parse)
2130 pkgRecords::Parser *parser;
2132 _profile(Package$parse$Lookup)
2133 parser = &[database_ records]->Lookup(file_);
2138 _profile(Package$parse$Find)
2143 {"icon", &parsed->icon_},
2144 {"depiction", &parsed->depiction_},
2145 {"homepage", &parsed->homepage_},
2146 {"website", &website},
2147 {"bugs", &parsed->bugs_},
2148 {"support", &parsed->support_},
2149 {"sponsor", &parsed->sponsor_},
2150 {"author", &parsed->author_},
2153 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2154 const char *start, *end;
2156 if (parser->Find(names[i].name_, start, end)) {
2157 CYString &value(*names[i].value_);
2158 _profile(Package$parse$Value)
2159 value.set(pool_, start, end - start);
2165 _profile(Package$parse$Tagline)
2166 const char *start, *end;
2167 if (parser->ShortDesc(start, end)) {
2168 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2171 while (stop != start && stop[-1] == '\r')
2173 parsed->tagline_.set(pool_, start, stop - start);
2177 _profile(Package$parse$Retain)
2178 if (parsed->homepage_.empty())
2179 parsed->homepage_ = website;
2180 if (parsed->homepage_ == parsed->depiction_)
2181 parsed->homepage_.clear();
2186 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2187 if ((self = [super init]) != nil) {
2188 _profile(Package$initWithVersion)
2189 era_ = [database era];
2194 _profile(Package$initWithVersion$ParentPkg)
2195 iterator_ = version.ParentPkg();
2198 database_ = database;
2200 _profile(Package$initWithVersion$Latest)
2201 latest_.set(NULL, StripVersion_(version_.VerStr()));
2204 pkgCache::VerIterator current;
2205 _profile(Package$initWithVersion$Versions)
2206 current = iterator_.CurrentVer();
2208 installed_.set(NULL, StripVersion_(current.VerStr()));
2210 if (!version_.end())
2211 file_ = version_.FileList();
2213 pkgCache &cache([database_ cache]);
2214 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2218 _profile(Package$initWithVersion$Name)
2219 id_.set(NULL, iterator_.Name());
2220 name_.set(NULL, iterator_.Display());
2223 _profile(Package$initWithVersion$lowercaseString)
2224 // XXX: do not use tolower() as this is not locale-specific? :(
2225 char *data(id_.data());
2226 for (size_t i(0), e(id_.size()); i != e; ++i)
2227 if ((data[i] & 0x20) == 0) {
2236 _profile(Package$initWithVersion$Tags)
2237 pkgCache::TagIterator tag(iterator_.TagList());
2239 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2241 const char *name(tag.Name());
2242 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2244 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2245 role_ = (NSString *) CYStringCreate(name + 6);
2247 if (strncmp(name, "cydia::", 7) == 0) {
2248 if (strcmp(name + 7, "essential") == 0)
2250 else if (strcmp(name + 7, "obsolete") == 0)
2255 } while (!tag.end());
2259 _profile(Package$initWithVersion$Metadata)
2260 PackageValue *metadata(PackageFind(id_.data(), id_.size()));
2261 metadata_ = metadata;
2263 const char *latest(version_.VerStr());
2264 size_t length(strlen(latest));
2266 uint16_t vhash(hashlittle(latest, length));
2268 size_t capped(std::min<size_t>(8, length));
2269 latest = latest + length - capped;
2271 if (metadata->first_ == 0)
2272 metadata->first_ = now_;
2274 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2275 metadata->last_ = now_;
2276 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2277 metadata->vhash_ = vhash;
2278 } else if (metadata->last_ == 0)
2279 metadata->last_ = metadata->first_;
2282 _profile(Package$initWithVersion$Section)
2283 section_.set(NULL, iterator_.Section());
2286 _profile(Package$initWithVersion$hasTag)
2287 essential_ |= ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2290 ignored_ = iterator_->SelectedState == pkgCache::State::Hold;
2294 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2295 pkgCache::VerIterator version;
2297 _profile(Package$packageWithIterator$GetCandidateVer)
2298 version = [database policy]->GetCandidateVer(iterator);
2304 return [[[Package alloc]
2305 initWithVersion:version
2312 - (pkgCache::PkgIterator) iterator {
2316 - (NSString *) section {
2317 if (section$_ == nil) {
2318 if (section_.empty())
2321 _profile(Package$section)
2322 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2323 NSString *name(section_);
2324 section$_ = [SectionMap_ objectForKey:name] ?: name;
2329 - (NSString *) simpleSection {
2330 if (NSString *section = [self section])
2331 return Simplify(section);
2336 - (NSString *) longSection {
2337 return LocalizeSection([self section]);
2340 - (NSString *) shortSection {
2341 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2344 - (NSString *) uri {
2347 pkgIndexFile *index;
2348 pkgCache::PkgFileIterator file(file_.File());
2349 if (![database_ list].FindIndex(file, index))
2351 return [NSString stringWithUTF8String:iterator_->Path];
2352 //return [NSString stringWithUTF8String:file.Site()];
2353 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2357 - (Address *) maintainer {
2358 @synchronized (database_) {
2359 if ([database_ era] != era_ || file_.end())
2362 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2363 const std::string &maintainer(parser->Maintainer());
2364 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2368 @synchronized (database_) {
2369 if ([database_ era] != era_ || version_.end())
2372 return version_->InstalledSize;
2375 - (NSString *) longDescription {
2376 @synchronized (database_) {
2377 if ([database_ era] != era_ || file_.end())
2380 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2381 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2383 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2384 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2385 if ([lines count] < 2)
2388 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2389 for (size_t i(1), e([lines count]); i != e; ++i) {
2390 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2391 [trimmed addObject:trim];
2394 return [trimmed componentsJoinedByString:@"\n"];
2397 - (NSString *) shortDescription {
2398 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2402 _profile(Package$index)
2403 CFStringRef name((CFStringRef) [self name]);
2404 if (CFStringGetLength(name) == 0)
2406 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2407 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2409 return toupper(character);
2413 - (PackageValue *) metadata {
2418 PackageValue *metadata([self metadata]);
2419 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2422 - (bool) subscribed {
2423 return [self metadata]->subscribed_;
2426 - (bool) setSubscribed:(bool)subscribed {
2427 PackageValue *metadata([self metadata]);
2428 if (metadata->subscribed_ == subscribed)
2430 metadata->subscribed_ = subscribed;
2438 - (NSString *) latest {
2442 - (NSString *) installed {
2446 - (BOOL) uninstalled {
2447 return installed_.empty();
2451 return !version_.end();
2454 - (BOOL) upgradableAndEssential:(BOOL)essential {
2455 _profile(Package$upgradableAndEssential)
2456 pkgCache::VerIterator current(iterator_.CurrentVer());
2458 return essential && essential_;
2460 return !version_.end() && version_ != current;
2464 - (BOOL) essential {
2469 return [database_ cache][iterator_].InstBroken();
2472 - (BOOL) unfiltered {
2473 _profile(Package$unfiltered$obsolete)
2478 _profile(Package$unfiltered$hasSupportingRole)
2479 if (![self hasSupportingRole])
2487 if (![self unfiltered])
2490 NSString *section([self section]);
2492 _profile(Package$visible$isSectionVisible)
2493 if (section != nil && !isSectionVisible(section))
2501 unsigned char current(iterator_->CurrentState);
2502 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2505 - (BOOL) halfConfigured {
2506 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2509 - (BOOL) halfInstalled {
2510 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2514 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2515 return state.Mode != pkgDepCache::ModeKeep;
2518 - (NSString *) mode {
2519 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2521 switch (state.Mode) {
2522 case pkgDepCache::ModeDelete:
2523 if ((state.iFlags & pkgDepCache::Purge) != 0)
2527 case pkgDepCache::ModeKeep:
2528 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2529 return @"REINSTALL";
2530 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2534 case pkgDepCache::ModeInstall:
2535 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2536 return @"REINSTALL";
2537 else*/ switch (state.Status) {
2539 return @"DOWNGRADE";
2545 return @"NEW_INSTALL";
2556 - (NSString *) name {
2557 return name_.empty() ? id_ : name_;
2560 - (UIImage *) icon {
2561 NSString *section = [self simpleSection];
2564 if (parsed_ != NULL)
2565 if (NSString *href = parsed_->icon_)
2566 if ([href hasPrefix:@"file:///"])
2567 // XXX: correct escaping
2568 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2569 if (icon == nil) if (section != nil)
2570 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2571 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2572 if ([dicon hasPrefix:@"file:///"])
2573 // XXX: correct escaping
2574 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2576 icon = [UIImage applicationImageNamed:@"unknown.png"];
2580 - (NSString *) homepage {
2581 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2584 - (NSString *) depiction {
2585 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2588 - (Address *) sponsor {
2589 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2592 - (Address *) author {
2593 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2596 - (NSString *) support {
2597 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2600 - (NSArray *) files {
2601 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2602 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2605 fin.open([path UTF8String]);
2610 while (std::getline(fin, line))
2611 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2616 - (NSArray *) warnings {
2617 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2618 const char *name(iterator_.Name());
2620 size_t length(strlen(name));
2621 if (length < 2) invalid:
2622 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2623 else for (size_t i(0); i != length; ++i)
2625 /* XXX: technically this is not allowed */
2626 (name[i] < 'A' || name[i] > 'Z') &&
2627 (name[i] < 'a' || name[i] > 'z') &&
2628 (name[i] < '0' || name[i] > '9') &&
2629 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2632 if (strcmp(name, "cydia") != 0) {
2635 bool _private = false;
2638 bool repository = [[self section] isEqualToString:@"Repositories"];
2640 if (NSArray *files = [self files])
2641 for (NSString *file in files)
2642 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2644 else if (!user && [file isEqualToString:@"/User"])
2646 else if (!_private && [file isEqualToString:@"/private"])
2648 else if (!stash && [file isEqualToString:@"/var/stash"])
2651 /* XXX: this is not sensitive enough. only some folders are valid. */
2652 if (cydia && !repository)
2653 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2655 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2657 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2659 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2662 return [warnings count] == 0 ? nil : warnings;
2665 - (NSArray *) applications {
2666 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2668 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2670 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2671 if (NSArray *files = [self files])
2672 for (NSString *file in files)
2673 if (application_r(file)) {
2674 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2675 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2676 if ([id isEqualToString:me])
2679 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2681 display = application_r[1];
2683 NSString *bundle([file stringByDeletingLastPathComponent]);
2684 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2685 if (icon == nil || [icon length] == 0)
2687 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2689 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2690 [applications addObject:application];
2692 [application addObject:id];
2693 [application addObject:display];
2694 [application addObject:url];
2697 return [applications count] == 0 ? nil : applications;
2700 - (Source *) source {
2701 if (source_ == nil) {
2702 @synchronized (database_) {
2703 if ([database_ era] != era_ || file_.end())
2704 source_ = (Source *) [NSNull null];
2706 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2710 return source_ == (Source *) [NSNull null] ? nil : source_;
2713 - (NSString *) role {
2717 - (BOOL) matches:(NSString *)text {
2723 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2724 if (range.location != NSNotFound)
2727 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2728 if (range.location != NSNotFound)
2731 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2732 if (range.location != NSNotFound)
2738 - (bool) hasSupportingRole {
2741 if ([role_ isEqualToString:@"enduser"])
2743 if ([Role_ isEqualToString:@"User"])
2745 if ([role_ isEqualToString:@"hacker"])
2747 if ([Role_ isEqualToString:@"Hacker"])
2749 if ([role_ isEqualToString:@"developer"])
2751 if ([Role_ isEqualToString:@"Developer"])
2756 - (BOOL) hasTag:(NSString *)tag {
2757 return tags_ == nil ? NO : [tags_ containsObject:tag];
2760 - (NSString *) primaryPurpose {
2761 for (NSString *tag in tags_)
2762 if ([tag hasPrefix:@"purpose::"])
2763 return [tag substringFromIndex:9];
2767 - (NSArray *) purposes {
2768 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2769 for (NSString *tag in tags_)
2770 if ([tag hasPrefix:@"purpose::"])
2771 [purposes addObject:[tag substringFromIndex:9]];
2772 return [purposes count] == 0 ? nil : purposes;
2775 - (bool) isCommercial {
2776 return [self hasTag:@"cydia::commercial"];
2779 - (CYString &) cyname {
2780 return name_.empty() ? id_ : name_;
2783 - (uint32_t) compareBySection:(NSArray *)sections {
2784 NSString *section([self section]);
2785 for (size_t i(0), e([sections count]); i != e; ++i) {
2786 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2790 return _not(uint32_t);
2794 @synchronized (database_) {
2795 pkgProblemResolver *resolver = [database_ resolver];
2796 resolver->Clear(iterator_);
2798 pkgCacheFile &cache([database_ cache]);
2799 cache->SetReInstall(iterator_, false);
2800 cache->MarkKeep(iterator_, false);
2804 @synchronized (database_) {
2805 pkgProblemResolver *resolver = [database_ resolver];
2806 resolver->Clear(iterator_);
2807 resolver->Protect(iterator_);
2809 pkgCacheFile &cache([database_ cache]);
2810 cache->SetReInstall(iterator_, false);
2811 cache->MarkInstall(iterator_, false);
2813 pkgDepCache::StateCache &state((*cache)[iterator_]);
2814 if (!state.Install())
2815 cache->SetReInstall(iterator_, true);
2819 @synchronized (database_) {
2820 pkgProblemResolver *resolver = [database_ resolver];
2821 resolver->Clear(iterator_);
2822 resolver->Remove(iterator_);
2823 resolver->Protect(iterator_);
2825 pkgCacheFile &cache([database_ cache]);
2826 cache->SetReInstall(iterator_, false);
2827 cache->MarkDelete(iterator_, true);
2830 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2831 _profile(Package$isUnfilteredAndSearchedForBy)
2834 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2835 value &= [self unfiltered];
2838 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2839 value &= [self matches:search];
2846 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2847 if ([search length] == 0)
2850 _profile(Package$isUnfilteredAndSelectedForBy)
2853 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2854 value &= [self unfiltered];
2857 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2858 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2865 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2866 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2869 - (bool) isVisibleInSection:(NSString *)name {
2870 NSString *section([self section]);
2874 section == nil && [name length] == 0 ||
2875 [name isEqualToString:section]
2876 ) && [self visible];
2879 - (bool) isVisibleInSource:(Source *)source {
2880 return [self source] == source && [self visible];
2885 /* Section Class {{{ */
2886 @interface Section : NSObject {
2891 NSString *localized_;
2894 - (NSComparisonResult) compareByLocalized:(Section *)section;
2895 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2896 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2897 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2898 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2899 - (NSString *) name;
2906 - (void) addToCount;
2908 - (void) setCount:(size_t)count;
2909 - (NSString *) localized;
2913 @implementation Section
2917 if (localized_ != nil)
2918 [localized_ release];
2922 - (NSComparisonResult) compareByLocalized:(Section *)section {
2923 NSString *lhs(localized_);
2924 NSString *rhs([section localized]);
2926 /*if ([lhs length] != 0 && [rhs length] != 0) {
2927 unichar lhc = [lhs characterAtIndex:0];
2928 unichar rhc = [rhs characterAtIndex:0];
2930 if (isalpha(lhc) && !isalpha(rhc))
2931 return NSOrderedAscending;
2932 else if (!isalpha(lhc) && isalpha(rhc))
2933 return NSOrderedDescending;
2936 return [lhs compare:rhs options:LaxCompareOptions_];
2939 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2940 if ((self = [self initWithName:name localize:NO]) != nil) {
2941 if (localized != nil)
2942 localized_ = [localized retain];
2946 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2947 return [self initWithName:name row:0 localize:localize];
2950 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2951 if ((self = [super init]) != nil) {
2952 name_ = [name retain];
2956 localized_ = [LocalizeSection(name_) retain];
2960 /* XXX: localize the index thingees */
2961 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2962 if ((self = [super init]) != nil) {
2963 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2969 - (NSString *) name {
2989 - (void) addToCount {
2993 - (void) setCount:(size_t)count {
2997 - (NSString *) localized {
3004 static NSString *Colon_;
3005 static NSString *Elision_;
3006 static NSString *Error_;
3007 static NSString *Warning_;
3009 /* Database Implementation {{{ */
3010 @implementation Database
3012 + (Database *) sharedInstance {
3013 static Database *instance;
3014 if (instance == nil)
3015 instance = [[Database alloc] init];
3023 - (void) releasePackages {
3024 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3025 CFArrayRemoveAllValues(packages_);
3029 // XXX: actually implement this thing
3031 [self releasePackages];
3032 apr_pool_destroy(pool_);
3033 NSRecycleZone(zone_);
3037 - (void) _readCydia:(NSNumber *)fd { _pooled
3038 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3039 std::istream is(&ib);
3042 static Pcre finish_r("^finish:([^:]*)$");
3044 while (std::getline(is, line)) {
3045 const char *data(line.c_str());
3046 size_t size = line.size();
3047 lprintf("C:%s\n", data);
3049 if (finish_r(data, size)) {
3050 NSString *finish = finish_r[1];
3051 int index = [Finishes_ indexOfObject:finish];
3052 if (index != INT_MAX && index > Finish_)
3060 - (void) _readStatus:(NSNumber *)fd { _pooled
3061 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3062 std::istream is(&ib);
3065 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3066 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3068 while (std::getline(is, line)) {
3069 const char *data(line.c_str());
3070 size_t size(line.size());
3071 lprintf("S:%s\n", data);
3073 if (conffile_r(data, size)) {
3074 [delegate_ setConfigurationData:conffile_r[1]];
3075 } else if (strncmp(data, "status: ", 8) == 0) {
3076 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3077 [delegate_ setProgressTitle:string];
3078 } else if (pmstatus_r(data, size)) {
3079 std::string type([pmstatus_r[1] UTF8String]);
3080 NSString *id = pmstatus_r[2];
3082 float percent([pmstatus_r[3] floatValue]);
3083 [delegate_ setProgressPercent:(percent / 100)];
3085 NSString *string = pmstatus_r[4];
3087 if (type == "pmerror")
3088 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3089 withObject:[NSArray arrayWithObjects:string, id, nil]
3092 else if (type == "pmstatus") {
3093 [delegate_ setProgressTitle:string];
3094 } else if (type == "pmconffile")
3095 [delegate_ setConfigurationData:string];
3097 lprintf("E:unknown pmstatus\n");
3099 lprintf("E:unknown status\n");
3105 - (void) _readOutput:(NSNumber *)fd { _pooled
3106 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3107 std::istream is(&ib);
3110 while (std::getline(is, line)) {
3111 lprintf("O:%s\n", line.c_str());
3112 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3122 - (Package *) packageWithName:(NSString *)name {
3123 @synchronized (self) {
3124 if (static_cast<pkgDepCache *>(cache_) == NULL)
3126 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3127 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3131 if ((self = [super init]) != nil) {
3138 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3139 apr_pool_create(&pool_, NULL);
3141 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3145 _assert(pipe(fds) != -1);
3148 _config->Set("APT::Keep-Fds::", cydiafd_);
3149 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3152 detachNewThreadSelector:@selector(_readCydia:)
3154 withObject:[NSNumber numberWithInt:fds[0]]
3157 _assert(pipe(fds) != -1);
3161 detachNewThreadSelector:@selector(_readStatus:)
3163 withObject:[NSNumber numberWithInt:fds[0]]
3166 _assert(pipe(fds) != -1);
3167 _assert(dup2(fds[0], 0) != -1);
3168 _assert(close(fds[0]) != -1);
3170 input_ = fdopen(fds[1], "a");
3172 _assert(pipe(fds) != -1);
3173 _assert(dup2(fds[1], 1) != -1);
3174 _assert(close(fds[1]) != -1);
3177 detachNewThreadSelector:@selector(_readOutput:)
3179 withObject:[NSNumber numberWithInt:fds[0]]
3184 - (pkgCacheFile &) cache {
3188 - (pkgDepCache::Policy *) policy {
3192 - (pkgRecords *) records {
3196 - (pkgProblemResolver *) resolver {
3200 - (pkgAcquire &) fetcher {
3204 - (pkgSourceList &) list {
3208 - (NSArray *) packages {
3209 return (NSArray *) packages_;
3212 - (NSArray *) sources {
3213 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3214 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3215 [sources addObject:i->second];
3219 - (NSArray *) issues {
3220 if (cache_->BrokenCount() == 0)
3223 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3225 for (Package *package in [self packages]) {
3226 if (![package broken])
3228 pkgCache::PkgIterator pkg([package iterator]);
3230 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3231 [entry addObject:[package name]];
3232 [issues addObject:entry];
3234 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3238 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3239 pkgCache::DepIterator start;
3240 pkgCache::DepIterator end;
3241 dep.GlobOr(start, end); // ++dep
3243 if (!cache_->IsImportantDep(end))
3245 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3248 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3249 [entry addObject:failure];
3250 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3252 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3253 if (Package *package = [self packageWithName:name])
3254 name = [package name];
3255 [failure addObject:name];
3257 pkgCache::PkgIterator target(start.TargetPkg());
3258 if (target->ProvidesList != 0)
3259 [failure addObject:@"?"];
3261 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3263 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3264 else if (!cache_[target].CandidateVerIter(cache_).end())
3265 [failure addObject:@"-"];
3266 else if (target->ProvidesList == 0)
3267 [failure addObject:@"!"];
3269 [failure addObject:@"%"];
3273 if (start.TargetVer() != 0)
3274 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3285 - (bool) popErrorWithTitle:(NSString *)title {
3287 std::string message;
3289 while (!_error->empty()) {
3291 bool warning(!_error->PopMessage(error));
3295 size_t size(error.size());
3296 if (size == 0 || error[size - 1] != '\n')
3298 error.resize(size - 1);
3300 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3302 if (!message.empty())
3307 if (fatal && !message.empty())
3308 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3313 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3314 return [self popErrorWithTitle:title] || !success;
3317 - (void) reloadData { CYPoolStart() {
3318 @synchronized (self) {
3321 [self releasePackages];
3342 apr_pool_clear(pool_);
3343 NSRecycleZone(zone_);
3345 int chk(creat("/tmp/cydia.chk", 0644));
3349 NSString *title(UCLocalize("DATABASE"));
3352 if (!cache_.Open(progress_, true)) { pop:
3354 bool warning(!_error->PopMessage(error));
3355 lprintf("cache_.Open():[%s]\n", error.c_str());
3357 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3358 [delegate_ repairWithSelector:@selector(configure)];
3359 else if (error == "The package lists or status file could not be parsed or opened.")
3360 [delegate_ repairWithSelector:@selector(update)];
3361 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3362 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3363 // else if (error == "The list of sources could not be read.")
3365 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3374 unlink("/tmp/cydia.chk");
3376 now_ = [[NSDate date] timeIntervalSince1970];
3378 policy_ = new pkgDepCache::Policy();
3379 records_ = new pkgRecords(cache_);
3380 resolver_ = new pkgProblemResolver(cache_);
3381 fetcher_ = new pkgAcquire(&status_);
3384 list_ = new pkgSourceList();
3385 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3388 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3389 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3393 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3396 if (cache_->BrokenCount() != 0) {
3397 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3400 if (cache_->BrokenCount() != 0) {
3401 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3405 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3409 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3410 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3411 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3412 // XXX: this could be more intelligent
3413 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3414 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3416 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3421 /*std::vector<Package *> packages;
3422 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3423 [packages_ release];
3428 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3429 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3430 //packages.push_back(package);
3431 CFArrayAppendValue(packages_, [package retain]);
3435 /*if (packages.empty())
3436 packages_ = [[NSArray alloc] init];
3438 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3441 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3442 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3443 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3451 /*if (!packages.empty())
3452 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3453 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3455 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3457 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3459 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3463 } } CYPoolEnd() _trace(); }
3466 @synchronized (self) {
3468 resolver_ = new pkgProblemResolver(cache_);
3470 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3471 if (!cache_[iterator].Keep()) {
3472 cache_->MarkKeep(iterator, false);
3473 cache_->SetReInstall(iterator, false);
3478 - (void) configure {
3479 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3480 system([dpkg UTF8String]);
3484 // XXX: I don't remember this condition
3489 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3491 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3493 if ([self popErrorWithTitle:title])
3497 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3500 public pkgArchiveCleaner
3503 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3508 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3515 fetcher_->Shutdown();
3517 pkgRecords records(cache_);
3519 lock_ = new FileFd();
3520 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3522 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3524 if ([self popErrorWithTitle:title])
3528 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3531 manager_ = (_system->CreatePM(cache_));
3532 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3539 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3541 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3543 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3545 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3546 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3549 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3554 bool failed = false;
3555 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3556 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3558 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3561 std::string uri = (*item)->DescURI();
3562 std::string error = (*item)->ErrorText;
3564 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3567 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3568 withObject:[NSArray arrayWithObjects:
3569 [NSString stringWithUTF8String:error.c_str()],
3581 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3583 if (_error->PendingError()) {
3588 if (result == pkgPackageManager::Failed) {
3593 if (result != pkgPackageManager::Completed) {
3598 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3600 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3602 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3603 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3606 if (![before isEqualToArray:after])
3611 NSString *title(UCLocalize("UPGRADE"));
3612 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3618 [self updateWithStatus:status_];
3621 - (void) updateWithStatus:(Status &)status {
3622 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3623 NSString *title(UCLocalize("REFRESHING_DATA"));
3626 if (!list.ReadMainList())
3627 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3630 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3631 if ([self popErrorWithTitle:title])
3634 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3635 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3636 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3638 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3642 - (void) setDelegate:(id)delegate {
3643 delegate_ = delegate;
3644 status_.setDelegate(delegate);
3645 progress_.setDelegate(delegate);
3648 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3649 SourceMap::const_iterator i(sources_.find(file->ID));
3650 return i == sources_.end() ? nil : i->second;
3656 /* Confirmation Controller {{{ */
3657 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3658 if (!iterator.end())
3659 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3660 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3662 pkgCache::PkgIterator package(dep.TargetPkg());
3665 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3673 /* Web Scripting {{{ */
3674 @interface CydiaObject : NSObject {
3676 _transient id delegate_;
3679 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3682 @implementation CydiaObject
3685 [indirect_ release];
3689 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3690 if ((self = [super init]) != nil) {
3691 indirect_ = [indirect retain];
3695 - (void) setDelegate:(id)delegate {
3696 delegate_ = delegate;
3699 + (NSArray *) _attributeKeys {
3700 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3703 - (NSArray *) attributeKeys {
3704 return [[self class] _attributeKeys];
3707 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3708 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3711 - (NSString *) device {
3712 return [[UIDevice currentDevice] uniqueIdentifier];
3715 #if 0 // XXX: implement!
3716 - (NSString *) mac {
3717 if (![indirect_ promptForSensitive:@"Mac Address"])
3721 - (NSString *) serial {
3722 if (![indirect_ promptForSensitive:@"Serial #"])
3726 - (NSString *) firewire {
3727 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3731 - (NSString *) imei {
3732 if (![indirect_ promptForSensitive:@"IMEI"])
3737 + (NSString *) webScriptNameForSelector:(SEL)selector {
3738 if (selector == @selector(close))
3740 else if (selector == @selector(getInstalledPackages))
3741 return @"getInstalledPackages";
3742 else if (selector == @selector(getPackageById:))
3743 return @"getPackageById";
3744 else if (selector == @selector(installPackages:))
3745 return @"installPackages";
3746 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3747 return @"setButtonImage";
3748 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3749 return @"setButtonTitle";
3750 else if (selector == @selector(setPopupHook:))
3751 return @"setPopupHook";
3752 else if (selector == @selector(setSpecial:))
3753 return @"setSpecial";
3754 else if (selector == @selector(setToken:))
3756 else if (selector == @selector(setViewportWidth:))
3757 return @"setViewportWidth";
3758 else if (selector == @selector(supports:))
3760 else if (selector == @selector(stringWithFormat:arguments:))
3762 else if (selector == @selector(localizedStringForKey:value:table:))
3764 else if (selector == @selector(du:))
3766 else if (selector == @selector(statfs:))
3772 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3773 return [self webScriptNameForSelector:selector] == nil;
3776 - (BOOL) supports:(NSString *)feature {
3777 return [feature isEqualToString:@"window.open"];
3780 - (NSArray *) getInstalledPackages {
3781 NSArray *packages([[Database sharedInstance] packages]);
3782 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3783 for (Package *package in packages)
3784 if ([package installed] != nil)
3785 [installed addObject:package];
3789 - (Package *) getPackageById:(NSString *)id {
3790 Package *package([[Database sharedInstance] packageWithName:id]);
3795 - (NSArray *) statfs:(NSString *)path {
3798 if (path == nil || statfs([path UTF8String], &stat) == -1)
3801 return [NSArray arrayWithObjects:
3802 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3803 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3804 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3808 - (NSNumber *) du:(NSString *)path {
3809 NSNumber *value(nil);
3812 _assert(pipe(fds) != -1);
3814 pid_t pid(ExecFork());
3816 _assert(dup2(fds[1], 1) != -1);
3817 _assert(close(fds[0]) != -1);
3818 _assert(close(fds[1]) != -1);
3819 /* XXX: this should probably not use du */
3820 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3825 _assert(close(fds[1]) != -1);
3827 if (FILE *du = fdopen(fds[0], "r")) {
3829 while (fgets(line, sizeof(line), du) != NULL) {
3830 size_t length(strlen(line));
3831 while (length != 0 && line[length - 1] == '\n')
3832 line[--length] = '\0';
3833 if (char *tab = strchr(line, '\t')) {
3835 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3840 } else _assert(close(fds[0]));
3844 if (waitpid(pid, &status, 0) == -1)
3847 else _assert(false);
3856 - (void) installPackages:(NSArray *)packages {
3857 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3860 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3861 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3864 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3865 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3868 - (void) setSpecial:(id)function {
3869 [indirect_ setSpecial:function];
3872 - (void) setToken:(NSString *)token {
3875 Token_ = [token retain];
3877 [Metadata_ setObject:Token_ forKey:@"Token"];
3881 - (void) setPopupHook:(id)function {
3882 [indirect_ setPopupHook:function];
3885 - (void) setViewportWidth:(float)width {
3886 [indirect_ setViewportWidth:width];
3889 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3890 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3891 unsigned count([arguments count]);
3893 for (unsigned i(0); i != count; ++i)
3894 values[i] = [arguments objectAtIndex:i];
3895 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3898 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3899 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3901 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3903 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3909 /* Cydia Browser Controller {{{ */
3910 @interface CYBrowserController : BrowserController {
3911 CydiaObject *cydia_;
3916 @implementation CYBrowserController
3923 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3926 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3927 [super webView:view didClearWindowObject:window forFrame:frame];
3929 WebDataSource *source([frame dataSource]);
3930 NSURLResponse *response([source response]);
3931 NSURL *url([response URL]);
3932 NSString *scheme([url scheme]);
3934 NSHTTPURLResponse *http;
3935 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3936 http = (NSHTTPURLResponse *) response;
3940 NSDictionary *headers([http allHeaderFields]);
3941 NSString *host([url host]);
3942 [self setHeaders:headers forHost:host];
3945 [host isEqualToString:@"cydia.saurik.com"] ||
3946 [host hasSuffix:@".cydia.saurik.com"] ||
3947 [scheme isEqualToString:@"file"]
3949 [window setValue:cydia_ forKey:@"cydia"];
3952 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3953 if (System_ != NULL)
3954 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3955 if (Machine_ != NULL)
3956 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3958 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3960 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3963 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3964 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3965 [self _setMoreHeaders:copy];
3969 - (void) setDelegate:(id)delegate {
3970 [super setDelegate:delegate];
3971 [cydia_ setDelegate:delegate];
3975 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3976 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3978 WebView *webview([[webview_ _documentView] webView]);
3980 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3982 NSString *application = package == nil ? @"Cydia" : [NSString
3983 stringWithFormat:@"Cydia/%@",
3988 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3990 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3991 if (Product_ != nil)
3992 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3994 [webview setApplicationNameForUserAgent:application];
4001 /* Confirmation {{{ */
4002 @protocol ConfirmationControllerDelegate
4003 - (void) cancelAndClear:(bool)clear;
4004 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4008 @interface ConfirmationController : CYBrowserController {
4009 _transient Database *database_;
4010 UIAlertView *essential_;
4017 - (id) initWithDatabase:(Database *)database;
4021 @implementation ConfirmationController
4028 if (essential_ != nil)
4029 [essential_ release];
4033 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4034 NSString *context([alert context]);
4036 if ([context isEqualToString:@"remove"]) {
4037 if (button == [alert cancelButtonIndex]) {
4038 [self dismissModalViewControllerAnimated:YES];
4039 } else if (button == [alert firstOtherButtonIndex]) {
4042 [delegate_ confirmWithNavigationController:[self navigationController]];
4045 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4046 } else if ([context isEqualToString:@"unable"]) {
4047 [self dismissModalViewControllerAnimated:YES];
4048 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4050 [super alertView:alert clickedButtonAtIndex:button];
4054 - (void) _doContinue {
4055 [self dismissModalViewControllerAnimated:YES];
4056 [delegate_ cancelAndClear:NO];
4059 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4060 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4064 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4065 [super webView:view didClearWindowObject:window forFrame:frame];
4066 [window setValue:changes_ forKey:@"changes"];
4067 [window setValue:issues_ forKey:@"issues"];
4068 [window setValue:sizes_ forKey:@"sizes"];
4069 [window setValue:self forKey:@"queue"];
4072 - (id) initWithDatabase:(Database *)database {
4073 if ((self = [super init]) != nil) {
4074 database_ = database;
4076 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4078 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4079 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4080 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4081 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4082 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4086 pkgDepCache::Policy *policy([database_ policy]);
4088 pkgCacheFile &cache([database_ cache]);
4089 NSArray *packages = [database_ packages];
4090 for (Package *package in packages) {
4091 pkgCache::PkgIterator iterator = [package iterator];
4092 pkgDepCache::StateCache &state(cache[iterator]);
4094 NSString *name([package name]);
4096 if (state.NewInstall())
4097 [installing addObject:name];
4098 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4099 [reinstalling addObject:name];
4100 else if (state.Upgrade())
4101 [upgrading addObject:name];
4102 else if (state.Downgrade())
4103 [downgrading addObject:name];
4104 else if (state.Delete()) {
4105 if ([package essential])
4107 [removing addObject:name];
4110 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4111 substrate_ |= DepSubstrate(iterator.CurrentVer());
4116 else if (Advanced_) {
4117 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4119 essential_ = [[UIAlertView alloc]
4120 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4121 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4123 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4124 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4127 [essential_ setContext:@"remove"];
4129 essential_ = [[UIAlertView alloc]
4130 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4131 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4133 cancelButtonTitle:UCLocalize("OKAY")
4134 otherButtonTitles:nil
4137 [essential_ setContext:@"unable"];
4140 changes_ = [[NSArray alloc] initWithObjects:
4148 issues_ = [database_ issues];
4150 issues_ = [issues_ retain];
4152 sizes_ = [[NSArray alloc] initWithObjects:
4153 SizeString([database_ fetcher].FetchNeeded()),
4154 SizeString([database_ fetcher].PartialPresent()),
4157 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4159 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4160 initWithTitle:UCLocalize("CANCEL")
4161 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4162 style:UIBarButtonItemStylePlain
4164 action:@selector(cancelButtonClicked)
4169 - (void) applyRightButton {
4170 #if !AlwaysReload && !IgnoreInstall
4171 if (issues_ == nil && ![self isLoading])
4172 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4173 initWithTitle:UCLocalize("CONFIRM")
4174 style:UIBarButtonItemStylePlain
4176 action:@selector(confirmButtonClicked)
4179 [super applyRightButton];
4181 [[self navigationItem] setRightBarButtonItem:nil];
4185 - (void) cancelButtonClicked {
4186 [self dismissModalViewControllerAnimated:YES];
4187 [delegate_ cancelAndClear:YES];
4191 - (void) confirmButtonClicked {
4195 if (essential_ != nil)
4200 [delegate_ confirmWithNavigationController:[self navigationController]];
4208 /* Progress Data {{{ */
4209 @interface ProgressData : NSObject {
4211 // XXX: should these really both be _transient?
4212 _transient id target_;
4213 _transient id object_;
4216 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4223 @implementation ProgressData
4225 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4226 if ((self = [super init]) != nil) {
4227 selector_ = selector;
4247 /* Progress Controller {{{ */
4248 @interface ProgressController : CYViewController <
4249 ConfigurationDelegate,
4252 _transient Database *database_;
4253 UIProgressBar *progress_;
4254 UITextView *output_;
4255 UITextLabel *status_;
4256 UIPushButton *close_;
4258 SHA1SumValue springlist_;
4259 SHA1SumValue notifyconf_;
4263 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4265 - (void) _retachThread;
4266 - (void) _detachNewThreadData:(ProgressData *)data;
4267 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4273 @protocol ProgressControllerDelegate
4274 - (void) progressControllerIsComplete:(ProgressController *)sender;
4277 @implementation ProgressController
4280 [database_ setDelegate:nil];
4281 [progress_ release];
4290 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4291 if ((self = [super init]) != nil) {
4292 database_ = database;
4293 [database_ setDelegate:self];
4294 delegate_ = delegate;
4296 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4298 progress_ = [[UIProgressBar alloc] init];
4299 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4300 [progress_ setStyle:0];
4302 status_ = [[UITextLabel alloc] init];
4303 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4304 [status_ setColor:[UIColor whiteColor]];
4305 [status_ setBackgroundColor:[UIColor clearColor]];
4306 [status_ setCentersHorizontally:YES];
4307 //[status_ setFont:font];
4309 output_ = [[UITextView alloc] init];
4311 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4312 //[output_ setTextFont:@"Courier New"];
4313 [output_ setFont:[[output_ font] fontWithSize:12]];
4314 [output_ setTextColor:[UIColor whiteColor]];
4315 [output_ setBackgroundColor:[UIColor clearColor]];
4316 [output_ setMarginTop:0];
4317 [output_ setAllowsRubberBanding:YES];
4318 [output_ setEditable:NO];
4319 [[self view] addSubview:output_];
4321 close_ = [[UIPushButton alloc] init];
4322 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4323 [close_ setAutosizesToFit:NO];
4324 [close_ setDrawsShadow:YES];
4325 [close_ setStretchBackground:YES];
4326 [close_ setEnabled:YES];
4327 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4328 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4329 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4330 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4334 - (void) positionViews {
4335 CGRect bounds = [[self view] bounds];
4336 CGSize prgsize = [UIProgressBar defaultSize];
4339 (bounds.size.width - prgsize.width) / 2,
4340 bounds.size.height - prgsize.height - 20
4343 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4345 [progress_ setFrame:prgrect];
4346 [status_ setFrame:CGRectMake(
4348 bounds.size.height - prgsize.height - 50,
4349 bounds.size.width - 20,
4352 [output_ setFrame:CGRectMake(
4355 bounds.size.width - 20,
4356 bounds.size.height - 62
4358 [close_ setFrame:CGRectMake(
4359 (bounds.size.width - closewidth) / 2,
4360 bounds.size.height - prgsize.height - 50,
4366 - (void) viewWillAppear:(BOOL)animated {
4367 [super viewDidAppear:animated];
4368 [[self navigationItem] setHidesBackButton:YES];
4369 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4371 [self positionViews];
4374 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4375 [self positionViews];
4378 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4379 NSString *context([alert context]);
4381 if ([context isEqualToString:@"conffile"]) {
4382 FILE *input = [database_ input];
4383 if (button == [alert cancelButtonIndex])
4384 fprintf(input, "N\n");
4385 else if (button == [alert firstOtherButtonIndex])
4386 fprintf(input, "Y\n");
4391 - (void) closeButtonPushed {
4394 UpdateExternalStatus(0);
4398 [self dismissModalViewControllerAnimated:YES];
4402 [delegate_ terminateWithSuccess];
4403 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4404 [delegate_ suspendWithAnimation:YES];
4406 [delegate_ suspend];*/
4410 system("launchctl stop com.apple.SpringBoard");
4414 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4423 - (void) _retachThread {
4424 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4426 [[self view] addSubview:close_];
4427 [progress_ removeFromSuperview];
4428 [status_ removeFromSuperview];
4430 [database_ popErrorWithTitle:title_];
4431 [delegate_ progressControllerIsComplete:self];
4435 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4438 MMap mmap(file, MMap::ReadOnly);
4440 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4441 if (!(notifyconf_ == sha1.Result()))
4448 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4451 MMap mmap(file, MMap::ReadOnly);
4453 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4454 if (!(springlist_ == sha1.Result()))
4460 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4461 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4462 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4463 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4464 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4467 system("su -c /usr/bin/uicache mobile");
4469 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4471 [delegate_ setStatusBarShowsProgress:NO];
4474 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4475 [[data target] performSelector:[data selector] withObject:[data object]];
4476 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4479 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4480 UpdateExternalStatus(1);
4487 title_ = [title retain];
4489 [[self navigationItem] setTitle:title_];
4491 [status_ setText:nil];
4492 [output_ setText:@""];
4493 [progress_ setProgress:0];
4495 [close_ removeFromSuperview];
4496 [[self view] addSubview:progress_];
4497 [[self view] addSubview:status_];
4499 [delegate_ setStatusBarShowsProgress:YES];
4504 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4507 MMap mmap(file, MMap::ReadOnly);
4509 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4510 notifyconf_ = sha1.Result();
4516 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4519 MMap mmap(file, MMap::ReadOnly);
4521 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4522 springlist_ = sha1.Result();
4527 detachNewThreadSelector:@selector(_detachNewThreadData:)
4529 withObject:[[[ProgressData alloc]
4530 initWithSelector:selector
4537 - (void) repairWithSelector:(SEL)selector {
4539 detachNewThreadSelector:selector
4542 title:UCLocalize("REPAIRING")
4546 - (void) setConfigurationData:(NSString *)data {
4548 performSelectorOnMainThread:@selector(_setConfigurationData:)
4554 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4555 CYActionSheet *sheet([[[CYActionSheet alloc]
4557 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4558 defaultButtonIndex:0
4561 [sheet setMessage:error];
4562 [sheet yieldToPopupAlertAnimated:YES];
4566 - (void) setProgressTitle:(NSString *)title {
4568 performSelectorOnMainThread:@selector(_setProgressTitle:)
4574 - (void) setProgressPercent:(float)percent {
4576 performSelectorOnMainThread:@selector(_setProgressPercent:)
4577 withObject:[NSNumber numberWithFloat:percent]
4582 - (void) startProgress {
4585 - (void) addProgressOutput:(NSString *)output {
4587 performSelectorOnMainThread:@selector(_addProgressOutput:)
4593 - (bool) isCancelling:(size_t)received {
4597 - (void) _setConfigurationData:(NSString *)data {
4598 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4600 if (!conffile_r(data)) {
4601 lprintf("E:invalid conffile\n");
4605 NSString *ofile = conffile_r[1];
4606 //NSString *nfile = conffile_r[2];
4608 UIAlertView *alert = [[[UIAlertView alloc]
4609 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4610 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4612 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4613 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4614 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4618 [alert setContext:@"conffile"];
4622 - (void) _setProgressTitle:(NSString *)title {
4623 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4624 for (size_t i(0), e([words count]); i != e; ++i) {
4625 NSString *word([words objectAtIndex:i]);
4626 if (Package *package = [database_ packageWithName:word])
4627 [words replaceObjectAtIndex:i withObject:[package name]];
4630 [status_ setText:[words componentsJoinedByString:@" "]];
4633 - (void) _setProgressPercent:(NSNumber *)percent {
4634 [progress_ setProgress:[percent floatValue]];
4637 - (void) _addProgressOutput:(NSString *)output {
4638 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4639 CGSize size = [output_ contentSize];
4640 CGRect rect = {{0, size.height}, {size.width, 0}};
4641 [output_ scrollRectToVisible:rect animated:YES];
4644 - (BOOL) isRunning {
4651 /* Cell Content View {{{ */
4652 @protocol ContentDelegate
4653 - (void) drawContentRect:(CGRect)rect;
4656 @interface ContentView : UIView {
4657 _transient id<ContentDelegate> delegate_;
4662 @implementation ContentView
4664 - (id) initWithFrame:(CGRect)frame {
4665 if ((self = [super initWithFrame:frame]) != nil) {
4666 [self setNeedsDisplayOnBoundsChange:YES];
4670 - (void) setDelegate:(id<ContentDelegate>)delegate {
4671 delegate_ = delegate;
4674 - (void) drawRect:(CGRect)rect {
4675 [super drawRect:rect];
4676 [delegate_ drawContentRect:rect];
4681 /* Cydia TableView Cell {{{ */
4682 @interface CYTableViewCell : UITableViewCell {
4683 ContentView *content_;
4689 @implementation CYTableViewCell
4696 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4697 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4699 if (view == content_) {
4700 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4701 highlighted_ = highlighted;
4704 [super _updateHighlightColorsForView:view highlighted:highlighted];
4707 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4708 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4709 highlighted_ = selected;
4711 [super setSelected:selected animated:animated];
4712 [content_ setNeedsDisplay];
4717 /* Package Cell {{{ */
4718 @interface PackageCell : CYTableViewCell <
4723 NSString *description_;
4731 - (PackageCell *) init;
4732 - (void) setPackage:(Package *)package;
4734 + (int) heightForPackage:(Package *)package;
4735 - (void) drawContentRect:(CGRect)rect;
4739 @implementation PackageCell
4741 - (void) clearPackage {
4752 if (description_ != nil) {
4753 [description_ release];
4757 if (source_ != nil) {
4762 if (badge_ != nil) {
4767 if (placard_ != nil) {
4777 [self clearPackage];
4781 - (PackageCell *) init {
4782 CGRect frame(CGRectMake(0, 0, 320, 74));
4783 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4784 UIView *content([self contentView]);
4785 CGRect bounds([content bounds]);
4787 content_ = [[ContentView alloc] initWithFrame:bounds];
4788 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4789 [content addSubview:content_];
4791 [content_ setDelegate:self];
4792 [content_ setOpaque:YES];
4796 - (void) _setBackgroundColor {
4798 if (NSString *mode = [package_ mode]) {
4799 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4800 color = remove ? RemovingColor_ : InstallingColor_;
4802 color = [UIColor whiteColor];
4804 [content_ setBackgroundColor:color];
4805 [self setNeedsDisplay];
4808 - (void) setPackage:(Package *)package {
4809 [self clearPackage];
4812 Source *source = [package source];
4814 icon_ = [[package icon] retain];
4815 name_ = [[package name] retain];
4818 description_ = [package longDescription];
4819 if (description_ == nil)
4820 description_ = [package shortDescription];
4821 if (description_ != nil)
4822 description_ = [description_ retain];
4824 commercial_ = [package isCommercial];
4826 package_ = [package retain];
4828 NSString *label = nil;
4829 bool trusted = false;
4831 if (source != nil) {
4832 label = [source label];
4833 trusted = [source trusted];
4834 } else if ([[package id] isEqualToString:@"firmware"])
4835 label = UCLocalize("APPLE");
4837 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4839 NSString *from(label);
4841 NSString *section = [package simpleSection];
4842 if (section != nil && ![section isEqualToString:label]) {
4843 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4844 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4847 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4848 source_ = [from retain];
4850 if (NSString *purpose = [package primaryPurpose])
4851 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4852 badge_ = [badge_ retain];
4854 if ([package installed] != nil)
4855 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4856 placard_ = [placard_ retain];
4858 [self _setBackgroundColor];
4859 [content_ setNeedsDisplay];
4862 - (void) drawContentRect:(CGRect)rect {
4863 bool highlighted(highlighted_);
4864 float width([self bounds].size.width);
4867 CGContextRef context(UIGraphicsGetCurrentContext());
4868 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4869 CGContextFillRect(context, rect);
4874 rect.size = [icon_ size];
4876 rect.size.width /= 2;
4877 rect.size.height /= 2;
4879 rect.origin.x = 25 - rect.size.width / 2;
4880 rect.origin.y = 25 - rect.size.height / 2;
4882 [icon_ drawInRect:rect];
4885 if (badge_ != nil) {
4886 CGSize size = [badge_ size];
4888 [badge_ drawAtPoint:CGPointMake(
4889 36 - size.width / 2,
4890 36 - size.height / 2
4898 UISetColor(commercial_ ? Purple_ : Black_);
4899 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4900 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4903 UISetColor(commercial_ ? Purplish_ : Gray_);
4904 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4906 if (placard_ != nil)
4907 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4910 + (int) heightForPackage:(Package *)package {
4916 /* Section Cell {{{ */
4917 @interface SectionCell : CYTableViewCell <
4929 - (void) setSection:(Section *)section editing:(BOOL)editing;
4933 @implementation SectionCell
4935 - (void) clearSection {
4936 if (basic_ != nil) {
4941 if (section_ != nil) {
4951 if (count_ != nil) {
4958 [self clearSection];
4964 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4965 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4966 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4967 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4968 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4970 UIView *content([self contentView]);
4971 CGRect bounds([content bounds]);
4973 content_ = [[ContentView alloc] initWithFrame:bounds];
4974 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4975 [content addSubview:content_];
4976 [content_ setBackgroundColor:[UIColor whiteColor]];
4978 [content_ setDelegate:self];
4982 - (void) onSwitch:(id)sender {
4983 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4984 if (metadata == nil) {
4985 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4986 [Sections_ setObject:metadata forKey:basic_];
4990 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4993 - (void) setSection:(Section *)section editing:(BOOL)editing {
4994 if (editing != editing_) {
4996 [switch_ removeFromSuperview];
4998 [self addSubview:switch_];
5002 [self clearSection];
5004 if (section == nil) {
5005 name_ = [UCLocalize("ALL_PACKAGES") retain];
5008 basic_ = [section name];
5010 basic_ = [basic_ retain];
5012 section_ = [section localized];
5013 if (section_ != nil)
5014 section_ = [section_ retain];
5016 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5017 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5020 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5023 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5024 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5026 [content_ setNeedsDisplay];
5029 - (void) setFrame:(CGRect)frame {
5030 [super setFrame:frame];
5032 CGRect rect([switch_ frame]);
5033 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5036 - (void) drawContentRect:(CGRect)rect {
5037 bool highlighted(highlighted_);
5039 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5044 float width(rect.size.width);
5050 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5052 CGSize size = [count_ sizeWithFont:Font14_];
5056 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5062 /* File Table {{{ */
5063 @interface FileTable : CYViewController <
5064 UITableViewDataSource,
5067 _transient Database *database_;
5070 NSMutableArray *files_;
5074 - (id) initWithDatabase:(Database *)database;
5075 - (void) setPackage:(Package *)package;
5079 @implementation FileTable
5082 if (package_ != nil)
5091 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5092 return files_ == nil ? 0 : [files_ count];
5095 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5099 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5100 static NSString *reuseIdentifier = @"Cell";
5102 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5104 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5105 [cell setFont:[UIFont systemFontOfSize:16]];
5107 [cell setText:[files_ objectAtIndex:indexPath.row]];
5108 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5113 - (id) initWithDatabase:(Database *)database {
5114 if ((self = [super init]) != nil) {
5115 database_ = database;
5117 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5119 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5121 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5122 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5123 [list_ setRowHeight:24.0f];
5124 [[self view] addSubview:list_];
5126 [list_ setDataSource:self];
5127 [list_ setDelegate:self];
5131 - (void) setPackage:(Package *)package {
5132 if (package_ != nil) {
5133 [package_ autorelease];
5142 [files_ removeAllObjects];
5144 if (package != nil) {
5145 package_ = [package retain];
5146 name_ = [[package id] retain];
5148 if (NSArray *files = [package files])
5149 [files_ addObjectsFromArray:files];
5151 if ([files_ count] != 0) {
5152 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5153 [files_ removeObjectAtIndex:0];
5154 [files_ sortUsingSelector:@selector(compareByPath:)];
5156 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5157 [stack addObject:@"/"];
5159 for (int i(0), e([files_ count]); i != e; ++i) {
5160 NSString *file = [files_ objectAtIndex:i];
5161 while (![file hasPrefix:[stack lastObject]])
5162 [stack removeLastObject];
5163 NSString *directory = [stack lastObject];
5164 [stack addObject:[file stringByAppendingString:@"/"]];
5165 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5166 ([stack count] - 2) * 3, "",
5167 [file substringFromIndex:[directory length]]
5176 - (void) reloadData {
5177 [self setPackage:[database_ packageWithName:name_]];
5182 /* Package Controller {{{ */
5183 @interface PackageController : CYBrowserController <
5184 UIActionSheetDelegate
5186 _transient Database *database_;
5190 NSMutableArray *buttons_;
5191 UIBarButtonItem *button_;
5194 - (id) initWithDatabase:(Database *)database;
5195 - (void) setPackage:(Package *)package;
5199 @implementation PackageController
5202 if (package_ != nil)
5216 if ([self retainCount] == 1)
5217 [delegate_ setPackageController:self];
5221 /* XXX: this is not safe at all... localization of /fail/ */
5222 - (void) _clickButtonWithName:(NSString *)name {
5223 if ([name isEqualToString:UCLocalize("CLEAR")])
5224 [delegate_ clearPackage:package_];
5225 else if ([name isEqualToString:UCLocalize("INSTALL")])
5226 [delegate_ installPackage:package_];
5227 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5228 [delegate_ installPackage:package_];
5229 else if ([name isEqualToString:UCLocalize("REMOVE")])
5230 [delegate_ removePackage:package_];
5231 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5232 [delegate_ installPackage:package_];
5233 else _assert(false);
5236 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5237 NSString *context([sheet context]);
5239 if ([context isEqualToString:@"modify"]) {
5240 if (button != [sheet cancelButtonIndex]) {
5241 NSString *buttonName = [buttons_ objectAtIndex:button];
5242 [self _clickButtonWithName:buttonName];
5245 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5249 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5250 [super webView:view didClearWindowObject:window forFrame:frame];
5251 [window setValue:package_ forKey:@"package"];
5254 - (bool) _allowJavaScriptPanel {
5259 - (void) _customButtonClicked {
5260 int count([buttons_ count]);
5265 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5267 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5268 [buttons addObjectsFromArray:buttons_];
5270 UIActionSheet *sheet = [[[UIActionSheet alloc]
5273 cancelButtonTitle:nil
5274 destructiveButtonTitle:nil
5275 otherButtonTitles:nil
5278 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5280 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5281 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5283 [sheet setContext:@"modify"];
5285 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5289 // We don't want to allow non-commercial packages to do custom things to the install button,
5290 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5291 - (void) customButtonClicked {
5293 [super customButtonClicked];
5295 [self _customButtonClicked];
5298 - (void) reloadButtonClicked {
5299 // Don't reload a package view by clicking the button.
5302 - (void) applyLoadingTitle {
5303 // Don't show "Loading" as the title. Ever.
5306 - (UIBarButtonItem *) rightButton {
5311 - (id) initWithDatabase:(Database *)database {
5312 if ((self = [super init]) != nil) {
5313 database_ = database;
5314 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5315 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5319 - (void) setPackage:(Package *)package {
5320 if (package_ != nil) {
5321 [package_ autorelease];
5330 [buttons_ removeAllObjects];
5332 if (package != nil) {
5335 package_ = [package retain];
5336 name_ = [[package id] retain];
5337 commercial_ = [package isCommercial];
5339 if ([package_ mode] != nil)
5340 [buttons_ addObject:UCLocalize("CLEAR")];
5341 if ([package_ source] == nil);
5342 else if ([package_ upgradableAndEssential:NO])
5343 [buttons_ addObject:UCLocalize("UPGRADE")];
5344 else if ([package_ uninstalled])
5345 [buttons_ addObject:UCLocalize("INSTALL")];
5347 [buttons_ addObject:UCLocalize("REINSTALL")];
5348 if (![package_ uninstalled])
5349 [buttons_ addObject:UCLocalize("REMOVE")];
5356 switch ([buttons_ count]) {
5357 case 0: title = nil; break;
5358 case 1: title = [buttons_ objectAtIndex:0]; break;
5359 default: title = UCLocalize("MODIFY"); break;
5362 button_ = [[UIBarButtonItem alloc]
5364 style:UIBarButtonItemStylePlain
5366 action:@selector(customButtonClicked)
5372 - (bool) isLoading {
5373 return commercial_ ? [super isLoading] : false;
5376 - (void) reloadData {
5377 [self setPackage:[database_ packageWithName:name_]];
5382 /* Package Table {{{ */
5383 @interface PackageTable : UIView <
5384 UITableViewDataSource,
5387 _transient Database *database_;
5388 NSMutableArray *packages_;
5389 NSMutableArray *sections_;
5391 NSMutableArray *index_;
5392 NSMutableDictionary *indices_;
5393 // XXX: this target_ seems to be delegate_. :(
5394 _transient id target_;
5396 // XXX: why do we even have this delegate_?
5397 _transient id delegate_;
5400 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5402 - (void) setDelegate:(id)delegate;
5404 - (void) reloadData;
5405 - (void) resetCursor;
5407 - (UITableView *) list;
5409 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5411 - (void) deselectWithAnimation:(BOOL)animated;
5415 @implementation PackageTable
5418 [packages_ release];
5419 [sections_ release];
5427 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5428 NSInteger count([sections_ count]);
5429 return count == 0 ? 1 : count;
5432 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5433 if ([sections_ count] == 0)
5435 return [[sections_ objectAtIndex:section] name];
5438 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5439 if ([sections_ count] == 0)
5441 return [[sections_ objectAtIndex:section] count];
5444 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5445 Section *section([sections_ objectAtIndex:[path section]]);
5446 NSInteger row([path row]);
5447 Package *package([packages_ objectAtIndex:([section row] + row)]);
5451 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5452 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5454 cell = [[[PackageCell alloc] init] autorelease];
5455 [cell setPackage:[self packageAtIndexPath:path]];
5459 - (void) deselectWithAnimation:(BOOL)animated {
5460 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5463 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5464 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5467 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5468 Package *package([self packageAtIndexPath:path]);
5469 package = [database_ packageWithName:[package id]];
5470 [target_ performSelector:action_ withObject:package];
5474 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5475 return [packages_ count] > 20 ? index_ : nil;
5478 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5482 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5483 if ((self = [super initWithFrame:frame]) != nil) {
5484 database_ = database;
5489 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5490 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5492 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5493 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5495 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5496 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5497 [list_ setRowHeight:73.0f];
5498 [self addSubview:list_];
5500 [list_ setDataSource:self];
5501 [list_ setDelegate:self];
5505 - (void) setDelegate:(id)delegate {
5506 delegate_ = delegate;
5509 - (bool) hasPackage:(Package *)package {
5513 - (void) reloadData {
5514 NSArray *packages = [database_ packages];
5516 [packages_ removeAllObjects];
5517 [sections_ removeAllObjects];
5519 _profile(PackageTable$reloadData$Filter)
5520 for (Package *package in packages)
5521 if ([self hasPackage:package])
5522 [packages_ addObject:package];
5525 [index_ removeAllObjects];
5526 [indices_ removeAllObjects];
5528 Section *section = nil;
5530 _profile(PackageTable$reloadData$Section)
5531 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5535 _profile(PackageTable$reloadData$Section$Package)
5536 package = [packages_ objectAtIndex:offset];
5537 index = [package index];
5540 if (section == nil || [section index] != index) {
5541 _profile(PackageTable$reloadData$Section$Allocate)
5542 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5545 [index_ addObject:[section name]];
5546 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5548 _profile(PackageTable$reloadData$Section$Add)
5549 [sections_ addObject:section];
5553 [section addToCount];
5557 _profile(PackageTable$reloadData$List)
5562 - (void) resetCursor {
5563 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5566 - (UITableView *) list {
5570 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5571 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5576 /* Filtered Package Table {{{ */
5577 @interface FilteredPackageTable : PackageTable {
5583 - (void) setObject:(id)object;
5584 - (void) setObject:(id)object forFilter:(SEL)filter;
5586 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5590 @implementation FilteredPackageTable
5598 - (void) setFilter:(SEL)filter {
5601 /* XXX: this is an unsafe optimization of doomy hell */
5602 Method method(class_getInstanceMethod([Package class], filter));
5603 _assert(method != NULL);
5604 imp_ = method_getImplementation(method);
5605 _assert(imp_ != NULL);
5608 - (void) setObject:(id)object {
5614 object_ = [object retain];
5617 - (void) setObject:(id)object forFilter:(SEL)filter {
5618 [self setFilter:filter];
5619 [self setObject:object];
5622 - (bool) hasPackage:(Package *)package {
5623 _profile(FilteredPackageTable$hasPackage)
5624 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5628 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5629 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5630 [self setFilter:filter];
5631 object_ = [object retain];
5639 /* Filtered Package Controller {{{ */
5640 @interface FilteredPackageController : CYViewController {
5641 _transient Database *database_;
5642 FilteredPackageTable *packages_;
5646 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5650 @implementation FilteredPackageController
5653 [packages_ release];
5659 - (void) viewDidAppear:(BOOL)animated {
5660 [super viewDidAppear:animated];
5661 [packages_ deselectWithAnimation:animated];
5664 - (void) didSelectPackage:(Package *)package {
5665 PackageController *view([delegate_ packageController]);
5666 [view setPackage:package];
5667 [view setDelegate:delegate_];
5668 [[self navigationController] pushViewController:view animated:YES];
5671 - (NSString *) title { return title_; }
5673 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5674 if ((self = [super init]) != nil) {
5675 database_ = database;
5676 title_ = [title copy];
5677 [[self navigationItem] setTitle:title_];
5679 packages_ = [[FilteredPackageTable alloc]
5680 initWithFrame:[[self view] bounds]
5683 action:@selector(didSelectPackage:)
5688 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5689 [[self view] addSubview:packages_];
5693 - (void) reloadData {
5694 [packages_ reloadData];
5697 - (void) setDelegate:(id)delegate {
5698 [super setDelegate:delegate];
5699 [packages_ setDelegate:delegate];
5706 /* Add Source Controller {{{ */
5707 @interface AddSourceController : CYViewController {
5708 _transient Database *database_;
5711 - (id) initWithDatabase:(Database *)database;
5715 @implementation AddSourceController
5717 - (id) initWithDatabase:(Database *)database {
5718 if ((self = [super init]) != nil) {
5719 database_ = database;
5725 /* Source Cell {{{ */
5726 @interface SourceCell : CYTableViewCell <
5731 NSString *description_;
5735 - (void) setSource:(Source *)source;
5739 @implementation SourceCell
5741 - (void) clearSource {
5744 [description_ release];
5753 - (void) setSource:(Source *)source {
5757 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5759 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5760 icon_ = [icon_ retain];
5762 origin_ = [[source name] retain];
5763 label_ = [[source uri] retain];
5764 description_ = [[source description] retain];
5766 [content_ setNeedsDisplay];
5774 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5775 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5776 UIView *content([self contentView]);
5777 CGRect bounds([content bounds]);
5779 content_ = [[ContentView alloc] initWithFrame:bounds];
5780 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5781 [content_ setBackgroundColor:[UIColor whiteColor]];
5782 [content addSubview:content_];
5784 [content_ setDelegate:self];
5785 [content_ setOpaque:YES];
5789 - (void) drawContentRect:(CGRect)rect {
5790 bool highlighted(highlighted_);
5791 float width(rect.size.width);
5794 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5801 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5805 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5809 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5814 /* Source Table {{{ */
5815 @interface SourceTable : CYViewController <
5816 UITableViewDataSource,
5819 _transient Database *database_;
5821 NSMutableArray *sources_;
5825 UIProgressHUD *hud_;
5828 //NSURLConnection *installer_;
5829 NSURLConnection *trivial_;
5830 NSURLConnection *trivial_bz2_;
5831 NSURLConnection *trivial_gz_;
5832 //NSURLConnection *automatic_;
5837 - (id) initWithDatabase:(Database *)database;
5839 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5843 @implementation SourceTable
5845 - (void) _releaseConnection:(NSURLConnection *)connection {
5846 if (connection != nil) {
5847 [connection cancel];
5848 //[connection setDelegate:nil];
5849 [connection release];
5861 //[self _releaseConnection:installer_];
5862 [self _releaseConnection:trivial_];
5863 [self _releaseConnection:trivial_gz_];
5864 [self _releaseConnection:trivial_bz2_];
5865 //[self _releaseConnection:automatic_];
5872 - (void) viewDidAppear:(BOOL)animated {
5873 [super viewDidAppear:animated];
5874 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5877 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5878 return offset_ == 0 ? 1 : 2;
5881 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5882 switch (section + (offset_ == 0 ? 1 : 0)) {
5883 case 0: return UCLocalize("ENTERED_BY_USER");
5884 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5890 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5891 int count = [sources_ count];
5893 case 0: return (offset_ == 0 ? count : offset_);
5894 case 1: return count - offset_;
5900 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5902 switch (indexPath.section) {
5903 case 0: idx = indexPath.row; break;
5904 case 1: idx = indexPath.row + offset_; break;
5908 return [sources_ objectAtIndex:idx];
5911 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5912 Source *source = [self sourceAtIndexPath:indexPath];
5913 return [source description] == nil ? 56 : 73;
5916 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5917 static NSString *cellIdentifier = @"SourceCell";
5919 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5920 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5921 [cell setSource:[self sourceAtIndexPath:indexPath]];
5926 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5927 return UITableViewCellAccessoryDisclosureIndicator;
5930 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5931 Source *source = [self sourceAtIndexPath:indexPath];
5933 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5934 initWithDatabase:database_
5935 title:[source label]
5936 filter:@selector(isVisibleInSource:)
5940 [packages setDelegate:delegate_];
5942 [[self navigationController] pushViewController:packages animated:YES];
5945 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5946 Source *source = [self sourceAtIndexPath:indexPath];
5947 return [source record] != nil;
5950 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5951 Source *source = [self sourceAtIndexPath:indexPath];
5952 [Sources_ removeObjectForKey:[source key]];
5953 [delegate_ syncData];
5957 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5960 @"./", @"Distribution",
5961 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5963 [delegate_ syncData];
5966 - (NSString *) getWarning {
5967 NSString *href(href_);
5968 NSRange colon([href rangeOfString:@"://"]);
5969 if (colon.location != NSNotFound)
5970 href = [href substringFromIndex:(colon.location + 3)];
5971 href = [href stringByAddingPercentEscapes];
5972 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5973 href = [href stringByCachingURLWithCurrentCDN];
5975 NSURL *url([NSURL URLWithString:href]);
5977 NSStringEncoding encoding;
5978 NSError *error(nil);
5980 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5981 return [warning length] == 0 ? nil : warning;
5985 - (void) _endConnection:(NSURLConnection *)connection {
5986 // XXX: the memory management in this method is horribly awkward
5988 NSURLConnection **field = NULL;
5989 if (connection == trivial_)
5991 else if (connection == trivial_bz2_)
5992 field = &trivial_bz2_;
5993 else if (connection == trivial_gz_)
5994 field = &trivial_gz_;
5995 _assert(field != NULL);
5996 [connection release];
6001 trivial_bz2_ == nil &&
6007 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6010 UIAlertView *alert = [[[UIAlertView alloc]
6011 initWithTitle:UCLocalize("SOURCE_WARNING")
6014 cancelButtonTitle:UCLocalize("CANCEL")
6015 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6018 [alert setContext:@"warning"];
6019 [alert setNumberOfRows:1];
6023 } else if (error_ != nil) {
6024 UIAlertView *alert = [[[UIAlertView alloc]
6025 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6026 message:[error_ localizedDescription]
6028 cancelButtonTitle:UCLocalize("OK")
6029 otherButtonTitles:nil
6032 [alert setContext:@"urlerror"];
6035 UIAlertView *alert = [[[UIAlertView alloc]
6036 initWithTitle:UCLocalize("NOT_REPOSITORY")
6037 message:UCLocalize("NOT_REPOSITORY_EX")
6039 cancelButtonTitle:UCLocalize("OK")
6040 otherButtonTitles:nil
6043 [alert setContext:@"trivial"];
6047 [delegate_ setStatusBarShowsProgress:NO];
6048 [delegate_ removeProgressHUD:hud_];
6058 if (error_ != nil) {
6065 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6066 switch ([response statusCode]) {
6072 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6073 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6075 error_ = [error retain];
6076 [self _endConnection:connection];
6079 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6080 [self _endConnection:connection];
6083 - (NSString *) title { return UCLocalize("SOURCES"); }
6085 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6086 NSMutableURLRequest *request = [NSMutableURLRequest
6087 requestWithURL:[NSURL URLWithString:href]
6088 cachePolicy:NSURLRequestUseProtocolCachePolicy
6089 timeoutInterval:120.0
6092 [request setHTTPMethod:method];
6094 if (Machine_ != NULL)
6095 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6096 if (UniqueID_ != nil)
6097 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6099 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6101 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6104 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6105 NSString *context([alert context]);
6107 if ([context isEqualToString:@"source"]) {
6110 NSString *href = [[alert textField] text];
6112 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6114 if (![href hasSuffix:@"/"])
6115 href_ = [href stringByAppendingString:@"/"];
6118 href_ = [href_ retain];
6120 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6121 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6122 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6123 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6127 // XXX: this is stupid
6128 hud_ = [[delegate_ addProgressHUD] retain];
6129 [hud_ setText:UCLocalize("VERIFYING_URL")];
6138 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6139 } else if ([context isEqualToString:@"trivial"])
6140 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6141 else if ([context isEqualToString:@"urlerror"])
6142 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6143 else if ([context isEqualToString:@"warning"]) {
6158 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6162 - (id) initWithDatabase:(Database *)database {
6163 if ((self = [super init]) != nil) {
6164 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6165 [self updateButtonsForEditingStatus:NO animated:NO];
6167 database_ = database;
6168 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6170 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6171 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6172 [[self view] addSubview:list_];
6174 [list_ setDataSource:self];
6175 [list_ setDelegate:self];
6181 - (void) reloadData {
6183 if (!list.ReadMainList())
6186 [sources_ removeAllObjects];
6187 [sources_ addObjectsFromArray:[database_ sources]];
6189 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6192 int count([sources_ count]);
6194 for (int i = 0; i != count; i++) {
6195 if ([[sources_ objectAtIndex:i] record] == nil)
6200 [list_ setEditing:NO];
6201 [self updateButtonsForEditingStatus:NO animated:NO];
6205 - (void) addButtonClicked {
6206 /*[book_ pushPage:[[[AddSourceController alloc]
6211 UIAlertView *alert = [[[UIAlertView alloc]
6212 initWithTitle:UCLocalize("ENTER_APT_URL")
6215 cancelButtonTitle:UCLocalize("CANCEL")
6216 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6219 [alert setContext:@"source"];
6220 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6222 [alert setNumberOfRows:1];
6223 [alert addTextFieldWithValue:@"http://" label:@""];
6225 UITextInputTraits *traits = [[alert textField] textInputTraits];
6226 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6227 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6228 [traits setKeyboardType:UIKeyboardTypeURL];
6229 // XXX: UIReturnKeyDone
6230 [traits setReturnKeyType:UIReturnKeyNext];
6235 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6236 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6237 initWithTitle:UCLocalize("ADD")
6238 style:UIBarButtonItemStylePlain
6240 action:@selector(addButtonClicked)
6241 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6243 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6244 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6245 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6247 action:@selector(editButtonClicked)
6248 ] autorelease] animated:animated];
6250 if (IsWildcat_ && !editing)
6251 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6252 initWithTitle:UCLocalize("SETTINGS")
6253 style:UIBarButtonItemStylePlain
6255 action:@selector(settingsButtonClicked)
6259 - (void) settingsButtonClicked {
6260 [delegate_ showSettings];
6263 - (void) editButtonClicked {
6264 [list_ setEditing:![list_ isEditing] animated:YES];
6266 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6272 /* Installed Controller {{{ */
6273 @interface InstalledController : FilteredPackageController {
6277 - (id) initWithDatabase:(Database *)database;
6279 - (void) updateRoleButton;
6280 - (void) queueStatusDidChange;
6284 @implementation InstalledController
6290 - (NSString *) title { return UCLocalize("INSTALLED"); }
6292 - (id) initWithDatabase:(Database *)database {
6293 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6294 [self updateRoleButton];
6295 [self queueStatusDidChange];
6300 - (void) queueButtonClicked {
6305 - (void) queueStatusDidChange {
6309 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6310 initWithTitle:UCLocalize("QUEUE")
6311 style:UIBarButtonItemStyleDone
6313 action:@selector(queueButtonClicked)
6316 [[self navigationItem] setLeftBarButtonItem:nil];
6322 - (void) reloadData {
6323 [packages_ reloadData];
6326 - (void) updateRoleButton {
6327 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6328 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6329 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6330 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6332 action:@selector(roleButtonClicked)
6336 - (void) roleButtonClicked {
6337 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6338 [packages_ reloadData];
6341 [self updateRoleButton];
6344 - (void) setDelegate:(id)delegate {
6345 [super setDelegate:delegate];
6346 [packages_ setDelegate:delegate];
6352 /* Home Controller {{{ */
6353 @interface HomeController : CYBrowserController {
6358 @implementation HomeController
6360 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6361 [super _setMoreHeaders:request];
6364 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6365 if (UniqueID_ != nil)
6366 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6368 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6371 - (void) aboutButtonClicked {
6372 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6374 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6375 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6376 [alert setCancelButtonIndex:0];
6379 @"Copyright (C) 2008-2010\n"
6380 "Jay Freeman (saurik)\n"
6381 "saurik@saurik.com\n"
6382 "http://www.saurik.com/"
6388 - (void) viewWillAppear:(BOOL)animated {
6389 [super viewWillAppear:animated];
6390 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6393 - (void) viewWillDisappear:(BOOL)animated {
6394 [super viewWillDisappear:animated];
6395 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6399 if ((self = [super init]) != nil) {
6400 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6401 initWithTitle:UCLocalize("ABOUT")
6402 style:UIBarButtonItemStylePlain
6404 action:@selector(aboutButtonClicked)
6411 /* Manage Controller {{{ */
6412 @interface ManageController : CYBrowserController {
6415 - (void) queueStatusDidChange;
6418 @implementation ManageController
6421 if ((self = [super init]) != nil) {
6422 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6424 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6425 initWithTitle:UCLocalize("SETTINGS")
6426 style:UIBarButtonItemStylePlain
6428 action:@selector(settingsButtonClicked)
6431 [self queueStatusDidChange];
6435 - (void) settingsButtonClicked {
6436 [delegate_ showSettings];
6440 - (void) queueButtonClicked {
6444 - (void) applyLoadingTitle {
6445 // No "Loading" title.
6448 - (void) applyRightButton {
6453 - (void) queueStatusDidChange {
6455 if (!IsWildcat_ && Queuing_) {
6456 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6457 initWithTitle:UCLocalize("QUEUE")
6458 style:UIBarButtonItemStyleDone
6460 action:@selector(queueButtonClicked)
6463 [[self navigationItem] setRightBarButtonItem:nil];
6468 - (bool) isLoading {
6475 /* Refresh Bar {{{ */
6476 @interface RefreshBar : UINavigationBar {
6477 UIProgressIndicator *indicator_;
6478 UITextLabel *prompt_;
6479 UIProgressBar *progress_;
6480 UINavigationButton *cancel_;
6485 @implementation RefreshBar
6488 [indicator_ release];
6490 [progress_ release];
6495 - (void) positionViews {
6496 CGRect frame = [cancel_ frame];
6497 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6498 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6499 [cancel_ setFrame:frame];
6501 CGSize prgsize = {75, 100};
6503 [self frame].size.width - prgsize.width - 10,
6504 ([self frame].size.height - prgsize.height) / 2
6506 [progress_ setFrame:prgrect];
6508 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6509 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6510 CGRect indrect = {{indoffset, indoffset}, indsize};
6511 [indicator_ setFrame:indrect];
6513 CGSize prmsize = {215, indsize.height + 4};
6515 indoffset * 2 + indsize.width,
6516 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6518 [prompt_ setFrame:prmrect];
6521 - (void)setFrame:(CGRect)frame {
6522 [super setFrame:frame];
6524 [self positionViews];
6527 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6528 if ((self = [super initWithFrame:frame])) {
6529 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6531 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6532 [self setBarStyle:UIBarStyleBlack];
6534 UIBarStyle barstyle([self _barStyle:NO]);
6535 bool ugly(barstyle == UIBarStyleDefault);
6537 UIProgressIndicatorStyle style = ugly ?
6538 UIProgressIndicatorStyleMediumBrown :
6539 UIProgressIndicatorStyleMediumWhite;
6541 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6542 [indicator_ setStyle:style];
6543 [indicator_ startAnimation];
6544 [self addSubview:indicator_];
6546 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6547 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6548 [prompt_ setBackgroundColor:[UIColor clearColor]];
6549 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6550 [self addSubview:prompt_];
6552 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6553 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6554 [progress_ setStyle:0];
6555 [self addSubview:progress_];
6557 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6558 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6559 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6560 [cancel_ setBarStyle:barstyle];
6562 [self positionViews];
6567 [cancel_ removeFromSuperview];
6571 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6572 [progress_ setProgress:0];
6573 [self addSubview:cancel_];
6577 [cancel_ removeFromSuperview];
6580 - (void) setPrompt:(NSString *)prompt {
6581 [prompt_ setText:prompt];
6584 - (void) setProgress:(float)progress {
6585 [progress_ setProgress:progress];
6591 @class CYNavigationController;
6593 /* Cydia Tab Bar Controller {{{ */
6594 @interface CYTabBarController : UITabBarController {
6595 _transient Database *database_;
6600 @implementation CYTabBarController
6602 /* XXX: some logic should probably go here related to
6603 freeing the view controllers on tab change */
6605 - (void) reloadData {
6606 size_t count([[self viewControllers] count]);
6607 for (size_t i(0); i != count; ++i) {
6608 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6613 - (id) initWithDatabase:(Database *)database {
6614 if ((self = [super init]) != nil) {
6615 database_ = database;
6622 /* Cydia Navigation Controller {{{ */
6623 @interface CYNavigationController : UINavigationController {
6624 _transient Database *database_;
6625 _transient id<UINavigationControllerDelegate> delegate_;
6628 - (id) initWithDatabase:(Database *)database;
6629 - (void) reloadData;
6634 @implementation CYNavigationController
6636 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6637 // Inherit autorotation settings for modal parents.
6638 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6639 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6641 return [super shouldAutorotateToInterfaceOrientation:orientation];
6649 - (void) reloadData {
6650 size_t count([[self viewControllers] count]);
6651 for (size_t i(0); i != count; ++i) {
6652 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6657 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6658 delegate_ = delegate;
6661 - (id) initWithDatabase:(Database *)database {
6662 if ((self = [super init]) != nil) {
6663 database_ = database;
6669 /* Cydia:// Protocol {{{ */
6670 @interface CydiaURLProtocol : NSURLProtocol {
6675 @implementation CydiaURLProtocol
6677 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6678 NSURL *url([request URL]);
6681 NSString *scheme([[url scheme] lowercaseString]);
6682 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6687 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6691 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6692 id<NSURLProtocolClient> client([self client]);
6694 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6696 NSData *data(UIImagePNGRepresentation(icon));
6698 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6699 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6700 [client URLProtocol:self didLoadData:data];
6701 [client URLProtocolDidFinishLoading:self];
6705 - (void) startLoading {
6706 id<NSURLProtocolClient> client([self client]);
6707 NSURLRequest *request([self request]);
6709 NSURL *url([request URL]);
6710 NSString *href([url absoluteString]);
6712 NSString *path([href substringFromIndex:8]);
6713 NSRange slash([path rangeOfString:@"/"]);
6716 if (slash.location == NSNotFound) {
6720 command = [path substringToIndex:slash.location];
6721 path = [path substringFromIndex:(slash.location + 1)];
6724 Database *database([Database sharedInstance]);
6726 if ([command isEqualToString:@"package-icon"]) {
6729 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6730 Package *package([database packageWithName:path]);
6733 UIImage *icon([package icon]);
6734 [self _returnPNGWithImage:icon forRequest:request];
6735 } else if ([command isEqualToString:@"source-icon"]) {
6738 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6739 NSString *source(Simplify(path));
6740 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6742 icon = [UIImage applicationImageNamed:@"unknown.png"];
6743 [self _returnPNGWithImage:icon forRequest:request];
6744 } else if ([command isEqualToString:@"uikit-image"]) {
6747 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6748 UIImage *icon(_UIImageWithName(path));
6749 [self _returnPNGWithImage:icon forRequest:request];
6750 } else if ([command isEqualToString:@"section-icon"]) {
6753 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6754 NSString *section(Simplify(path));
6755 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6757 icon = [UIImage applicationImageNamed:@"unknown.png"];
6758 [self _returnPNGWithImage:icon forRequest:request];
6760 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6764 - (void) stopLoading {
6770 /* Sections Controller {{{ */
6771 @interface SectionsController : CYViewController <
6772 UITableViewDataSource,
6775 _transient Database *database_;
6776 NSMutableArray *sections_;
6777 NSMutableArray *filtered_;
6783 - (id) initWithDatabase:(Database *)database;
6784 - (void) reloadData;
6787 - (void) editButtonClicked;
6791 @implementation SectionsController
6794 [list_ setDataSource:nil];
6795 [list_ setDelegate:nil];
6797 [sections_ release];
6798 [filtered_ release];
6800 [accessory_ release];
6804 - (void) viewDidAppear:(BOOL)animated {
6805 [super viewDidAppear:animated];
6806 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6809 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6810 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6814 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6815 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6818 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6822 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6823 static NSString *reuseIdentifier = @"SectionCell";
6825 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6827 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6829 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6834 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6838 Section *section = [self sectionAtIndexPath:indexPath];
6839 NSString *name = [section name];
6842 if ([indexPath row] == 0) {
6845 title = UCLocalize("ALL_PACKAGES");
6848 name = [NSString stringWithString:name];
6849 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6852 title = UCLocalize("NO_SECTION");
6856 FilteredPackageController *table = [[[FilteredPackageController alloc]
6857 initWithDatabase:database_
6859 filter:@selector(isVisibleInSection:)
6863 [table setDelegate:delegate_];
6865 [[self navigationController] pushViewController:table animated:YES];
6868 - (NSString *) title { return UCLocalize("SECTIONS"); }
6870 - (id) initWithDatabase:(Database *)database {
6871 if ((self = [super init]) != nil) {
6872 database_ = database;
6874 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6876 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6877 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6879 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6880 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6881 [list_ setRowHeight:45.0f];
6882 [[self view] addSubview:list_];
6884 [list_ setDataSource:self];
6885 [list_ setDelegate:self];
6891 - (void) reloadData {
6892 NSArray *packages = [database_ packages];
6894 [sections_ removeAllObjects];
6895 [filtered_ removeAllObjects];
6897 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6900 for (Package *package in packages) {
6901 NSString *name([package section]);
6902 NSString *key(name == nil ? @"" : name);
6906 _profile(SectionsView$reloadData$Section)
6907 section = [sections objectForKey:key];
6908 if (section == nil) {
6909 _profile(SectionsView$reloadData$Section$Allocate)
6910 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6911 [sections setObject:section forKey:key];
6916 [section addToCount];
6918 _profile(SectionsView$reloadData$Filter)
6919 if (![package valid] || ![package visible])
6927 [sections_ addObjectsFromArray:[sections allValues]];
6929 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6931 for (Section *section in sections_) {
6932 size_t count([section row]);
6936 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6937 [section setCount:count];
6938 [filtered_ addObject:section];
6941 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6942 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
6943 style:UIBarButtonItemStylePlain
6945 action:@selector(editButtonClicked)
6946 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6952 - (void) resetView {
6954 [self editButtonClicked];
6957 - (void) editButtonClicked {
6958 if ((editing_ = !editing_))
6961 [delegate_ updateData];
6963 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6964 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6965 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6968 - (UIView *) accessoryView {
6974 /* Changes Controller {{{ */
6975 @interface ChangesController : CYViewController <
6976 UITableViewDataSource,
6979 _transient Database *database_;
6980 CFMutableArrayRef packages_;
6981 NSMutableArray *sections_;
6984 BOOL hasSentFirstLoad_;
6987 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6988 - (void) reloadData;
6992 @implementation ChangesController
6995 [list_ setDelegate:nil];
6996 [list_ setDataSource:nil];
6998 CFRelease(packages_);
7000 [sections_ release];
7005 - (void) viewDidAppear:(BOOL)animated {
7006 [super viewDidAppear:animated];
7007 if (!hasSentFirstLoad_) {
7008 hasSentFirstLoad_ = YES;
7009 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7011 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7015 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7016 NSInteger count([sections_ count]);
7017 return count == 0 ? 1 : count;
7020 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7021 if ([sections_ count] == 0)
7023 return [[sections_ objectAtIndex:section] name];
7026 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7027 if ([sections_ count] == 0)
7029 return [[sections_ objectAtIndex:section] count];
7032 - (Package *) packageAtIndex:(NSUInteger)index {
7033 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7036 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7037 Section *section([sections_ objectAtIndex:[path section]]);
7038 NSInteger row([path row]);
7039 return [self packageAtIndex:([section row] + row)];
7042 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7043 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7045 cell = [[[PackageCell alloc] init] autorelease];
7046 [cell setPackage:[self packageAtIndexPath:path]];
7050 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7051 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7054 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7055 Package *package([self packageAtIndexPath:path]);
7056 PackageController *view([delegate_ packageController]);
7057 [view setDelegate:delegate_];
7058 [view setPackage:package];
7059 [[self navigationController] pushViewController:view animated:YES];
7063 - (void) refreshButtonClicked {
7064 [delegate_ beginUpdate];
7065 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7068 - (void) upgradeButtonClicked {
7069 [delegate_ distUpgrade];
7072 - (NSString *) title { return UCLocalize("CHANGES"); }
7074 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7075 if ((self = [super init]) != nil) {
7076 database_ = database;
7077 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7079 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7081 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7083 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7084 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7085 [list_ setRowHeight:73.0f];
7086 [[self view] addSubview:list_];
7088 [list_ setDataSource:self];
7089 [list_ setDelegate:self];
7091 delegate_ = delegate;
7095 - (void) _reloadPackages:(NSArray *)packages {
7097 for (Package *package in packages)
7098 if ([package upgradableAndEssential:YES] || [package visible])
7099 CFArrayAppendValue(packages_, package);
7102 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7106 - (void) reloadData {
7107 NSArray *packages = [database_ packages];
7109 CFArrayRemoveAllValues(packages_);
7111 [sections_ removeAllObjects];
7114 UIProgressHUD *hud([delegate_ addProgressHUD]);
7115 [hud setText:UCLocalize("LOADING")];
7116 //NSLog(@"HUD:%@::%@", delegate_, hud);
7117 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7118 [delegate_ removeProgressHUD:hud];
7120 [self _reloadPackages:packages];
7123 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7124 Section *ignored = nil;
7125 Section *section = nil;
7129 bool unseens = false;
7131 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7133 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7134 Package *package = [self packageAtIndex:offset];
7136 BOOL uae = [package upgradableAndEssential:YES];
7140 time_t seen([package seen]);
7142 if (section == nil || last != seen) {
7146 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7149 _profile(ChangesController$reloadData$Allocate)
7150 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7151 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7152 [sections_ addObject:section];
7156 [section addToCount];
7157 } else if ([package ignored]) {
7158 if (ignored == nil) {
7159 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7161 [ignored addToCount];
7164 [upgradable addToCount];
7169 CFRelease(formatter);
7172 Section *last = [sections_ lastObject];
7173 size_t count = [last count];
7174 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7175 [sections_ removeLastObject];
7178 if ([ignored count] != 0)
7179 [sections_ insertObject:ignored atIndex:0];
7181 [sections_ insertObject:upgradable atIndex:0];
7186 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7187 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7188 style:UIBarButtonItemStylePlain
7190 action:@selector(upgradeButtonClicked)
7193 if (![delegate_ updating])
7194 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7195 initWithTitle:UCLocalize("REFRESH")
7196 style:UIBarButtonItemStylePlain
7198 action:@selector(refreshButtonClicked)
7204 /* Search Controller {{{ */
7205 @interface SearchController : FilteredPackageController <
7208 UISearchBar *search_;
7211 - (id) initWithDatabase:(Database *)database;
7212 - (void) reloadData;
7216 @implementation SearchController
7223 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7224 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7225 [search_ resignFirstResponder];
7229 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7230 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7234 - (NSString *) title { return nil; }
7236 - (id) initWithDatabase:(Database *)database {
7237 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7240 - (void)viewDidAppear:(BOOL)animated {
7241 [super viewDidAppear:animated];
7243 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7244 [search_ layoutSubviews];
7245 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7246 UITextField *textField = [search_ searchField];
7247 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7248 [search_ setDelegate:self];
7249 [textField setEnablesReturnKeyAutomatically:NO];
7250 [[self navigationItem] setTitleView:textField];
7254 - (void) _reloadData {
7257 - (void) reloadData {
7258 _profile(SearchController$reloadData)
7259 [packages_ reloadData];
7262 [packages_ resetCursor];
7265 - (void) didSelectPackage:(Package *)package {
7266 [search_ resignFirstResponder];
7267 [super didSelectPackage:package];
7272 /* Settings Controller {{{ */
7273 @interface SettingsController : CYViewController <
7274 UITableViewDataSource,
7277 _transient Database *database_;
7280 UITableView *table_;
7281 UISwitch *subscribedSwitch_;
7282 UISwitch *ignoredSwitch_;
7283 UITableViewCell *subscribedCell_;
7284 UITableViewCell *ignoredCell_;
7287 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7291 @implementation SettingsController
7295 if (package_ != nil)
7298 [subscribedSwitch_ release];
7299 [ignoredSwitch_ release];
7300 [subscribedCell_ release];
7301 [ignoredCell_ release];
7306 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7307 if (package_ == nil)
7313 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7314 if (package_ == nil)
7320 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7321 return UCLocalize("SHOW_ALL_CHANGES_EX");
7324 - (void) onSubscribed:(id)control {
7325 bool value([control isOn]);
7326 if (package_ == nil)
7328 if ([package_ setSubscribed:value])
7329 [delegate_ updateData];
7332 - (void) onIgnored:(id)control {
7333 // TODO: set Held state - possibly call out to dpkg, etc.
7336 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7337 if (package_ == nil)
7340 switch ([indexPath row]) {
7341 case 0: return subscribedCell_;
7342 case 1: return ignoredCell_;
7350 - (NSString *) title { return UCLocalize("SETTINGS"); }
7352 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7353 if ((self = [super init])) {
7354 database_ = database;
7355 name_ = [package retain];
7357 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7359 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7360 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7361 [[self view] addSubview:table_];
7363 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7364 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7365 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7367 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7368 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7369 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7371 subscribedCell_ = [[UITableViewCell alloc] init];
7372 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7373 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7374 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7376 ignoredCell_ = [[UITableViewCell alloc] init];
7377 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7378 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7379 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7381 [table_ setDataSource:self];
7382 [table_ setDelegate:self];
7387 - (void) reloadData {
7388 if (package_ != nil)
7389 [package_ autorelease];
7390 package_ = [database_ packageWithName:name_];
7391 if (package_ != nil) {
7393 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7394 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7397 [table_ reloadData];
7402 /* Signature Controller {{{ */
7403 @interface SignatureController : CYBrowserController {
7404 _transient Database *database_;
7408 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7412 @implementation SignatureController
7419 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7421 [super webView:view didClearWindowObject:window forFrame:frame];
7424 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7425 if ((self = [super init]) != nil) {
7426 database_ = database;
7427 package_ = [package retain];
7432 - (void) reloadData {
7433 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7439 /* Role Controller {{{ */
7440 @interface RoleController : CYViewController <
7441 UITableViewDataSource,
7444 _transient Database *database_;
7445 // XXX: ok, "roledelegate_"?...
7446 _transient id roledelegate_;
7447 UITableView *table_;
7448 UISegmentedControl *segment_;
7452 - (void) showDoneButton;
7453 - (void) resizeSegmentedControl;
7457 @implementation RoleController
7461 [container_ release];
7466 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7467 if ((self = [super init])) {
7468 database_ = database;
7469 roledelegate_ = delegate;
7471 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7473 NSArray *items = [NSArray arrayWithObjects:
7475 UCLocalize("HACKER"),
7476 UCLocalize("DEVELOPER"),
7478 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7479 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7480 [container_ addSubview:segment_];
7483 if ([Role_ isEqualToString:@"User"]) index = 0;
7484 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7485 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7487 [segment_ setSelectedSegmentIndex:index];
7488 [self showDoneButton];
7491 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7492 [self resizeSegmentedControl];
7494 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7495 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7496 [table_ setDelegate:self];
7497 [table_ setDataSource:self];
7498 [[self view] addSubview:table_];
7499 [table_ reloadData];
7503 - (void) resizeSegmentedControl {
7504 CGFloat width = [[self view] frame].size.width;
7505 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7508 - (void) viewWillAppear:(BOOL)animated {
7509 [super viewWillAppear:animated];
7511 [self resizeSegmentedControl];
7514 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7515 [self resizeSegmentedControl];
7518 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7519 [self resizeSegmentedControl];
7523 NSString *role(nil);
7525 switch ([segment_ selectedSegmentIndex]) {
7526 case 0: role = @"User"; break;
7527 case 1: role = @"Hacker"; break;
7528 case 2: role = @"Developer"; break;
7533 if (![role isEqualToString:Role_]) {
7534 bool rolling(Role_ == nil);
7537 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7541 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7546 [roledelegate_ loadData];
7548 [roledelegate_ updateData];
7552 - (void) segmentChanged:(UISegmentedControl *)control {
7553 [self showDoneButton];
7556 - (void) saveAndClose {
7559 [[self navigationItem] setRightBarButtonItem:nil];
7560 [[self navigationController] dismissModalViewControllerAnimated:YES];
7563 - (void) doneButtonClicked {
7564 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7565 [spinner startAnimating];
7566 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7567 [[self navigationItem] setRightBarButtonItem:spinItem];
7569 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7572 - (void) showDoneButton {
7573 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7574 initWithTitle:UCLocalize("DONE")
7575 style:UIBarButtonItemStyleDone
7577 action:@selector(doneButtonClicked)
7578 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7581 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7582 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7586 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7590 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7591 return nil; // This method is required by the protocol.
7594 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7596 return UCLocalize("ROLE_EX");
7598 return [NSString stringWithFormat:
7599 @"%@: %@\n%@: %@\n%@: %@",
7600 UCLocalize("USER"), UCLocalize("USER_EX"),
7601 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7602 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7607 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7608 return section == 3 ? 44.0f : 0;
7611 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7612 return section == 3 ? container_ : nil;
7617 /* Stash Controller {{{ */
7618 @interface CYStashController : CYViewController {
7619 // XXX: just delete these things
7620 _transient UIActivityIndicatorView *spinner_;
7621 _transient UILabel *status_;
7622 _transient UILabel *caption_;
7626 @implementation CYStashController
7628 if ((self = [super init])) {
7629 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7631 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7632 CGRect spinrect = [spinner_ frame];
7633 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7634 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7635 [spinner_ setFrame:spinrect];
7636 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7637 [[self view] addSubview:spinner_];
7638 [spinner_ startAnimating];
7641 captrect.size.width = [[self view] frame].size.width;
7642 captrect.size.height = 40.0f;
7643 captrect.origin.x = 0;
7644 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7645 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7646 [caption_ setText:@"Initializing Filesystem"];
7647 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7648 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7649 [caption_ setTextColor:[UIColor whiteColor]];
7650 [caption_ setBackgroundColor:[UIColor clearColor]];
7651 [caption_ setShadowColor:[UIColor blackColor]];
7652 [caption_ setTextAlignment:UITextAlignmentCenter];
7653 [[self view] addSubview:caption_];
7656 statusrect.size.width = [[self view] frame].size.width;
7657 statusrect.size.height = 30.0f;
7658 statusrect.origin.x = 0;
7659 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7660 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7661 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7662 [status_ setText:@"(Cydia will exit when complete.)"];
7663 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7664 [status_ setTextColor:[UIColor whiteColor]];
7665 [status_ setBackgroundColor:[UIColor clearColor]];
7666 [status_ setShadowColor:[UIColor blackColor]];
7667 [status_ setTextAlignment:UITextAlignmentCenter];
7668 [[self view] addSubview:status_];
7672 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7673 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7678 /* Cydia Container {{{ */
7679 @interface CYContainer : UIViewController <ProgressDelegate> {
7680 _transient Database *database_;
7681 RefreshBar *refreshbar_;
7685 // XXX: ok, "updatedelegate_"?...
7686 _transient NSObject<CydiaDelegate> *updatedelegate_;
7687 // XXX: can't we query for this variable when we need it?
7688 _transient UITabBarController *root_;
7691 - (void) setTabBarController:(UITabBarController *)controller;
7693 - (void) dropBar:(BOOL)animated;
7694 - (void) beginUpdate;
7695 - (void) raiseBar:(BOOL)animated;
7700 @implementation CYContainer
7702 - (BOOL) _reallyWantsFullScreenLayout {
7706 // NOTE: UIWindow only sends the top controller these messages,
7707 // So we have to forward them on.
7709 - (void) viewDidAppear:(BOOL)animated {
7710 [super viewDidAppear:animated];
7711 [root_ viewDidAppear:animated];
7714 - (void) viewWillAppear:(BOOL)animated {
7715 [super viewWillAppear:animated];
7716 [root_ viewWillAppear:animated];
7719 - (void) viewDidDisappear:(BOOL)animated {
7720 [super viewDidDisappear:animated];
7721 [root_ viewDidDisappear:animated];
7724 - (void) viewWillDisappear:(BOOL)animated {
7725 [super viewWillDisappear:animated];
7726 [root_ viewWillDisappear:animated];
7729 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7730 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7733 - (void) setTabBarController:(UITabBarController *)controller {
7735 [[self view] addSubview:[root_ view]];
7738 - (void) setUpdate:(NSDate *)date {
7742 - (void) beginUpdate {
7744 [refreshbar_ start];
7749 detachNewThreadSelector:@selector(performUpdate)
7755 - (void) performUpdate { _pooled
7757 status.setDelegate(self);
7758 [database_ updateWithStatus:status];
7761 performSelectorOnMainThread:@selector(completeUpdate)
7767 - (void) completeUpdate {
7772 [self raiseBar:YES];
7774 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7777 - (void) cancelUpdate {
7779 [self raiseBar:YES];
7781 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7784 - (void) cancelPressed {
7785 [self cancelUpdate];
7792 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7793 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7796 - (void) startProgress {
7799 - (void) setProgressTitle:(NSString *)title {
7801 performSelectorOnMainThread:@selector(_setProgressTitle:)
7807 - (bool) isCancelling:(size_t)received {
7811 - (void) setProgressPercent:(float)percent {
7813 performSelectorOnMainThread:@selector(_setProgressPercent:)
7814 withObject:[NSNumber numberWithFloat:percent]
7819 - (void) addProgressOutput:(NSString *)output {
7821 performSelectorOnMainThread:@selector(_addProgressOutput:)
7827 - (void) _setProgressTitle:(NSString *)title {
7828 [refreshbar_ setPrompt:title];
7831 - (void) _setProgressPercent:(NSNumber *)percent {
7832 [refreshbar_ setProgress:[percent floatValue]];
7835 - (void) _addProgressOutput:(NSString *)output {
7838 - (void) setUpdateDelegate:(id)delegate {
7839 updatedelegate_ = delegate;
7842 - (CGFloat) statusBarHeight {
7843 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7844 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7846 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7850 - (void) dropBar:(BOOL)animated {
7855 [[self view] addSubview:refreshbar_];
7857 CGFloat sboffset = [self statusBarHeight];
7859 CGRect barframe = [refreshbar_ frame];
7860 barframe.origin.y = sboffset;
7861 [refreshbar_ setFrame:barframe];
7864 [UIView beginAnimations:nil context:NULL];
7865 CGRect viewframe = [[root_ view] frame];
7866 viewframe.origin.y += barframe.size.height + sboffset;
7867 viewframe.size.height -= barframe.size.height + sboffset;
7868 [[root_ view] setFrame:viewframe];
7870 [UIView commitAnimations];
7872 // Ensure bar has the proper width for our view, it might have changed
7873 barframe.size.width = viewframe.size.width;
7874 [refreshbar_ setFrame:barframe];
7876 // XXX: fix Apple's layout bug
7877 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7880 - (void) raiseBar:(BOOL)animated {
7885 [refreshbar_ removeFromSuperview];
7887 CGFloat sboffset = [self statusBarHeight];
7890 [UIView beginAnimations:nil context:NULL];
7891 CGRect barframe = [refreshbar_ frame];
7892 CGRect viewframe = [[root_ view] frame];
7893 viewframe.origin.y -= barframe.size.height + sboffset;
7894 viewframe.size.height += barframe.size.height + sboffset;
7895 [[root_ view] setFrame:viewframe];
7897 [UIView commitAnimations];
7899 // XXX: fix Apple's layout bug
7900 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7903 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7904 // XXX: fix Apple's layout bug
7905 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7908 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7914 // XXX: fix Apple's layout bug
7915 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7918 - (void) statusBarFrameChanged:(NSNotification *)notification {
7926 [refreshbar_ release];
7927 [[NSNotificationCenter defaultCenter] removeObserver:self];
7931 - (id) initWithDatabase:(Database *)database {
7932 if ((self = [super init]) != nil) {
7933 database_ = database;
7935 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7936 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7938 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7955 @interface Cydia : UIApplication <
7956 ConfirmationControllerDelegate,
7957 ProgressControllerDelegate,
7959 UINavigationControllerDelegate,
7960 UITabBarControllerDelegate
7962 // XXX: evaluate all fields for _transient
7965 CYContainer *container_;
7966 CYTabBarController *tabbar_;
7968 NSMutableArray *essential_;
7969 NSMutableArray *broken_;
7971 Database *database_;
7977 SectionsController *sections_;
7978 ChangesController *changes_;
7979 ManageController *manage_;
7980 SearchController *search_;
7981 SourceTable *sources_;
7982 InstalledController *installed_;
7985 CYStashController *stash_;
7990 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7991 - (void) setPage:(CYViewController *)page;
7996 static _finline void _setHomePage(Cydia *self) {
7997 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
8000 @implementation Cydia
8002 - (void) beginUpdate {
8003 [container_ beginUpdate];
8007 return [container_ updating];
8010 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8015 if ([broken_ count] != 0) {
8016 int count = [broken_ count];
8018 UIAlertView *alert = [[[UIAlertView alloc]
8019 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8020 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8022 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8023 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8026 [alert setContext:@"fixhalf"];
8028 } else if (!Ignored_ && [essential_ count] != 0) {
8029 int count = [essential_ count];
8031 UIAlertView *alert = [[[UIAlertView alloc]
8032 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8033 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8035 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8036 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8039 [alert setContext:@"upgrade"];
8044 - (void) _saveConfig {
8047 NSString *error(nil);
8048 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8050 NSError *error(nil);
8051 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8052 NSLog(@"failure to save metadata data: %@", error);
8055 NSLog(@"failure to serialize metadata: %@", error);
8063 - (void) _updateData {
8066 /* XXX: this is just stupid */
8067 if (tag_ != 1 && sections_ != nil)
8068 [sections_ reloadData];
8069 if (tag_ != 2 && changes_ != nil)
8070 [changes_ reloadData];
8071 if (tag_ != 4 && search_ != nil)
8072 [search_ reloadData];
8074 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8077 - (int)indexOfTabWithTag:(int)tag {
8079 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8080 if ([[controller tabBarItem] tag] == tag)
8088 - (void) _refreshIfPossible {
8089 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8091 bool recently = false;
8092 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8093 if (update != nil) {
8094 NSTimeInterval interval([update timeIntervalSinceNow]);
8095 if (interval <= 0 && interval > -(15*60))
8099 // Don't automatic refresh if:
8100 // - We already refreshed recently.
8101 // - We already auto-refreshed this launch.
8102 // - Auto-refresh is disabled.
8103 if (recently || loaded_ || ManualRefresh) {
8104 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8106 // If we are cancelling due to ManualRefresh or a recent refresh
8107 // we need to make sure it knows it's already loaded.
8111 // We are going to load, so remember that.
8115 SCNetworkReachabilityFlags flags; {
8116 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8117 SCNetworkReachabilityGetFlags(reachability, &flags);
8118 CFRelease(reachability);
8121 // XXX: this elaborate mess is what Apple is using to determine this? :(
8122 // XXX: do we care if the user has to intervene? maybe that's ok?
8124 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8125 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8126 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8127 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8128 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8129 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8133 // If we can reach the server, auto-refresh!
8135 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8140 - (void) refreshIfPossible {
8141 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8144 - (void) _reloadData {
8145 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8146 [hud setText:UCLocalize("RELOADING_DATA")];
8148 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8151 [self removeProgressHUD:hud];
8155 [essential_ removeAllObjects];
8156 [broken_ removeAllObjects];
8158 NSArray *packages([database_ packages]);
8159 for (Package *package in packages) {
8161 [broken_ addObject:package];
8162 if ([package upgradableAndEssential:NO]) {
8163 if ([package essential])
8164 [essential_ addObject:package];
8169 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8171 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8172 [changesItem setBadgeValue:badge];
8173 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8175 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8176 [self setApplicationBadge:badge];
8178 [self setApplicationBadgeString:badge];
8180 [changesItem setBadgeValue:nil];
8181 [changesItem setAnimatedBadge:NO];
8183 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8184 [self removeApplicationBadge];
8185 else // XXX: maybe use setApplicationBadgeString also?
8186 [self setApplicationIconBadgeNumber:0];
8191 [self refreshIfPossible];
8194 - (void) updateData {
8203 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8204 _assert(file != NULL);
8206 for (NSString *key in [Sources_ allKeys]) {
8207 NSDictionary *source([Sources_ objectForKey:key]);
8209 fprintf(file, "%s %s %s\n",
8210 [[source objectForKey:@"Type"] UTF8String],
8211 [[source objectForKey:@"URI"] UTF8String],
8212 [[source objectForKey:@"Distribution"] UTF8String]
8220 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8221 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8223 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8224 [container_ presentModalViewController:navigation animated:YES];
8227 detachNewThreadSelector:@selector(update_)
8230 title:UCLocalize("UPDATING_SOURCES")
8234 - (void) reloadData {
8235 @synchronized (self) {
8241 pkgProblemResolver *resolver = [database_ resolver];
8243 resolver->InstallProtect();
8244 if (!resolver->Resolve(true))
8248 - (CGRect) popUpBounds {
8249 return [[tabbar_ view] bounds];
8253 if (![database_ prepare])
8256 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8257 [page setDelegate:self];
8258 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8259 [confirm_ setDelegate:self];
8262 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8263 [container_ presentModalViewController:confirm_ animated:YES];
8269 @synchronized (self) {
8274 - (void) clearPackage:(Package *)package {
8275 @synchronized (self) {
8282 - (void) installPackages:(NSArray *)packages {
8283 @synchronized (self) {
8284 for (Package *package in packages)
8291 - (void) installPackage:(Package *)package {
8292 @synchronized (self) {
8299 - (void) removePackage:(Package *)package {
8300 @synchronized (self) {
8307 - (void) distUpgrade {
8308 @synchronized (self) {
8309 if (![database_ upgrade])
8316 @synchronized (self) {
8321 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8322 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8324 if (navigation != nil) {
8325 [navigation pushViewController:progress animated:YES];
8327 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8329 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8330 [container_ presentModalViewController:navigation animated:YES];
8334 detachNewThreadSelector:@selector(perform)
8337 title:UCLocalize("RUNNING")
8341 - (void) progressControllerIsComplete:(ProgressController *)progress {
8345 - (void) setPage:(CYViewController *)page {
8346 [page setDelegate:self];
8348 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8349 [navController setViewControllers:[NSArray arrayWithObject:page]];
8350 for (CYNavigationController *page in [tabbar_ viewControllers])
8351 if (page != navController)
8352 [page setViewControllers:nil];
8355 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8356 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8357 [browser loadURL:url];
8361 - (SectionsController *) sectionsController {
8362 if (sections_ == nil)
8363 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8367 - (ChangesController *) changesController {
8368 if (changes_ == nil)
8369 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8373 - (ManageController *) manageController {
8374 if (manage_ == nil) {
8375 manage_ = (ManageController *) [[self
8376 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8377 withClass:[ManageController class]
8380 queueDelegate_ = manage_;
8385 - (SearchController *) searchController {
8387 search_ = [[SearchController alloc] initWithDatabase:database_];
8391 - (SourceTable *) sourcesController {
8392 if (sources_ == nil)
8393 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8397 - (InstalledController *) installedController {
8398 if (installed_ == nil) {
8399 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8401 queueDelegate_ = installed_;
8406 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8407 int tag = [[viewController tabBarItem] tag];
8409 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8411 } else if (tag_ == 1) {
8412 [[self sectionsController] resetView];
8416 case kCydiaTag: _setHomePage(self); break;
8418 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8419 case kChangesTag: [self setPage:[self changesController]]; break;
8420 case kManageTag: [self setPage:[self manageController]]; break;
8421 case kInstalledTag: [self setPage:[self installedController]]; break;
8422 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8423 case kSearchTag: [self setPage:[self searchController]]; break;
8431 - (void) showSettings {
8432 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8433 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8435 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8436 [container_ presentModalViewController:nav animated:YES];
8439 - (void) setPackageController:(PackageController *)view {
8441 [view setPackage:nil];
8445 - (PackageController *) _packageController {
8446 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8449 - (PackageController *) packageController {
8450 return [self _packageController];
8453 // Returns the navigation controller for the queuing badge.
8454 - (id) queueBadgeController {
8455 int index = [self indexOfTabWithTag:kManageTag];
8457 index = [self indexOfTabWithTag:kInstalledTag];
8459 return [[tabbar_ viewControllers] objectAtIndex:index];
8462 - (void) cancelAndClear:(bool)clear {
8463 @synchronized (self) {
8469 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8473 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8477 [queueDelegate_ queueStatusDidChange];
8481 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8482 NSString *context([alert context]);
8484 if ([context isEqualToString:@"fixhalf"]) {
8485 if (button == [alert firstOtherButtonIndex]) {
8486 @synchronized (self) {
8487 for (Package *broken in broken_) {
8490 NSString *id = [broken id];
8491 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8492 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8493 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8494 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8500 } else if (button == [alert cancelButtonIndex]) {
8501 [broken_ removeAllObjects];
8505 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8506 } else if ([context isEqualToString:@"upgrade"]) {
8507 if (button == [alert firstOtherButtonIndex]) {
8508 @synchronized (self) {
8509 for (Package *essential in essential_)
8510 [essential install];
8515 } else if (button == [alert firstOtherButtonIndex] + 1) {
8517 } else if (button == [alert cancelButtonIndex]) {
8521 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8525 - (void) system:(NSString *)command { _pooled
8526 system([command UTF8String]);
8529 - (void) applicationWillSuspend {
8531 [super applicationWillSuspend];
8534 - (BOOL) hudIsShowing {
8535 return (hudcount_ > 0);
8538 - (void) applicationSuspend:(__GSEvent *)event {
8539 // Use external process status API internally.
8540 // This is probably a really bad idea.
8541 uint64_t status = 0;
8543 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8544 notify_get_state(notify_token, &status);
8545 notify_cancel(notify_token);
8548 if (![self hudIsShowing] && status == 0)
8549 [super applicationSuspend:event];
8552 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8553 if (![self hudIsShowing])
8554 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8557 - (void) _setSuspended:(BOOL)value {
8558 if (![self hudIsShowing])
8559 [super _setSuspended:value];
8562 - (UIProgressHUD *) addProgressHUD {
8563 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8564 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8566 [window_ setUserInteractionEnabled:NO];
8569 UIViewController *target = container_;
8570 while ([target modalViewController] != nil) target = [target modalViewController];
8571 [[target view] addSubview:hud];
8577 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8579 [hud removeFromSuperview];
8580 [window_ setUserInteractionEnabled:YES];
8584 - (CYViewController *) pageForPackage:(NSString *)name {
8585 if (Package *package = [database_ packageWithName:name]) {
8586 PackageController *view([self packageController]);
8587 [view setPackage:package];
8590 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8591 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8592 return [self _pageForURL:url withClass:[CYBrowserController class]];
8596 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8600 NSString *href([url absoluteString]);
8601 if ([href hasPrefix:@"apptapp://package/"])
8602 return [self pageForPackage:[href substringFromIndex:18]];
8604 NSString *scheme([[url scheme] lowercaseString]);
8605 if (![scheme isEqualToString:@"cydia"])
8607 NSString *path([url absoluteString]);
8608 if ([path length] < 8)
8610 path = [path substringFromIndex:8];
8611 if (![path hasPrefix:@"/"])
8612 path = [@"/" stringByAppendingString:path];
8614 if ([path isEqualToString:@"/add-source"])
8615 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8616 else if ([path isEqualToString:@"/storage"])
8617 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8618 else if ([path isEqualToString:@"/sources"])
8619 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8620 else if ([path isEqualToString:@"/packages"])
8621 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8622 else if ([path hasPrefix:@"/url/"])
8623 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8624 else if ([path hasPrefix:@"/launch/"])
8625 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8626 else if ([path hasPrefix:@"/package-settings/"])
8627 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8628 else if ([path hasPrefix:@"/package-signature/"])
8629 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8630 else if ([path hasPrefix:@"/package/"])
8631 return [self pageForPackage:[path substringFromIndex:9]];
8632 else if ([path hasPrefix:@"/files/"]) {
8633 NSString *name = [path substringFromIndex:7];
8635 if (Package *package = [database_ packageWithName:name]) {
8636 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8637 [files setPackage:package];
8645 - (BOOL) openCydiaURL:(NSURL *)url {
8646 CYViewController *page = nil;
8649 NSLog(@"open url: %@", url);
8651 if ((page = [self pageForURL:url hasTag:&tag])) {
8652 [self setPage:page];
8654 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8660 - (void) applicationOpenURL:(NSURL *)url {
8661 [super applicationOpenURL:url];
8662 NSLog(@"first: %@", url);
8663 if (!loaded_) starturl_ = [url retain];
8664 else [self openCydiaURL:url];
8667 - (void) applicationWillResignActive:(UIApplication *)application {
8668 // Stop refreshing if you get a phone call or lock the device.
8669 if ([container_ updating])
8670 [container_ cancelUpdate];
8672 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8673 [super applicationWillResignActive:application];
8676 - (void) addStashController {
8677 stash_ = [[CYStashController alloc] init];
8678 [window_ addSubview:[stash_ view]];
8681 - (void) removeStashController {
8682 [[stash_ view] removeFromSuperview];
8687 [self setIdleTimerDisabled:YES];
8689 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8690 [self setStatusBarShowsProgress:YES];
8691 UpdateExternalStatus(1);
8693 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8695 UpdateExternalStatus(0);
8696 [self setStatusBarShowsProgress:NO];
8698 [self removeStashController];
8700 if (ExecFork() == 0) {
8701 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8702 perror("launchctl stop");
8706 - (void) setupTabBarController {
8707 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8708 [tabbar_ setDelegate:self];
8710 NSMutableArray *items([NSMutableArray arrayWithObjects:
8711 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8712 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8713 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8714 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8718 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8719 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8721 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8724 NSMutableArray *controllers([NSMutableArray array]);
8726 for (UITabBarItem *item in items) {
8727 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8728 [controller setTabBarItem:item];
8729 [controllers addObject:controller];
8732 [tabbar_ setViewControllers:controllers];
8735 - (void) applicationDidFinishLaunching:(id)unused {
8736 [CYBrowserController _initialize];
8738 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8740 Font12_ = [[UIFont systemFontOfSize:12] retain];
8741 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8742 Font14_ = [[UIFont systemFontOfSize:14] retain];
8743 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8744 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8748 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8749 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8751 UIScreen *screen([UIScreen mainScreen]);
8753 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8754 [window_ orderFront:self];
8755 [window_ makeKey:self];
8756 [window_ setHidden:NO];
8759 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8760 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8761 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8762 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8763 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8764 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8765 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8766 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8767 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8770 [self addStashController];
8771 // XXX: this would be much cleaner as a yieldToSelector:
8772 // that way the removeStashController could happen right here inline
8773 // we also could no longer require the useless stash_ field anymore
8774 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8778 database_ = [Database sharedInstance];
8780 [self setupTabBarController];
8782 container_ = [[CYContainer alloc] initWithDatabase:database_];
8783 [container_ setUpdateDelegate:self];
8784 [container_ setTabBarController:tabbar_];
8785 [window_ addSubview:[container_ view]];
8787 // Show pinstripes while loading data.
8788 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8790 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8797 [self showSettings];
8801 [window_ setUserInteractionEnabled:NO];
8803 UIView *container = [[[UIView alloc] init] autorelease];
8804 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8806 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8807 [spinner startAnimating];
8808 [container addSubview:spinner];
8810 UILabel *label = [[[UILabel alloc] init] autorelease];
8811 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8812 [label setBackgroundColor:[UIColor clearColor]];
8813 [label setTextColor:[UIColor blackColor]];
8814 [label setShadowColor:[UIColor whiteColor]];
8815 [label setShadowOffset:CGSizeMake(0, 1)];
8816 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8817 [container addSubview:label];
8819 CGSize viewsize = [[tabbar_ view] frame].size;
8820 CGSize spinnersize = [spinner bounds].size;
8821 CGSize textsize = [[label text] sizeWithFont:[label font]];
8822 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8824 CGRect containrect = {
8825 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8826 CGSizeMake(bothwidth, spinnersize.height)
8829 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8837 [container setFrame:containrect];
8838 [spinner setFrame:spinrect];
8839 [label setFrame:textrect];
8840 [[container_ view] addSubview:container];
8845 // Show the initial page
8846 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
8847 [tabbar_ setSelectedIndex:0];
8851 [starturl_ release];
8854 [window_ setUserInteractionEnabled:YES];
8856 // XXX: does this actually slow anything down?
8857 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8858 [container removeFromSuperview];
8861 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8862 if (item != nil && IsWildcat_) {
8863 [sheet showFromBarButtonItem:item animated:YES];
8865 [sheet showInView:window_];
8872 id Alloc_(id self, SEL selector) {
8873 id object = alloc_(self, selector);
8874 lprintf("[%s]A-%p\n", self->isa->name, object);
8879 id Dealloc_(id self, SEL selector) {
8880 id object = dealloc_(self, selector);
8881 lprintf("[%s]D-%p\n", self->isa->name, object);
8885 Class $WebDefaultUIKitDelegate;
8887 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8888 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8889 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8890 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8893 static NSNumber *shouldPlayKeyboardSounds;
8897 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8899 case 1104: // Keyboard Button Clicked
8900 case 1105: // Keyboard Delete Repeated
8901 if (shouldPlayKeyboardSounds == nil) {
8902 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8903 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8906 if (![shouldPlayKeyboardSounds boolValue])
8910 _UIHardware$_playSystemSound$(self, _cmd, sound);
8914 int main(int argc, char *argv[]) { _pooled
8917 if (Class $UIDevice = objc_getClass("UIDevice")) {
8918 UIDevice *device([$UIDevice currentDevice]);
8919 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8923 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8925 /* Library Hacks {{{ */
8926 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8928 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8929 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8930 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8931 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8932 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8935 $UIHardware = objc_getClass("UIHardware");
8936 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8937 if (UIHardware$_playSystemSound$ != NULL) {
8938 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8939 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8942 /* Set Locale {{{ */
8943 Locale_ = CFLocaleCopyCurrent();
8944 Languages_ = [NSLocale preferredLanguages];
8945 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8946 //NSLog(@"%@", [Languages_ description]);
8949 if (Languages_ == nil || [Languages_ count] == 0)
8950 // XXX: consider just setting to C and then falling through?
8953 lang = [[Languages_ objectAtIndex:0] UTF8String];
8954 setenv("LANG", lang, true);
8957 //std::setlocale(LC_ALL, lang);
8958 NSLog(@"Setting Language: %s", lang);
8961 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8963 /* Parse Arguments {{{ */
8964 bool substrate(false);
8970 for (int argi(1); argi != argc; ++argi)
8971 if (strcmp(argv[argi], "--") == 0) {
8973 argv[argi] = argv[0];
8979 for (int argi(1); argi != arge; ++argi)
8980 if (strcmp(args[argi], "--substrate") == 0)
8983 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8987 App_ = [[NSBundle mainBundle] bundlePath];
8988 Home_ = NSHomeDirectory();
8994 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8995 alloc_ = alloc->method_imp;
8996 alloc->method_imp = (IMP) &Alloc_;*/
8998 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8999 dealloc_ = dealloc->method_imp;
9000 dealloc->method_imp = (IMP) &Dealloc_;*/
9002 /* System Information {{{ */
9006 size = sizeof(maxproc);
9007 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9008 perror("sysctlbyname(\"kern.maxproc\", ?)");
9009 else if (maxproc < 64) {
9011 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9012 perror("sysctlbyname(\"kern.maxproc\", #)");
9015 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9016 char *osversion = new char[size];
9017 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9018 perror("sysctlbyname(\"kern.osversion\", ?)");
9020 System_ = [NSString stringWithUTF8String:osversion];
9022 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9023 char *machine = new char[size];
9024 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9025 perror("sysctlbyname(\"hw.machine\", ?)");
9029 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9030 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9031 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9032 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9036 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9037 NSData *data((NSData *) ecid);
9038 size_t length([data length]);
9039 uint8_t bytes[length];
9040 [data getBytes:bytes];
9041 char string[length * 2 + 1];
9042 for (size_t i(0); i != length; ++i)
9043 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9044 ChipID_ = [NSString stringWithUTF8String:string];
9048 IOObjectRelease(service);
9052 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9054 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9055 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9056 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9058 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9059 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9060 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9062 if (mcc != NULL && mnc != NULL)
9063 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9070 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9071 Build_ = [system objectForKey:@"ProductBuildVersion"];
9072 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9073 Product_ = [info objectForKey:@"SafariProductVersion"];
9074 Safari_ = [info objectForKey:@"CFBundleVersion"];
9077 /* Load Database {{{ */
9079 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9081 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9083 if (Metadata_ == NULL)
9084 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9086 Settings_ = [Metadata_ objectForKey:@"Settings"];
9088 Packages_ = [Metadata_ objectForKey:@"Packages"];
9089 Sections_ = [Metadata_ objectForKey:@"Sections"];
9090 Sources_ = [Metadata_ objectForKey:@"Sources"];
9092 Token_ = [Metadata_ objectForKey:@"Token"];
9095 if (Settings_ != nil)
9096 Role_ = [Settings_ objectForKey:@"Role"];
9098 if (Sections_ == nil) {
9099 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9100 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9103 if (Sources_ == nil) {
9104 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9105 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9110 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9113 if (Packages_ != nil) {
9114 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9116 [Metadata_ removeObjectForKey:@"Packages"];
9121 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9123 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9124 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9125 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9126 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9127 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9128 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9130 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9132 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9133 unlink("/tmp/.cydia.fw");
9135 } else if (access("/User", F_OK) != 0 || version < 2) {
9138 system("/usr/libexec/cydia/firmware.sh");
9142 _assert([[NSFileManager defaultManager]
9143 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9144 withIntermediateDirectories:YES
9149 if (access("/tmp/cydia.chk", F_OK) == 0) {
9150 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9151 _assert(errno == ENOENT);
9152 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9153 _assert(errno == ENOENT);
9156 /* APT Initialization {{{ */
9157 _assert(pkgInitConfig(*_config));
9158 _assert(pkgInitSystem(*_config, _system));
9161 _config->Set("APT::Acquire::Translation", lang);
9163 // XXX: this timeout might be important :(
9164 //_config->Set("Acquire::http::Timeout", 15);
9166 _config->Set("Acquire::http::MaxParallel", 3);
9168 /* Color Choices {{{ */
9169 space_ = CGColorSpaceCreateDeviceRGB();
9171 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9172 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9173 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9174 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9175 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9176 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9177 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9178 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9179 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9181 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9182 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9184 /* UIKit Configuration {{{ */
9185 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9186 if ($GSFontSetUseLegacyFontMetrics != NULL)
9187 $GSFontSetUseLegacyFontMetrics(YES);
9189 // XXX: I have a feeling this was important
9190 //UIKeyboardDisableAutomaticAppearance();
9193 Colon_ = UCLocalize("COLON_DELIMITED");
9194 Elision_ = UCLocalize("ELISION");
9195 Error_ = UCLocalize("ERROR");
9196 Warning_ = UCLocalize("WARNING");
9199 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9201 CGColorSpaceRelease(space_);