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, Cytore::Offset<PackageValue> *cache = NULL) {
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_;
1489 static void PackageImport(const void *key, const void *value, void *context) {
1491 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1492 NSLog(@"failed to import package %@", key);
1496 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1497 NSDictionary *package((NSDictionary *) value);
1499 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1500 if ([subscribed boolValue])
1501 metadata->subscribed_ = true;
1503 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1504 time_t time([date timeIntervalSince1970]);
1505 if (metadata->first_ > time || metadata->first_ == 0)
1506 metadata->first_ = time;
1509 if (NSDate *date = [package objectForKey:@"LastSeen"]) {
1510 time_t time([date timeIntervalSince1970]);
1511 if (metadata->last_ < time || metadata->last_ == 0) {
1512 metadata->last_ = time;
1515 } else if (metadata->last_ == 0) last: {
1516 NSString *version([package objectForKey:@"LastVersion"]);
1517 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1518 size_t length(strlen(buffer));
1519 uint16_t vhash(hashlittle(buffer, length));
1521 size_t capped(std::min<size_t>(8, length));
1522 char *latest(buffer + length - capped);
1524 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1525 metadata->vhash_ = vhash;
1531 /* Source Class {{{ */
1532 @interface Source : NSObject {
1533 CYString depiction_;
1534 CYString description_;
1540 CYString distribution_;
1545 NSString *authority_;
1547 CYString defaultIcon_;
1549 NSDictionary *record_;
1553 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1555 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1557 - (NSString *) depictionForPackage:(NSString *)package;
1558 - (NSString *) supportForPackage:(NSString *)package;
1560 - (NSDictionary *) record;
1564 - (NSString *) distribution;
1565 - (NSString *) type;
1567 - (NSString *) host;
1569 - (NSString *) name;
1570 - (NSString *) description;
1571 - (NSString *) label;
1572 - (NSString *) origin;
1573 - (NSString *) version;
1575 - (NSString *) defaultIcon;
1579 @implementation Source
1583 distribution_.clear();
1586 description_.clear();
1592 defaultIcon_.clear();
1594 if (record_ != nil) {
1604 if (authority_ != nil) {
1605 [authority_ release];
1611 // XXX: this is a very inefficient way to call these deconstructors
1616 + (NSArray *) _attributeKeys {
1617 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1620 - (NSArray *) attributeKeys {
1621 return [[self class] _attributeKeys];
1624 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1625 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1628 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1631 trusted_ = index->IsTrusted();
1633 uri_.set(pool, index->GetURI());
1634 distribution_.set(pool, index->GetDist());
1635 type_.set(pool, index->GetType());
1637 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1638 if (dindex != NULL) {
1640 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1643 pkgTagFile tags(&fd);
1645 pkgTagSection section;
1652 {"default-icon", &defaultIcon_},
1653 {"depiction", &depiction_},
1654 {"description", &description_},
1656 {"origin", &origin_},
1657 {"support", &support_},
1658 {"version", &version_},
1661 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1662 const char *start, *end;
1664 if (section.Find(names[i].name_, start, end)) {
1665 CYString &value(*names[i].value_);
1666 value.set(pool, start, end - start);
1672 record_ = [Sources_ objectForKey:[self key]];
1674 record_ = [record_ retain];
1676 NSURL *url([NSURL URLWithString:uri_]);
1680 host_ = [[host_ lowercaseString] retain];
1685 authority_ = [url path];
1687 if (authority_ != nil)
1688 authority_ = [authority_ retain];
1691 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1692 if ((self = [super init]) != nil) {
1693 [self setMetaIndex:index inPool:pool];
1697 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1698 NSDictionary *lhr = [self record];
1699 NSDictionary *rhr = [source record];
1702 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1704 NSString *lhs = [self name];
1705 NSString *rhs = [source name];
1707 if ([lhs length] != 0 && [rhs length] != 0) {
1708 unichar lhc = [lhs characterAtIndex:0];
1709 unichar rhc = [rhs characterAtIndex:0];
1711 if (isalpha(lhc) && !isalpha(rhc))
1712 return NSOrderedAscending;
1713 else if (!isalpha(lhc) && isalpha(rhc))
1714 return NSOrderedDescending;
1717 return [lhs compare:rhs options:LaxCompareOptions_];
1720 - (NSString *) depictionForPackage:(NSString *)package {
1721 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1724 - (NSString *) supportForPackage:(NSString *)package {
1725 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1728 - (NSDictionary *) record {
1736 - (NSString *) uri {
1740 - (NSString *) distribution {
1741 return distribution_;
1744 - (NSString *) type {
1748 - (NSString *) key {
1749 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1752 - (NSString *) host {
1756 - (NSString *) name {
1757 return origin_.empty() ? authority_ : origin_;
1760 - (NSString *) description {
1761 return description_;
1764 - (NSString *) label {
1765 return label_.empty() ? authority_ : label_;
1768 - (NSString *) origin {
1772 - (NSString *) version {
1776 - (NSString *) defaultIcon {
1777 return defaultIcon_;
1782 /* Relationship Class {{{ */
1783 @interface Relationship : NSObject {
1788 - (NSString *) type;
1790 - (NSString *) name;
1794 @implementation Relationship
1802 - (NSString *) type {
1810 - (NSString *) name {
1817 /* Package Class {{{ */
1818 struct ParsedPackage {
1823 CYString depiction_;
1833 @interface Package : NSObject {
1837 pkgCache::VerIterator version_;
1838 pkgCache::PkgIterator iterator_;
1839 _transient Database *database_;
1840 pkgCache::VerFileIterator file_;
1843 ParsedPackage *parsed_;
1846 _transient NSString *section$_;
1851 CYString installed_;
1856 NSMutableArray *tags_;
1859 Cytore::Offset<PackageValue> metadata_;
1864 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1865 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1867 - (pkgCache::PkgIterator) iterator;
1870 - (NSString *) section;
1871 - (NSString *) simpleSection;
1873 - (NSString *) longSection;
1874 - (NSString *) shortSection;
1878 - (Address *) maintainer;
1880 - (NSString *) longDescription;
1881 - (NSString *) shortDescription;
1884 - (PackageValue *) metadata;
1887 - (bool) subscribed;
1888 - (bool) setSubscribed:(bool)subscribed;
1892 - (NSString *) latest;
1893 - (NSString *) installed;
1894 - (BOOL) uninstalled;
1897 - (BOOL) upgradableAndEssential:(BOOL)essential;
1900 - (BOOL) unfiltered;
1904 - (BOOL) halfConfigured;
1905 - (BOOL) halfInstalled;
1907 - (NSString *) mode;
1910 - (NSString *) name;
1912 - (NSString *) homepage;
1913 - (NSString *) depiction;
1914 - (Address *) author;
1916 - (NSString *) support;
1918 - (NSArray *) files;
1919 - (NSArray *) warnings;
1920 - (NSArray *) applications;
1922 - (Source *) source;
1923 - (NSString *) role;
1925 - (BOOL) matches:(NSString *)text;
1927 - (bool) hasSupportingRole;
1928 - (BOOL) hasTag:(NSString *)tag;
1929 - (NSString *) primaryPurpose;
1930 - (NSArray *) purposes;
1931 - (bool) isCommercial;
1933 - (CYString &) cyname;
1935 - (uint32_t) compareBySection:(NSArray *)sections;
1940 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1941 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1942 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1943 - (bool) isVisibleInSection:(NSString *)section;
1944 - (bool) isVisibleInSource:(Source *)source;
1948 uint32_t PackageChangesRadix(Package *self, void *) {
1953 uint32_t timestamp : 30;
1954 uint32_t ignored : 1;
1955 uint32_t upgradable : 1;
1959 bool upgradable([self upgradableAndEssential:YES]);
1960 value.bits.upgradable = upgradable ? 1 : 0;
1963 value.bits.timestamp = 0;
1964 value.bits.ignored = [self ignored] ? 0 : 1;
1965 value.bits.upgradable = 1;
1967 value.bits.timestamp = [self seen] >> 2;
1968 value.bits.ignored = 0;
1969 value.bits.upgradable = 0;
1972 return _not(uint32_t) - value.key;
1975 _finline static void Stifle(uint8_t &value) {
1978 uint32_t PackagePrefixRadix(Package *self, void *context) {
1979 size_t offset(reinterpret_cast<size_t>(context));
1980 CYString &name([self cyname]);
1982 size_t size(name.size());
1985 char *text(name.data());
1988 if (!isdigit(text[0]))
1992 while (size != digits && isdigit(text[digits]))
2002 if (offset == 0 && zeros != 0) {
2003 memset(data, '0', zeros);
2004 memcpy(data + zeros, text, 4 - zeros);
2006 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2007 if (size <= offset - zeros)
2010 text += offset - zeros;
2011 size -= offset - zeros;
2014 memcpy(data, text, 4);
2016 memcpy(data, text, size);
2017 memset(data + size, 0, 4 - size);
2020 for (size_t i(0); i != 4; ++i)
2021 if (isalpha(data[i]))
2029 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2031 /* XXX: ntohl may be more honest */
2032 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2035 CYString &(*PackageName)(Package *self, SEL sel);
2037 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2038 _profile(PackageNameCompare)
2039 CYString &lhi(PackageName(lhs, @selector(cyname)));
2040 CYString &rhi(PackageName(rhs, @selector(cyname)));
2041 CFStringRef lhn(lhi), rhn(rhi);
2044 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2045 else if (rhn == NULL)
2046 return NSOrderedDescending;
2048 _profile(PackageNameCompare$NumbersLast)
2049 if (!lhi.empty() && !rhi.empty()) {
2050 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2051 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2052 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2053 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2054 return lha ? NSOrderedAscending : NSOrderedDescending;
2058 CFIndex length = CFStringGetLength(lhn);
2060 _profile(PackageNameCompare$Compare)
2061 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2066 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2067 return PackageNameCompare(*lhs, *rhs, context);
2070 struct PackageNameOrdering :
2071 std::binary_function<Package *, Package *, bool>
2073 _finline bool operator ()(Package *lhs, Package *rhs) const {
2074 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2078 @implementation Package
2080 - (NSString *) description {
2081 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2085 if (parsed_ != NULL)
2099 + (NSString *) webScriptNameForSelector:(SEL)selector {
2100 if (selector == @selector(hasTag:))
2106 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2107 return [self webScriptNameForSelector:selector] == nil;
2110 + (NSArray *) _attributeKeys {
2111 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];
2114 - (NSArray *) attributeKeys {
2115 return [[self class] _attributeKeys];
2118 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2119 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2123 if (parsed_ != NULL)
2125 @synchronized (database_) {
2126 if ([database_ era] != era_ || file_.end())
2129 ParsedPackage *parsed(new ParsedPackage);
2132 _profile(Package$parse)
2133 pkgRecords::Parser *parser;
2135 _profile(Package$parse$Lookup)
2136 parser = &[database_ records]->Lookup(file_);
2141 _profile(Package$parse$Find)
2146 {"icon", &parsed->icon_},
2147 {"depiction", &parsed->depiction_},
2148 {"homepage", &parsed->homepage_},
2149 {"website", &website},
2150 {"bugs", &parsed->bugs_},
2151 {"support", &parsed->support_},
2152 {"sponsor", &parsed->sponsor_},
2153 {"author", &parsed->author_},
2156 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2157 const char *start, *end;
2159 if (parser->Find(names[i].name_, start, end)) {
2160 CYString &value(*names[i].value_);
2161 _profile(Package$parse$Value)
2162 value.set(pool_, start, end - start);
2168 _profile(Package$parse$Tagline)
2169 const char *start, *end;
2170 if (parser->ShortDesc(start, end)) {
2171 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2174 while (stop != start && stop[-1] == '\r')
2176 parsed->tagline_.set(pool_, start, stop - start);
2180 _profile(Package$parse$Retain)
2181 if (parsed->homepage_.empty())
2182 parsed->homepage_ = website;
2183 if (parsed->homepage_ == parsed->depiction_)
2184 parsed->homepage_.clear();
2189 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2190 if ((self = [super init]) != nil) {
2191 _profile(Package$initWithVersion)
2192 era_ = [database era];
2197 _profile(Package$initWithVersion$ParentPkg)
2198 iterator_ = version.ParentPkg();
2201 database_ = database;
2203 _profile(Package$initWithVersion$Latest)
2204 latest_.set(NULL, StripVersion_(version_.VerStr()));
2207 pkgCache::VerIterator current;
2208 _profile(Package$initWithVersion$Versions)
2209 current = iterator_.CurrentVer();
2211 installed_.set(NULL, StripVersion_(current.VerStr()));
2213 if (!version_.end())
2214 file_ = version_.FileList();
2216 pkgCache &cache([database_ cache]);
2217 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2221 _profile(Package$initWithVersion$Name)
2222 id_.set(NULL, iterator_.Name());
2223 name_.set(NULL, iterator_.Display());
2226 _profile(Package$initWithVersion$lowercaseString)
2227 // XXX: do not use tolower() as this is not locale-specific? :(
2228 char *data(id_.data());
2229 for (size_t i(0), e(id_.size()); i != e; ++i)
2230 if ((data[i] & 0x20) == 0) {
2239 _profile(Package$initWithVersion$Tags)
2240 pkgCache::TagIterator tag(iterator_.TagList());
2242 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2244 const char *name(tag.Name());
2245 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2246 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2247 role_ = (NSString *) CYStringCreate(name + 6);
2249 } while (!tag.end());
2253 _profile(Package$initWithVersion$Metadata)
2254 PackageValue *metadata(PackageFind(id_.data(), id_.size(), &metadata_));
2256 const char *latest(version_.VerStr());
2257 size_t length(strlen(latest));
2259 uint16_t vhash(hashlittle(latest, length));
2261 size_t capped(std::min<size_t>(8, length));
2262 latest = latest + length - capped;
2264 if (metadata->first_ == 0)
2265 metadata->first_ = now_;
2267 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2268 metadata->last_ = now_;
2269 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2270 metadata->vhash_ = vhash;
2271 } else if (metadata->last_ == 0)
2272 metadata->last_ = metadata->first_;
2275 _profile(Package$initWithVersion$Section)
2276 section_.set(NULL, iterator_.Section());
2279 _profile(Package$initWithVersion$hasTag)
2280 obsolete_ = [self hasTag:@"cydia::obsolete"];
2281 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2284 ignored_ = iterator_->SelectedState == pkgCache::State::Hold;
2288 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2289 pkgCache::VerIterator version;
2291 _profile(Package$packageWithIterator$GetCandidateVer)
2292 version = [database policy]->GetCandidateVer(iterator);
2298 return [[[Package alloc]
2299 initWithVersion:version
2306 - (pkgCache::PkgIterator) iterator {
2310 - (NSString *) section {
2311 if (section$_ == nil) {
2312 if (section_.empty())
2315 _profile(Package$section)
2316 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2317 NSString *name(section_);
2318 section$_ = [SectionMap_ objectForKey:name] ?: name;
2323 - (NSString *) simpleSection {
2324 if (NSString *section = [self section])
2325 return Simplify(section);
2330 - (NSString *) longSection {
2331 return LocalizeSection([self section]);
2334 - (NSString *) shortSection {
2335 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2338 - (NSString *) uri {
2341 pkgIndexFile *index;
2342 pkgCache::PkgFileIterator file(file_.File());
2343 if (![database_ list].FindIndex(file, index))
2345 return [NSString stringWithUTF8String:iterator_->Path];
2346 //return [NSString stringWithUTF8String:file.Site()];
2347 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2351 - (Address *) maintainer {
2352 @synchronized (database_) {
2353 if ([database_ era] != era_ || file_.end())
2356 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2357 const std::string &maintainer(parser->Maintainer());
2358 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2362 @synchronized (database_) {
2363 if ([database_ era] != era_ || version_.end())
2366 return version_->InstalledSize;
2369 - (NSString *) longDescription {
2370 @synchronized (database_) {
2371 if ([database_ era] != era_ || file_.end())
2374 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2375 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2377 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2378 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2379 if ([lines count] < 2)
2382 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2383 for (size_t i(1), e([lines count]); i != e; ++i) {
2384 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2385 [trimmed addObject:trim];
2388 return [trimmed componentsJoinedByString:@"\n"];
2391 - (NSString *) shortDescription {
2392 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2396 _profile(Package$index)
2397 CFStringRef name((CFStringRef) [self name]);
2398 if (CFStringGetLength(name) == 0)
2400 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2401 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2403 return toupper(character);
2407 - (PackageValue *) metadata {
2408 return &MetaFile_.Get(metadata_);
2412 PackageValue *metadata([self metadata]);
2413 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2416 - (bool) subscribed {
2417 return [self metadata]->subscribed_;
2420 - (bool) setSubscribed:(bool)subscribed {
2421 PackageValue *metadata([self metadata]);
2422 if (metadata->subscribed_ == subscribed)
2424 metadata->subscribed_ = subscribed;
2432 - (NSString *) latest {
2436 - (NSString *) installed {
2440 - (BOOL) uninstalled {
2441 return installed_.empty();
2445 return !version_.end();
2448 - (BOOL) upgradableAndEssential:(BOOL)essential {
2449 _profile(Package$upgradableAndEssential)
2450 pkgCache::VerIterator current(iterator_.CurrentVer());
2452 return essential && essential_;
2454 return !version_.end() && version_ != current;
2458 - (BOOL) essential {
2463 return [database_ cache][iterator_].InstBroken();
2466 - (BOOL) unfiltered {
2467 _profile(Package$unfiltered$obsolete)
2472 _profile(Package$unfiltered$hasSupportingRole)
2473 if (![self hasSupportingRole])
2481 if (![self unfiltered])
2484 NSString *section([self section]);
2486 _profile(Package$visible$isSectionVisible)
2487 if (section != nil && !isSectionVisible(section))
2495 unsigned char current(iterator_->CurrentState);
2496 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2499 - (BOOL) halfConfigured {
2500 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2503 - (BOOL) halfInstalled {
2504 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2508 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2509 return state.Mode != pkgDepCache::ModeKeep;
2512 - (NSString *) mode {
2513 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2515 switch (state.Mode) {
2516 case pkgDepCache::ModeDelete:
2517 if ((state.iFlags & pkgDepCache::Purge) != 0)
2521 case pkgDepCache::ModeKeep:
2522 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2523 return @"REINSTALL";
2524 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2528 case pkgDepCache::ModeInstall:
2529 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2530 return @"REINSTALL";
2531 else*/ switch (state.Status) {
2533 return @"DOWNGRADE";
2539 return @"NEW_INSTALL";
2550 - (NSString *) name {
2551 return name_.empty() ? id_ : name_;
2554 - (UIImage *) icon {
2555 NSString *section = [self simpleSection];
2558 if (parsed_ != NULL)
2559 if (NSString *href = parsed_->icon_)
2560 if ([href hasPrefix:@"file:///"])
2561 // XXX: correct escaping
2562 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2563 if (icon == nil) if (section != nil)
2564 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2565 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2566 if ([dicon hasPrefix:@"file:///"])
2567 // XXX: correct escaping
2568 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2570 icon = [UIImage applicationImageNamed:@"unknown.png"];
2574 - (NSString *) homepage {
2575 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2578 - (NSString *) depiction {
2579 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2582 - (Address *) sponsor {
2583 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2586 - (Address *) author {
2587 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2590 - (NSString *) support {
2591 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2594 - (NSArray *) files {
2595 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2596 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2599 fin.open([path UTF8String]);
2604 while (std::getline(fin, line))
2605 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2610 - (NSArray *) warnings {
2611 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2612 const char *name(iterator_.Name());
2614 size_t length(strlen(name));
2615 if (length < 2) invalid:
2616 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2617 else for (size_t i(0); i != length; ++i)
2619 /* XXX: technically this is not allowed */
2620 (name[i] < 'A' || name[i] > 'Z') &&
2621 (name[i] < 'a' || name[i] > 'z') &&
2622 (name[i] < '0' || name[i] > '9') &&
2623 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2626 if (strcmp(name, "cydia") != 0) {
2629 bool _private = false;
2632 bool repository = [[self section] isEqualToString:@"Repositories"];
2634 if (NSArray *files = [self files])
2635 for (NSString *file in files)
2636 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2638 else if (!user && [file isEqualToString:@"/User"])
2640 else if (!_private && [file isEqualToString:@"/private"])
2642 else if (!stash && [file isEqualToString:@"/var/stash"])
2645 /* XXX: this is not sensitive enough. only some folders are valid. */
2646 if (cydia && !repository)
2647 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2649 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2651 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2653 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2656 return [warnings count] == 0 ? nil : warnings;
2659 - (NSArray *) applications {
2660 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2662 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2664 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2665 if (NSArray *files = [self files])
2666 for (NSString *file in files)
2667 if (application_r(file)) {
2668 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2669 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2670 if ([id isEqualToString:me])
2673 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2675 display = application_r[1];
2677 NSString *bundle([file stringByDeletingLastPathComponent]);
2678 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2679 if (icon == nil || [icon length] == 0)
2681 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2683 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2684 [applications addObject:application];
2686 [application addObject:id];
2687 [application addObject:display];
2688 [application addObject:url];
2691 return [applications count] == 0 ? nil : applications;
2694 - (Source *) source {
2695 if (source_ == nil) {
2696 @synchronized (database_) {
2697 if ([database_ era] != era_ || file_.end())
2698 source_ = (Source *) [NSNull null];
2700 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2704 return source_ == (Source *) [NSNull null] ? nil : source_;
2707 - (NSString *) role {
2711 - (BOOL) matches:(NSString *)text {
2717 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2718 if (range.location != NSNotFound)
2721 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2722 if (range.location != NSNotFound)
2725 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2726 if (range.location != NSNotFound)
2732 - (bool) hasSupportingRole {
2735 if ([role_ isEqualToString:@"enduser"])
2737 if ([Role_ isEqualToString:@"User"])
2739 if ([role_ isEqualToString:@"hacker"])
2741 if ([Role_ isEqualToString:@"Hacker"])
2743 if ([role_ isEqualToString:@"developer"])
2745 if ([Role_ isEqualToString:@"Developer"])
2750 - (BOOL) hasTag:(NSString *)tag {
2751 return tags_ == nil ? NO : [tags_ containsObject:tag];
2754 - (NSString *) primaryPurpose {
2755 for (NSString *tag in tags_)
2756 if ([tag hasPrefix:@"purpose::"])
2757 return [tag substringFromIndex:9];
2761 - (NSArray *) purposes {
2762 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2763 for (NSString *tag in tags_)
2764 if ([tag hasPrefix:@"purpose::"])
2765 [purposes addObject:[tag substringFromIndex:9]];
2766 return [purposes count] == 0 ? nil : purposes;
2769 - (bool) isCommercial {
2770 return [self hasTag:@"cydia::commercial"];
2773 - (CYString &) cyname {
2774 return name_.empty() ? id_ : name_;
2777 - (uint32_t) compareBySection:(NSArray *)sections {
2778 NSString *section([self section]);
2779 for (size_t i(0), e([sections count]); i != e; ++i) {
2780 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2784 return _not(uint32_t);
2788 @synchronized (database_) {
2789 pkgProblemResolver *resolver = [database_ resolver];
2790 resolver->Clear(iterator_);
2792 pkgCacheFile &cache([database_ cache]);
2793 cache->SetReInstall(iterator_, false);
2794 cache->MarkKeep(iterator_, false);
2798 @synchronized (database_) {
2799 pkgProblemResolver *resolver = [database_ resolver];
2800 resolver->Clear(iterator_);
2801 resolver->Protect(iterator_);
2803 pkgCacheFile &cache([database_ cache]);
2804 cache->SetReInstall(iterator_, false);
2805 cache->MarkInstall(iterator_, false);
2807 pkgDepCache::StateCache &state((*cache)[iterator_]);
2808 if (!state.Install())
2809 cache->SetReInstall(iterator_, true);
2813 @synchronized (database_) {
2814 pkgProblemResolver *resolver = [database_ resolver];
2815 resolver->Clear(iterator_);
2816 resolver->Remove(iterator_);
2817 resolver->Protect(iterator_);
2819 pkgCacheFile &cache([database_ cache]);
2820 cache->SetReInstall(iterator_, false);
2821 cache->MarkDelete(iterator_, true);
2824 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2825 _profile(Package$isUnfilteredAndSearchedForBy)
2828 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2829 value &= [self unfiltered];
2832 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2833 value &= [self matches:search];
2840 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2841 if ([search length] == 0)
2844 _profile(Package$isUnfilteredAndSelectedForBy)
2847 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2848 value &= [self unfiltered];
2851 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2852 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2859 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2860 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2863 - (bool) isVisibleInSection:(NSString *)name {
2864 NSString *section([self section]);
2868 section == nil && [name length] == 0 ||
2869 [name isEqualToString:section]
2870 ) && [self visible];
2873 - (bool) isVisibleInSource:(Source *)source {
2874 return [self source] == source && [self visible];
2879 /* Section Class {{{ */
2880 @interface Section : NSObject {
2885 NSString *localized_;
2888 - (NSComparisonResult) compareByLocalized:(Section *)section;
2889 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2890 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2891 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2892 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2893 - (NSString *) name;
2900 - (void) addToCount;
2902 - (void) setCount:(size_t)count;
2903 - (NSString *) localized;
2907 @implementation Section
2911 if (localized_ != nil)
2912 [localized_ release];
2916 - (NSComparisonResult) compareByLocalized:(Section *)section {
2917 NSString *lhs(localized_);
2918 NSString *rhs([section localized]);
2920 /*if ([lhs length] != 0 && [rhs length] != 0) {
2921 unichar lhc = [lhs characterAtIndex:0];
2922 unichar rhc = [rhs characterAtIndex:0];
2924 if (isalpha(lhc) && !isalpha(rhc))
2925 return NSOrderedAscending;
2926 else if (!isalpha(lhc) && isalpha(rhc))
2927 return NSOrderedDescending;
2930 return [lhs compare:rhs options:LaxCompareOptions_];
2933 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2934 if ((self = [self initWithName:name localize:NO]) != nil) {
2935 if (localized != nil)
2936 localized_ = [localized retain];
2940 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2941 return [self initWithName:name row:0 localize:localize];
2944 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2945 if ((self = [super init]) != nil) {
2946 name_ = [name retain];
2950 localized_ = [LocalizeSection(name_) retain];
2954 /* XXX: localize the index thingees */
2955 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2956 if ((self = [super init]) != nil) {
2957 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2963 - (NSString *) name {
2983 - (void) addToCount {
2987 - (void) setCount:(size_t)count {
2991 - (NSString *) localized {
2998 static NSString *Colon_;
2999 static NSString *Elision_;
3000 static NSString *Error_;
3001 static NSString *Warning_;
3003 /* Database Implementation {{{ */
3004 @implementation Database
3006 + (Database *) sharedInstance {
3007 static Database *instance;
3008 if (instance == nil)
3009 instance = [[Database alloc] init];
3017 - (void) releasePackages {
3018 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3019 CFArrayRemoveAllValues(packages_);
3023 // XXX: actually implement this thing
3025 [self releasePackages];
3026 apr_pool_destroy(pool_);
3027 NSRecycleZone(zone_);
3031 - (void) _readCydia:(NSNumber *)fd { _pooled
3032 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3033 std::istream is(&ib);
3036 static Pcre finish_r("^finish:([^:]*)$");
3038 while (std::getline(is, line)) {
3039 const char *data(line.c_str());
3040 size_t size = line.size();
3041 lprintf("C:%s\n", data);
3043 if (finish_r(data, size)) {
3044 NSString *finish = finish_r[1];
3045 int index = [Finishes_ indexOfObject:finish];
3046 if (index != INT_MAX && index > Finish_)
3054 - (void) _readStatus:(NSNumber *)fd { _pooled
3055 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3056 std::istream is(&ib);
3059 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3060 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3062 while (std::getline(is, line)) {
3063 const char *data(line.c_str());
3064 size_t size(line.size());
3065 lprintf("S:%s\n", data);
3067 if (conffile_r(data, size)) {
3068 [delegate_ setConfigurationData:conffile_r[1]];
3069 } else if (strncmp(data, "status: ", 8) == 0) {
3070 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3071 [delegate_ setProgressTitle:string];
3072 } else if (pmstatus_r(data, size)) {
3073 std::string type([pmstatus_r[1] UTF8String]);
3074 NSString *id = pmstatus_r[2];
3076 float percent([pmstatus_r[3] floatValue]);
3077 [delegate_ setProgressPercent:(percent / 100)];
3079 NSString *string = pmstatus_r[4];
3081 if (type == "pmerror")
3082 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3083 withObject:[NSArray arrayWithObjects:string, id, nil]
3086 else if (type == "pmstatus") {
3087 [delegate_ setProgressTitle:string];
3088 } else if (type == "pmconffile")
3089 [delegate_ setConfigurationData:string];
3091 lprintf("E:unknown pmstatus\n");
3093 lprintf("E:unknown status\n");
3099 - (void) _readOutput:(NSNumber *)fd { _pooled
3100 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3101 std::istream is(&ib);
3104 while (std::getline(is, line)) {
3105 lprintf("O:%s\n", line.c_str());
3106 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3116 - (Package *) packageWithName:(NSString *)name {
3117 @synchronized (self) {
3118 if (static_cast<pkgDepCache *>(cache_) == NULL)
3120 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3121 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3125 if ((self = [super init]) != nil) {
3132 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3133 apr_pool_create(&pool_, NULL);
3135 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3139 _assert(pipe(fds) != -1);
3142 _config->Set("APT::Keep-Fds::", cydiafd_);
3143 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3146 detachNewThreadSelector:@selector(_readCydia:)
3148 withObject:[NSNumber numberWithInt:fds[0]]
3151 _assert(pipe(fds) != -1);
3155 detachNewThreadSelector:@selector(_readStatus:)
3157 withObject:[NSNumber numberWithInt:fds[0]]
3160 _assert(pipe(fds) != -1);
3161 _assert(dup2(fds[0], 0) != -1);
3162 _assert(close(fds[0]) != -1);
3164 input_ = fdopen(fds[1], "a");
3166 _assert(pipe(fds) != -1);
3167 _assert(dup2(fds[1], 1) != -1);
3168 _assert(close(fds[1]) != -1);
3171 detachNewThreadSelector:@selector(_readOutput:)
3173 withObject:[NSNumber numberWithInt:fds[0]]
3178 - (pkgCacheFile &) cache {
3182 - (pkgDepCache::Policy *) policy {
3186 - (pkgRecords *) records {
3190 - (pkgProblemResolver *) resolver {
3194 - (pkgAcquire &) fetcher {
3198 - (pkgSourceList &) list {
3202 - (NSArray *) packages {
3203 return (NSArray *) packages_;
3206 - (NSArray *) sources {
3207 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3208 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3209 [sources addObject:i->second];
3213 - (NSArray *) issues {
3214 if (cache_->BrokenCount() == 0)
3217 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3219 for (Package *package in [self packages]) {
3220 if (![package broken])
3222 pkgCache::PkgIterator pkg([package iterator]);
3224 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3225 [entry addObject:[package name]];
3226 [issues addObject:entry];
3228 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3232 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3233 pkgCache::DepIterator start;
3234 pkgCache::DepIterator end;
3235 dep.GlobOr(start, end); // ++dep
3237 if (!cache_->IsImportantDep(end))
3239 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3242 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3243 [entry addObject:failure];
3244 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3246 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3247 if (Package *package = [self packageWithName:name])
3248 name = [package name];
3249 [failure addObject:name];
3251 pkgCache::PkgIterator target(start.TargetPkg());
3252 if (target->ProvidesList != 0)
3253 [failure addObject:@"?"];
3255 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3257 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3258 else if (!cache_[target].CandidateVerIter(cache_).end())
3259 [failure addObject:@"-"];
3260 else if (target->ProvidesList == 0)
3261 [failure addObject:@"!"];
3263 [failure addObject:@"%"];
3267 if (start.TargetVer() != 0)
3268 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3279 - (bool) popErrorWithTitle:(NSString *)title {
3281 std::string message;
3283 while (!_error->empty()) {
3285 bool warning(!_error->PopMessage(error));
3289 size_t size(error.size());
3290 if (size == 0 || error[size - 1] != '\n')
3292 error.resize(size - 1);
3294 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3296 if (!message.empty())
3301 if (fatal && !message.empty())
3302 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3307 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3308 return [self popErrorWithTitle:title] || !success;
3311 - (void) reloadData { CYPoolStart() {
3312 @synchronized (self) {
3315 [self releasePackages];
3336 apr_pool_clear(pool_);
3337 NSRecycleZone(zone_);
3339 int chk(creat("/tmp/cydia.chk", 0644));
3343 NSString *title(UCLocalize("DATABASE"));
3346 if (!cache_.Open(progress_, true)) { pop:
3348 bool warning(!_error->PopMessage(error));
3349 lprintf("cache_.Open():[%s]\n", error.c_str());
3351 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3352 [delegate_ repairWithSelector:@selector(configure)];
3353 else if (error == "The package lists or status file could not be parsed or opened.")
3354 [delegate_ repairWithSelector:@selector(update)];
3355 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3356 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3357 // else if (error == "The list of sources could not be read.")
3359 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3368 unlink("/tmp/cydia.chk");
3370 now_ = [[NSDate date] timeIntervalSince1970];
3372 policy_ = new pkgDepCache::Policy();
3373 records_ = new pkgRecords(cache_);
3374 resolver_ = new pkgProblemResolver(cache_);
3375 fetcher_ = new pkgAcquire(&status_);
3378 list_ = new pkgSourceList();
3379 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3382 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3383 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3387 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3390 if (cache_->BrokenCount() != 0) {
3391 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3394 if (cache_->BrokenCount() != 0) {
3395 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3399 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3403 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3404 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3405 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3406 // XXX: this could be more intelligent
3407 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3408 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3410 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3415 /*std::vector<Package *> packages;
3416 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3417 [packages_ release];
3422 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3423 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3424 //packages.push_back(package);
3425 CFArrayAppendValue(packages_, [package retain]);
3429 /*if (packages.empty())
3430 packages_ = [[NSArray alloc] init];
3432 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3435 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3436 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3437 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3445 /*if (!packages.empty())
3446 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3447 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3449 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3451 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3453 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3457 } } CYPoolEnd() _trace(); }
3460 @synchronized (self) {
3462 resolver_ = new pkgProblemResolver(cache_);
3464 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3465 if (!cache_[iterator].Keep()) {
3466 cache_->MarkKeep(iterator, false);
3467 cache_->SetReInstall(iterator, false);
3472 - (void) configure {
3473 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3474 system([dpkg UTF8String]);
3478 // XXX: I don't remember this condition
3483 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3485 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3487 if ([self popErrorWithTitle:title])
3491 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3494 public pkgArchiveCleaner
3497 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3502 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3509 fetcher_->Shutdown();
3511 pkgRecords records(cache_);
3513 lock_ = new FileFd();
3514 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3516 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3518 if ([self popErrorWithTitle:title])
3522 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3525 manager_ = (_system->CreatePM(cache_));
3526 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3533 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3535 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3537 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3539 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3540 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3543 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3548 bool failed = false;
3549 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3550 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3552 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3555 std::string uri = (*item)->DescURI();
3556 std::string error = (*item)->ErrorText;
3558 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3561 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3562 withObject:[NSArray arrayWithObjects:
3563 [NSString stringWithUTF8String:error.c_str()],
3575 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3577 if (_error->PendingError()) {
3582 if (result == pkgPackageManager::Failed) {
3587 if (result != pkgPackageManager::Completed) {
3592 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3594 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3596 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3597 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3600 if (![before isEqualToArray:after])
3605 NSString *title(UCLocalize("UPGRADE"));
3606 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3612 [self updateWithStatus:status_];
3615 - (void) updateWithStatus:(Status &)status {
3616 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3617 NSString *title(UCLocalize("REFRESHING_DATA"));
3620 if (!list.ReadMainList())
3621 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3624 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3625 if ([self popErrorWithTitle:title])
3628 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3629 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3630 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3632 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3636 - (void) setDelegate:(id)delegate {
3637 delegate_ = delegate;
3638 status_.setDelegate(delegate);
3639 progress_.setDelegate(delegate);
3642 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3643 SourceMap::const_iterator i(sources_.find(file->ID));
3644 return i == sources_.end() ? nil : i->second;
3650 /* Confirmation Controller {{{ */
3651 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3652 if (!iterator.end())
3653 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3654 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3656 pkgCache::PkgIterator package(dep.TargetPkg());
3659 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3667 /* Web Scripting {{{ */
3668 @interface CydiaObject : NSObject {
3670 _transient id delegate_;
3673 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3676 @implementation CydiaObject
3679 [indirect_ release];
3683 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3684 if ((self = [super init]) != nil) {
3685 indirect_ = [indirect retain];
3689 - (void) setDelegate:(id)delegate {
3690 delegate_ = delegate;
3693 + (NSArray *) _attributeKeys {
3694 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3697 - (NSArray *) attributeKeys {
3698 return [[self class] _attributeKeys];
3701 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3702 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3705 - (NSString *) device {
3706 return [[UIDevice currentDevice] uniqueIdentifier];
3709 #if 0 // XXX: implement!
3710 - (NSString *) mac {
3711 if (![indirect_ promptForSensitive:@"Mac Address"])
3715 - (NSString *) serial {
3716 if (![indirect_ promptForSensitive:@"Serial #"])
3720 - (NSString *) firewire {
3721 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3725 - (NSString *) imei {
3726 if (![indirect_ promptForSensitive:@"IMEI"])
3731 + (NSString *) webScriptNameForSelector:(SEL)selector {
3732 if (selector == @selector(close))
3734 else if (selector == @selector(getInstalledPackages))
3735 return @"getInstalledPackages";
3736 else if (selector == @selector(getPackageById:))
3737 return @"getPackageById";
3738 else if (selector == @selector(installPackages:))
3739 return @"installPackages";
3740 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3741 return @"setButtonImage";
3742 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3743 return @"setButtonTitle";
3744 else if (selector == @selector(setPopupHook:))
3745 return @"setPopupHook";
3746 else if (selector == @selector(setSpecial:))
3747 return @"setSpecial";
3748 else if (selector == @selector(setToken:))
3750 else if (selector == @selector(setViewportWidth:))
3751 return @"setViewportWidth";
3752 else if (selector == @selector(supports:))
3754 else if (selector == @selector(stringWithFormat:arguments:))
3756 else if (selector == @selector(localizedStringForKey:value:table:))
3758 else if (selector == @selector(du:))
3760 else if (selector == @selector(statfs:))
3766 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3767 return [self webScriptNameForSelector:selector] == nil;
3770 - (BOOL) supports:(NSString *)feature {
3771 return [feature isEqualToString:@"window.open"];
3774 - (NSArray *) getInstalledPackages {
3775 NSArray *packages([[Database sharedInstance] packages]);
3776 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3777 for (Package *package in packages)
3778 if ([package installed] != nil)
3779 [installed addObject:package];
3783 - (Package *) getPackageById:(NSString *)id {
3784 Package *package([[Database sharedInstance] packageWithName:id]);
3789 - (NSArray *) statfs:(NSString *)path {
3792 if (path == nil || statfs([path UTF8String], &stat) == -1)
3795 return [NSArray arrayWithObjects:
3796 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3797 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3798 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3802 - (NSNumber *) du:(NSString *)path {
3803 NSNumber *value(nil);
3806 _assert(pipe(fds) != -1);
3808 pid_t pid(ExecFork());
3810 _assert(dup2(fds[1], 1) != -1);
3811 _assert(close(fds[0]) != -1);
3812 _assert(close(fds[1]) != -1);
3813 /* XXX: this should probably not use du */
3814 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3819 _assert(close(fds[1]) != -1);
3821 if (FILE *du = fdopen(fds[0], "r")) {
3823 while (fgets(line, sizeof(line), du) != NULL) {
3824 size_t length(strlen(line));
3825 while (length != 0 && line[length - 1] == '\n')
3826 line[--length] = '\0';
3827 if (char *tab = strchr(line, '\t')) {
3829 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3834 } else _assert(close(fds[0]));
3838 if (waitpid(pid, &status, 0) == -1)
3841 else _assert(false);
3850 - (void) installPackages:(NSArray *)packages {
3851 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3854 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3855 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3858 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3859 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3862 - (void) setSpecial:(id)function {
3863 [indirect_ setSpecial:function];
3866 - (void) setToken:(NSString *)token {
3869 Token_ = [token retain];
3871 [Metadata_ setObject:Token_ forKey:@"Token"];
3875 - (void) setPopupHook:(id)function {
3876 [indirect_ setPopupHook:function];
3879 - (void) setViewportWidth:(float)width {
3880 [indirect_ setViewportWidth:width];
3883 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3884 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3885 unsigned count([arguments count]);
3887 for (unsigned i(0); i != count; ++i)
3888 values[i] = [arguments objectAtIndex:i];
3889 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3892 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3893 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3895 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3897 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3903 /* Cydia Browser Controller {{{ */
3904 @interface CYBrowserController : BrowserController {
3905 CydiaObject *cydia_;
3910 @implementation CYBrowserController
3917 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3920 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3921 [super webView:view didClearWindowObject:window forFrame:frame];
3923 WebDataSource *source([frame dataSource]);
3924 NSURLResponse *response([source response]);
3925 NSURL *url([response URL]);
3926 NSString *scheme([url scheme]);
3928 NSHTTPURLResponse *http;
3929 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3930 http = (NSHTTPURLResponse *) response;
3934 NSDictionary *headers([http allHeaderFields]);
3935 NSString *host([url host]);
3936 [self setHeaders:headers forHost:host];
3939 [host isEqualToString:@"cydia.saurik.com"] ||
3940 [host hasSuffix:@".cydia.saurik.com"] ||
3941 [scheme isEqualToString:@"file"]
3943 [window setValue:cydia_ forKey:@"cydia"];
3946 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3947 if (System_ != NULL)
3948 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3949 if (Machine_ != NULL)
3950 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3952 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3954 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3957 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3958 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3959 [self _setMoreHeaders:copy];
3963 - (void) setDelegate:(id)delegate {
3964 [super setDelegate:delegate];
3965 [cydia_ setDelegate:delegate];
3969 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3970 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3972 WebView *webview([[webview_ _documentView] webView]);
3974 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3976 NSString *application = package == nil ? @"Cydia" : [NSString
3977 stringWithFormat:@"Cydia/%@",
3982 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3984 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3985 if (Product_ != nil)
3986 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3988 [webview setApplicationNameForUserAgent:application];
3995 /* Confirmation {{{ */
3996 @protocol ConfirmationControllerDelegate
3997 - (void) cancelAndClear:(bool)clear;
3998 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4002 @interface ConfirmationController : CYBrowserController {
4003 _transient Database *database_;
4004 UIAlertView *essential_;
4011 - (id) initWithDatabase:(Database *)database;
4015 @implementation ConfirmationController
4022 if (essential_ != nil)
4023 [essential_ release];
4027 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4028 NSString *context([alert context]);
4030 if ([context isEqualToString:@"remove"]) {
4031 if (button == [alert cancelButtonIndex]) {
4032 [self dismissModalViewControllerAnimated:YES];
4033 } else if (button == [alert firstOtherButtonIndex]) {
4036 [delegate_ confirmWithNavigationController:[self navigationController]];
4039 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4040 } else if ([context isEqualToString:@"unable"]) {
4041 [self dismissModalViewControllerAnimated:YES];
4042 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4044 [super alertView:alert clickedButtonAtIndex:button];
4048 - (void) _doContinue {
4049 [self dismissModalViewControllerAnimated:YES];
4050 [delegate_ cancelAndClear:NO];
4053 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4054 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4058 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4059 [super webView:view didClearWindowObject:window forFrame:frame];
4060 [window setValue:changes_ forKey:@"changes"];
4061 [window setValue:issues_ forKey:@"issues"];
4062 [window setValue:sizes_ forKey:@"sizes"];
4063 [window setValue:self forKey:@"queue"];
4066 - (id) initWithDatabase:(Database *)database {
4067 if ((self = [super init]) != nil) {
4068 database_ = database;
4070 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4072 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4073 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4074 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4075 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4076 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4080 pkgDepCache::Policy *policy([database_ policy]);
4082 pkgCacheFile &cache([database_ cache]);
4083 NSArray *packages = [database_ packages];
4084 for (Package *package in packages) {
4085 pkgCache::PkgIterator iterator = [package iterator];
4086 pkgDepCache::StateCache &state(cache[iterator]);
4088 NSString *name([package name]);
4090 if (state.NewInstall())
4091 [installing addObject:name];
4092 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4093 [reinstalling addObject:name];
4094 else if (state.Upgrade())
4095 [upgrading addObject:name];
4096 else if (state.Downgrade())
4097 [downgrading addObject:name];
4098 else if (state.Delete()) {
4099 if ([package essential])
4101 [removing addObject:name];
4104 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4105 substrate_ |= DepSubstrate(iterator.CurrentVer());
4110 else if (Advanced_) {
4111 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4113 essential_ = [[UIAlertView alloc]
4114 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4115 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4117 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4118 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4121 [essential_ setContext:@"remove"];
4123 essential_ = [[UIAlertView alloc]
4124 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4125 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4127 cancelButtonTitle:UCLocalize("OKAY")
4128 otherButtonTitles:nil
4131 [essential_ setContext:@"unable"];
4134 changes_ = [[NSArray alloc] initWithObjects:
4142 issues_ = [database_ issues];
4144 issues_ = [issues_ retain];
4146 sizes_ = [[NSArray alloc] initWithObjects:
4147 SizeString([database_ fetcher].FetchNeeded()),
4148 SizeString([database_ fetcher].PartialPresent()),
4151 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4153 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4154 initWithTitle:UCLocalize("CANCEL")
4155 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4156 style:UIBarButtonItemStylePlain
4158 action:@selector(cancelButtonClicked)
4163 - (void) applyRightButton {
4164 #if !AlwaysReload && !IgnoreInstall
4165 if (issues_ == nil && ![self isLoading])
4166 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4167 initWithTitle:UCLocalize("CONFIRM")
4168 style:UIBarButtonItemStylePlain
4170 action:@selector(confirmButtonClicked)
4173 [super applyRightButton];
4175 [[self navigationItem] setRightBarButtonItem:nil];
4179 - (void) cancelButtonClicked {
4180 [self dismissModalViewControllerAnimated:YES];
4181 [delegate_ cancelAndClear:YES];
4185 - (void) confirmButtonClicked {
4189 if (essential_ != nil)
4194 [delegate_ confirmWithNavigationController:[self navigationController]];
4202 /* Progress Data {{{ */
4203 @interface ProgressData : NSObject {
4205 // XXX: should these really both be _transient?
4206 _transient id target_;
4207 _transient id object_;
4210 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4217 @implementation ProgressData
4219 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4220 if ((self = [super init]) != nil) {
4221 selector_ = selector;
4241 /* Progress Controller {{{ */
4242 @interface ProgressController : CYViewController <
4243 ConfigurationDelegate,
4246 _transient Database *database_;
4247 UIProgressBar *progress_;
4248 UITextView *output_;
4249 UITextLabel *status_;
4250 UIPushButton *close_;
4252 SHA1SumValue springlist_;
4253 SHA1SumValue notifyconf_;
4257 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4259 - (void) _retachThread;
4260 - (void) _detachNewThreadData:(ProgressData *)data;
4261 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4267 @protocol ProgressControllerDelegate
4268 - (void) progressControllerIsComplete:(ProgressController *)sender;
4271 @implementation ProgressController
4274 [database_ setDelegate:nil];
4275 [progress_ release];
4284 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4285 if ((self = [super init]) != nil) {
4286 database_ = database;
4287 [database_ setDelegate:self];
4288 delegate_ = delegate;
4290 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4292 progress_ = [[UIProgressBar alloc] init];
4293 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4294 [progress_ setStyle:0];
4296 status_ = [[UITextLabel alloc] init];
4297 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4298 [status_ setColor:[UIColor whiteColor]];
4299 [status_ setBackgroundColor:[UIColor clearColor]];
4300 [status_ setCentersHorizontally:YES];
4301 //[status_ setFont:font];
4303 output_ = [[UITextView alloc] init];
4305 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4306 //[output_ setTextFont:@"Courier New"];
4307 [output_ setFont:[[output_ font] fontWithSize:12]];
4308 [output_ setTextColor:[UIColor whiteColor]];
4309 [output_ setBackgroundColor:[UIColor clearColor]];
4310 [output_ setMarginTop:0];
4311 [output_ setAllowsRubberBanding:YES];
4312 [output_ setEditable:NO];
4313 [[self view] addSubview:output_];
4315 close_ = [[UIPushButton alloc] init];
4316 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4317 [close_ setAutosizesToFit:NO];
4318 [close_ setDrawsShadow:YES];
4319 [close_ setStretchBackground:YES];
4320 [close_ setEnabled:YES];
4321 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4322 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4323 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4324 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4328 - (void) positionViews {
4329 CGRect bounds = [[self view] bounds];
4330 CGSize prgsize = [UIProgressBar defaultSize];
4333 (bounds.size.width - prgsize.width) / 2,
4334 bounds.size.height - prgsize.height - 20
4337 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4339 [progress_ setFrame:prgrect];
4340 [status_ setFrame:CGRectMake(
4342 bounds.size.height - prgsize.height - 50,
4343 bounds.size.width - 20,
4346 [output_ setFrame:CGRectMake(
4349 bounds.size.width - 20,
4350 bounds.size.height - 62
4352 [close_ setFrame:CGRectMake(
4353 (bounds.size.width - closewidth) / 2,
4354 bounds.size.height - prgsize.height - 50,
4360 - (void) viewWillAppear:(BOOL)animated {
4361 [super viewDidAppear:animated];
4362 [[self navigationItem] setHidesBackButton:YES];
4363 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4365 [self positionViews];
4368 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4369 [self positionViews];
4372 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4373 NSString *context([alert context]);
4375 if ([context isEqualToString:@"conffile"]) {
4376 FILE *input = [database_ input];
4377 if (button == [alert cancelButtonIndex])
4378 fprintf(input, "N\n");
4379 else if (button == [alert firstOtherButtonIndex])
4380 fprintf(input, "Y\n");
4385 - (void) closeButtonPushed {
4388 UpdateExternalStatus(0);
4392 [self dismissModalViewControllerAnimated:YES];
4396 [delegate_ terminateWithSuccess];
4397 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4398 [delegate_ suspendWithAnimation:YES];
4400 [delegate_ suspend];*/
4404 system("launchctl stop com.apple.SpringBoard");
4408 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4417 - (void) _retachThread {
4418 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4420 [[self view] addSubview:close_];
4421 [progress_ removeFromSuperview];
4422 [status_ removeFromSuperview];
4424 [database_ popErrorWithTitle:title_];
4425 [delegate_ progressControllerIsComplete:self];
4429 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4432 MMap mmap(file, MMap::ReadOnly);
4434 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4435 if (!(notifyconf_ == sha1.Result()))
4442 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4445 MMap mmap(file, MMap::ReadOnly);
4447 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4448 if (!(springlist_ == sha1.Result()))
4454 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4455 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4456 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4457 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4458 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4461 system("su -c /usr/bin/uicache mobile");
4463 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4465 [delegate_ setStatusBarShowsProgress:NO];
4468 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4469 [[data target] performSelector:[data selector] withObject:[data object]];
4470 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4473 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4474 UpdateExternalStatus(1);
4481 title_ = [title retain];
4483 [[self navigationItem] setTitle:title_];
4485 [status_ setText:nil];
4486 [output_ setText:@""];
4487 [progress_ setProgress:0];
4489 [close_ removeFromSuperview];
4490 [[self view] addSubview:progress_];
4491 [[self view] addSubview:status_];
4493 [delegate_ setStatusBarShowsProgress:YES];
4498 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4501 MMap mmap(file, MMap::ReadOnly);
4503 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4504 notifyconf_ = sha1.Result();
4510 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4513 MMap mmap(file, MMap::ReadOnly);
4515 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4516 springlist_ = sha1.Result();
4521 detachNewThreadSelector:@selector(_detachNewThreadData:)
4523 withObject:[[[ProgressData alloc]
4524 initWithSelector:selector
4531 - (void) repairWithSelector:(SEL)selector {
4533 detachNewThreadSelector:selector
4536 title:UCLocalize("REPAIRING")
4540 - (void) setConfigurationData:(NSString *)data {
4542 performSelectorOnMainThread:@selector(_setConfigurationData:)
4548 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4549 CYActionSheet *sheet([[[CYActionSheet alloc]
4551 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4552 defaultButtonIndex:0
4555 [sheet setMessage:error];
4556 [sheet yieldToPopupAlertAnimated:YES];
4560 - (void) setProgressTitle:(NSString *)title {
4562 performSelectorOnMainThread:@selector(_setProgressTitle:)
4568 - (void) setProgressPercent:(float)percent {
4570 performSelectorOnMainThread:@selector(_setProgressPercent:)
4571 withObject:[NSNumber numberWithFloat:percent]
4576 - (void) startProgress {
4579 - (void) addProgressOutput:(NSString *)output {
4581 performSelectorOnMainThread:@selector(_addProgressOutput:)
4587 - (bool) isCancelling:(size_t)received {
4591 - (void) _setConfigurationData:(NSString *)data {
4592 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4594 if (!conffile_r(data)) {
4595 lprintf("E:invalid conffile\n");
4599 NSString *ofile = conffile_r[1];
4600 //NSString *nfile = conffile_r[2];
4602 UIAlertView *alert = [[[UIAlertView alloc]
4603 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4604 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4606 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4607 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4608 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4612 [alert setContext:@"conffile"];
4616 - (void) _setProgressTitle:(NSString *)title {
4617 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4618 for (size_t i(0), e([words count]); i != e; ++i) {
4619 NSString *word([words objectAtIndex:i]);
4620 if (Package *package = [database_ packageWithName:word])
4621 [words replaceObjectAtIndex:i withObject:[package name]];
4624 [status_ setText:[words componentsJoinedByString:@" "]];
4627 - (void) _setProgressPercent:(NSNumber *)percent {
4628 [progress_ setProgress:[percent floatValue]];
4631 - (void) _addProgressOutput:(NSString *)output {
4632 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4633 CGSize size = [output_ contentSize];
4634 CGRect rect = {{0, size.height}, {size.width, 0}};
4635 [output_ scrollRectToVisible:rect animated:YES];
4638 - (BOOL) isRunning {
4645 /* Cell Content View {{{ */
4646 @protocol ContentDelegate
4647 - (void) drawContentRect:(CGRect)rect;
4650 @interface ContentView : UIView {
4651 _transient id<ContentDelegate> delegate_;
4656 @implementation ContentView
4658 - (id) initWithFrame:(CGRect)frame {
4659 if ((self = [super initWithFrame:frame]) != nil) {
4660 [self setNeedsDisplayOnBoundsChange:YES];
4664 - (void) setDelegate:(id<ContentDelegate>)delegate {
4665 delegate_ = delegate;
4668 - (void) drawRect:(CGRect)rect {
4669 [super drawRect:rect];
4670 [delegate_ drawContentRect:rect];
4675 /* Cydia TableView Cell {{{ */
4676 @interface CYTableViewCell : UITableViewCell {
4677 ContentView *content_;
4683 @implementation CYTableViewCell
4690 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4691 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4693 if (view == content_) {
4694 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4695 highlighted_ = highlighted;
4698 [super _updateHighlightColorsForView:view highlighted:highlighted];
4701 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4702 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4703 highlighted_ = selected;
4705 [super setSelected:selected animated:animated];
4706 [content_ setNeedsDisplay];
4711 /* Package Cell {{{ */
4712 @interface PackageCell : CYTableViewCell <
4717 NSString *description_;
4725 - (PackageCell *) init;
4726 - (void) setPackage:(Package *)package;
4728 + (int) heightForPackage:(Package *)package;
4729 - (void) drawContentRect:(CGRect)rect;
4733 @implementation PackageCell
4735 - (void) clearPackage {
4746 if (description_ != nil) {
4747 [description_ release];
4751 if (source_ != nil) {
4756 if (badge_ != nil) {
4761 if (placard_ != nil) {
4771 [self clearPackage];
4775 - (PackageCell *) init {
4776 CGRect frame(CGRectMake(0, 0, 320, 74));
4777 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4778 UIView *content([self contentView]);
4779 CGRect bounds([content bounds]);
4781 content_ = [[ContentView alloc] initWithFrame:bounds];
4782 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4783 [content addSubview:content_];
4785 [content_ setDelegate:self];
4786 [content_ setOpaque:YES];
4790 - (void) _setBackgroundColor {
4792 if (NSString *mode = [package_ mode]) {
4793 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4794 color = remove ? RemovingColor_ : InstallingColor_;
4796 color = [UIColor whiteColor];
4798 [content_ setBackgroundColor:color];
4799 [self setNeedsDisplay];
4802 - (void) setPackage:(Package *)package {
4803 [self clearPackage];
4806 Source *source = [package source];
4808 icon_ = [[package icon] retain];
4809 name_ = [[package name] retain];
4812 description_ = [package longDescription];
4813 if (description_ == nil)
4814 description_ = [package shortDescription];
4815 if (description_ != nil)
4816 description_ = [description_ retain];
4818 commercial_ = [package isCommercial];
4820 package_ = [package retain];
4822 NSString *label = nil;
4823 bool trusted = false;
4825 if (source != nil) {
4826 label = [source label];
4827 trusted = [source trusted];
4828 } else if ([[package id] isEqualToString:@"firmware"])
4829 label = UCLocalize("APPLE");
4831 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4833 NSString *from(label);
4835 NSString *section = [package simpleSection];
4836 if (section != nil && ![section isEqualToString:label]) {
4837 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4838 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4841 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4842 source_ = [from retain];
4844 if (NSString *purpose = [package primaryPurpose])
4845 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4846 badge_ = [badge_ retain];
4848 if ([package installed] != nil)
4849 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4850 placard_ = [placard_ retain];
4852 [self _setBackgroundColor];
4853 [content_ setNeedsDisplay];
4856 - (void) drawContentRect:(CGRect)rect {
4857 bool highlighted(highlighted_);
4858 float width([self bounds].size.width);
4861 CGContextRef context(UIGraphicsGetCurrentContext());
4862 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4863 CGContextFillRect(context, rect);
4868 rect.size = [icon_ size];
4870 rect.size.width /= 2;
4871 rect.size.height /= 2;
4873 rect.origin.x = 25 - rect.size.width / 2;
4874 rect.origin.y = 25 - rect.size.height / 2;
4876 [icon_ drawInRect:rect];
4879 if (badge_ != nil) {
4880 CGSize size = [badge_ size];
4882 [badge_ drawAtPoint:CGPointMake(
4883 36 - size.width / 2,
4884 36 - size.height / 2
4892 UISetColor(commercial_ ? Purple_ : Black_);
4893 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4894 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4897 UISetColor(commercial_ ? Purplish_ : Gray_);
4898 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4900 if (placard_ != nil)
4901 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4904 + (int) heightForPackage:(Package *)package {
4910 /* Section Cell {{{ */
4911 @interface SectionCell : CYTableViewCell <
4923 - (void) setSection:(Section *)section editing:(BOOL)editing;
4927 @implementation SectionCell
4929 - (void) clearSection {
4930 if (basic_ != nil) {
4935 if (section_ != nil) {
4945 if (count_ != nil) {
4952 [self clearSection];
4958 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4959 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4960 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4961 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4962 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4964 UIView *content([self contentView]);
4965 CGRect bounds([content bounds]);
4967 content_ = [[ContentView alloc] initWithFrame:bounds];
4968 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4969 [content addSubview:content_];
4970 [content_ setBackgroundColor:[UIColor whiteColor]];
4972 [content_ setDelegate:self];
4976 - (void) onSwitch:(id)sender {
4977 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4978 if (metadata == nil) {
4979 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4980 [Sections_ setObject:metadata forKey:basic_];
4984 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4987 - (void) setSection:(Section *)section editing:(BOOL)editing {
4988 if (editing != editing_) {
4990 [switch_ removeFromSuperview];
4992 [self addSubview:switch_];
4996 [self clearSection];
4998 if (section == nil) {
4999 name_ = [UCLocalize("ALL_PACKAGES") retain];
5002 basic_ = [section name];
5004 basic_ = [basic_ retain];
5006 section_ = [section localized];
5007 if (section_ != nil)
5008 section_ = [section_ retain];
5010 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5011 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5014 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5017 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5018 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5020 [content_ setNeedsDisplay];
5023 - (void) setFrame:(CGRect)frame {
5024 [super setFrame:frame];
5026 CGRect rect([switch_ frame]);
5027 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5030 - (void) drawContentRect:(CGRect)rect {
5031 bool highlighted(highlighted_);
5033 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5038 float width(rect.size.width);
5044 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5046 CGSize size = [count_ sizeWithFont:Font14_];
5050 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5056 /* File Table {{{ */
5057 @interface FileTable : CYViewController <
5058 UITableViewDataSource,
5061 _transient Database *database_;
5064 NSMutableArray *files_;
5068 - (id) initWithDatabase:(Database *)database;
5069 - (void) setPackage:(Package *)package;
5073 @implementation FileTable
5076 if (package_ != nil)
5085 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5086 return files_ == nil ? 0 : [files_ count];
5089 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5093 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5094 static NSString *reuseIdentifier = @"Cell";
5096 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5098 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5099 [cell setFont:[UIFont systemFontOfSize:16]];
5101 [cell setText:[files_ objectAtIndex:indexPath.row]];
5102 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5107 - (id) initWithDatabase:(Database *)database {
5108 if ((self = [super init]) != nil) {
5109 database_ = database;
5111 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5113 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5115 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5116 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5117 [list_ setRowHeight:24.0f];
5118 [[self view] addSubview:list_];
5120 [list_ setDataSource:self];
5121 [list_ setDelegate:self];
5125 - (void) setPackage:(Package *)package {
5126 if (package_ != nil) {
5127 [package_ autorelease];
5136 [files_ removeAllObjects];
5138 if (package != nil) {
5139 package_ = [package retain];
5140 name_ = [[package id] retain];
5142 if (NSArray *files = [package files])
5143 [files_ addObjectsFromArray:files];
5145 if ([files_ count] != 0) {
5146 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5147 [files_ removeObjectAtIndex:0];
5148 [files_ sortUsingSelector:@selector(compareByPath:)];
5150 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5151 [stack addObject:@"/"];
5153 for (int i(0), e([files_ count]); i != e; ++i) {
5154 NSString *file = [files_ objectAtIndex:i];
5155 while (![file hasPrefix:[stack lastObject]])
5156 [stack removeLastObject];
5157 NSString *directory = [stack lastObject];
5158 [stack addObject:[file stringByAppendingString:@"/"]];
5159 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5160 ([stack count] - 2) * 3, "",
5161 [file substringFromIndex:[directory length]]
5170 - (void) reloadData {
5171 [self setPackage:[database_ packageWithName:name_]];
5176 /* Package Controller {{{ */
5177 @interface PackageController : CYBrowserController <
5178 UIActionSheetDelegate
5180 _transient Database *database_;
5184 NSMutableArray *buttons_;
5185 UIBarButtonItem *button_;
5188 - (id) initWithDatabase:(Database *)database;
5189 - (void) setPackage:(Package *)package;
5193 @implementation PackageController
5196 if (package_ != nil)
5210 if ([self retainCount] == 1)
5211 [delegate_ setPackageController:self];
5215 /* XXX: this is not safe at all... localization of /fail/ */
5216 - (void) _clickButtonWithName:(NSString *)name {
5217 if ([name isEqualToString:UCLocalize("CLEAR")])
5218 [delegate_ clearPackage:package_];
5219 else if ([name isEqualToString:UCLocalize("INSTALL")])
5220 [delegate_ installPackage:package_];
5221 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5222 [delegate_ installPackage:package_];
5223 else if ([name isEqualToString:UCLocalize("REMOVE")])
5224 [delegate_ removePackage:package_];
5225 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5226 [delegate_ installPackage:package_];
5227 else _assert(false);
5230 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5231 NSString *context([sheet context]);
5233 if ([context isEqualToString:@"modify"]) {
5234 if (button != [sheet cancelButtonIndex]) {
5235 NSString *buttonName = [buttons_ objectAtIndex:button];
5236 [self _clickButtonWithName:buttonName];
5239 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5243 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5244 [super webView:view didClearWindowObject:window forFrame:frame];
5245 [window setValue:package_ forKey:@"package"];
5248 - (bool) _allowJavaScriptPanel {
5253 - (void) _customButtonClicked {
5254 int count([buttons_ count]);
5259 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5261 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5262 [buttons addObjectsFromArray:buttons_];
5264 UIActionSheet *sheet = [[[UIActionSheet alloc]
5267 cancelButtonTitle:nil
5268 destructiveButtonTitle:nil
5269 otherButtonTitles:nil
5272 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5274 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5275 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5277 [sheet setContext:@"modify"];
5279 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5283 // We don't want to allow non-commercial packages to do custom things to the install button,
5284 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5285 - (void) customButtonClicked {
5287 [super customButtonClicked];
5289 [self _customButtonClicked];
5292 - (void) reloadButtonClicked {
5293 // Don't reload a package view by clicking the button.
5296 - (void) applyLoadingTitle {
5297 // Don't show "Loading" as the title. Ever.
5300 - (UIBarButtonItem *) rightButton {
5305 - (id) initWithDatabase:(Database *)database {
5306 if ((self = [super init]) != nil) {
5307 database_ = database;
5308 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5309 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5313 - (void) setPackage:(Package *)package {
5314 if (package_ != nil) {
5315 [package_ autorelease];
5324 [buttons_ removeAllObjects];
5326 if (package != nil) {
5329 package_ = [package retain];
5330 name_ = [[package id] retain];
5331 commercial_ = [package isCommercial];
5333 if ([package_ mode] != nil)
5334 [buttons_ addObject:UCLocalize("CLEAR")];
5335 if ([package_ source] == nil);
5336 else if ([package_ upgradableAndEssential:NO])
5337 [buttons_ addObject:UCLocalize("UPGRADE")];
5338 else if ([package_ uninstalled])
5339 [buttons_ addObject:UCLocalize("INSTALL")];
5341 [buttons_ addObject:UCLocalize("REINSTALL")];
5342 if (![package_ uninstalled])
5343 [buttons_ addObject:UCLocalize("REMOVE")];
5350 switch ([buttons_ count]) {
5351 case 0: title = nil; break;
5352 case 1: title = [buttons_ objectAtIndex:0]; break;
5353 default: title = UCLocalize("MODIFY"); break;
5356 button_ = [[UIBarButtonItem alloc]
5358 style:UIBarButtonItemStylePlain
5360 action:@selector(customButtonClicked)
5366 - (bool) isLoading {
5367 return commercial_ ? [super isLoading] : false;
5370 - (void) reloadData {
5371 [self setPackage:[database_ packageWithName:name_]];
5376 /* Package Table {{{ */
5377 @interface PackageTable : UIView <
5378 UITableViewDataSource,
5381 _transient Database *database_;
5382 NSMutableArray *packages_;
5383 NSMutableArray *sections_;
5385 NSMutableArray *index_;
5386 NSMutableDictionary *indices_;
5387 // XXX: this target_ seems to be delegate_. :(
5388 _transient id target_;
5390 // XXX: why do we even have this delegate_?
5391 _transient id delegate_;
5394 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5396 - (void) setDelegate:(id)delegate;
5398 - (void) reloadData;
5399 - (void) resetCursor;
5401 - (UITableView *) list;
5403 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5405 - (void) deselectWithAnimation:(BOOL)animated;
5409 @implementation PackageTable
5412 [packages_ release];
5413 [sections_ release];
5421 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5422 NSInteger count([sections_ count]);
5423 return count == 0 ? 1 : count;
5426 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5427 if ([sections_ count] == 0)
5429 return [[sections_ objectAtIndex:section] name];
5432 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5433 if ([sections_ count] == 0)
5435 return [[sections_ objectAtIndex:section] count];
5438 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5439 Section *section([sections_ objectAtIndex:[path section]]);
5440 NSInteger row([path row]);
5441 Package *package([packages_ objectAtIndex:([section row] + row)]);
5445 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5446 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5448 cell = [[[PackageCell alloc] init] autorelease];
5449 [cell setPackage:[self packageAtIndexPath:path]];
5453 - (void) deselectWithAnimation:(BOOL)animated {
5454 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5457 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5458 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5461 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5462 Package *package([self packageAtIndexPath:path]);
5463 package = [database_ packageWithName:[package id]];
5464 [target_ performSelector:action_ withObject:package];
5468 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5469 return [packages_ count] > 20 ? index_ : nil;
5472 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5476 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5477 if ((self = [super initWithFrame:frame]) != nil) {
5478 database_ = database;
5483 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5484 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5486 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5487 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5489 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5490 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5491 [list_ setRowHeight:73.0f];
5492 [self addSubview:list_];
5494 [list_ setDataSource:self];
5495 [list_ setDelegate:self];
5499 - (void) setDelegate:(id)delegate {
5500 delegate_ = delegate;
5503 - (bool) hasPackage:(Package *)package {
5507 - (void) reloadData {
5508 NSArray *packages = [database_ packages];
5510 [packages_ removeAllObjects];
5511 [sections_ removeAllObjects];
5513 _profile(PackageTable$reloadData$Filter)
5514 for (Package *package in packages)
5515 if ([self hasPackage:package])
5516 [packages_ addObject:package];
5519 [index_ removeAllObjects];
5520 [indices_ removeAllObjects];
5522 Section *section = nil;
5524 _profile(PackageTable$reloadData$Section)
5525 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5529 _profile(PackageTable$reloadData$Section$Package)
5530 package = [packages_ objectAtIndex:offset];
5531 index = [package index];
5534 if (section == nil || [section index] != index) {
5535 _profile(PackageTable$reloadData$Section$Allocate)
5536 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5539 [index_ addObject:[section name]];
5540 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5542 _profile(PackageTable$reloadData$Section$Add)
5543 [sections_ addObject:section];
5547 [section addToCount];
5551 _profile(PackageTable$reloadData$List)
5556 - (void) resetCursor {
5557 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5560 - (UITableView *) list {
5564 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5565 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5570 /* Filtered Package Table {{{ */
5571 @interface FilteredPackageTable : PackageTable {
5577 - (void) setObject:(id)object;
5578 - (void) setObject:(id)object forFilter:(SEL)filter;
5580 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5584 @implementation FilteredPackageTable
5592 - (void) setFilter:(SEL)filter {
5595 /* XXX: this is an unsafe optimization of doomy hell */
5596 Method method(class_getInstanceMethod([Package class], filter));
5597 _assert(method != NULL);
5598 imp_ = method_getImplementation(method);
5599 _assert(imp_ != NULL);
5602 - (void) setObject:(id)object {
5608 object_ = [object retain];
5611 - (void) setObject:(id)object forFilter:(SEL)filter {
5612 [self setFilter:filter];
5613 [self setObject:object];
5616 - (bool) hasPackage:(Package *)package {
5617 _profile(FilteredPackageTable$hasPackage)
5618 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5622 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5623 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5624 [self setFilter:filter];
5625 object_ = [object retain];
5633 /* Filtered Package Controller {{{ */
5634 @interface FilteredPackageController : CYViewController {
5635 _transient Database *database_;
5636 FilteredPackageTable *packages_;
5640 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5644 @implementation FilteredPackageController
5647 [packages_ release];
5653 - (void) viewDidAppear:(BOOL)animated {
5654 [super viewDidAppear:animated];
5655 [packages_ deselectWithAnimation:animated];
5658 - (void) didSelectPackage:(Package *)package {
5659 PackageController *view([delegate_ packageController]);
5660 [view setPackage:package];
5661 [view setDelegate:delegate_];
5662 [[self navigationController] pushViewController:view animated:YES];
5665 - (NSString *) title { return title_; }
5667 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5668 if ((self = [super init]) != nil) {
5669 database_ = database;
5670 title_ = [title copy];
5671 [[self navigationItem] setTitle:title_];
5673 packages_ = [[FilteredPackageTable alloc]
5674 initWithFrame:[[self view] bounds]
5677 action:@selector(didSelectPackage:)
5682 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5683 [[self view] addSubview:packages_];
5687 - (void) reloadData {
5688 [packages_ reloadData];
5691 - (void) setDelegate:(id)delegate {
5692 [super setDelegate:delegate];
5693 [packages_ setDelegate:delegate];
5700 /* Add Source Controller {{{ */
5701 @interface AddSourceController : CYViewController {
5702 _transient Database *database_;
5705 - (id) initWithDatabase:(Database *)database;
5709 @implementation AddSourceController
5711 - (id) initWithDatabase:(Database *)database {
5712 if ((self = [super init]) != nil) {
5713 database_ = database;
5719 /* Source Cell {{{ */
5720 @interface SourceCell : CYTableViewCell <
5725 NSString *description_;
5729 - (void) setSource:(Source *)source;
5733 @implementation SourceCell
5735 - (void) clearSource {
5738 [description_ release];
5747 - (void) setSource:(Source *)source {
5751 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5753 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5754 icon_ = [icon_ retain];
5756 origin_ = [[source name] retain];
5757 label_ = [[source uri] retain];
5758 description_ = [[source description] retain];
5760 [content_ setNeedsDisplay];
5768 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5769 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5770 UIView *content([self contentView]);
5771 CGRect bounds([content bounds]);
5773 content_ = [[ContentView alloc] initWithFrame:bounds];
5774 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5775 [content_ setBackgroundColor:[UIColor whiteColor]];
5776 [content addSubview:content_];
5778 [content_ setDelegate:self];
5779 [content_ setOpaque:YES];
5783 - (void) drawContentRect:(CGRect)rect {
5784 bool highlighted(highlighted_);
5785 float width(rect.size.width);
5788 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5795 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5799 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5803 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5808 /* Source Table {{{ */
5809 @interface SourceTable : CYViewController <
5810 UITableViewDataSource,
5813 _transient Database *database_;
5815 NSMutableArray *sources_;
5819 UIProgressHUD *hud_;
5822 //NSURLConnection *installer_;
5823 NSURLConnection *trivial_;
5824 NSURLConnection *trivial_bz2_;
5825 NSURLConnection *trivial_gz_;
5826 //NSURLConnection *automatic_;
5831 - (id) initWithDatabase:(Database *)database;
5833 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5837 @implementation SourceTable
5839 - (void) _releaseConnection:(NSURLConnection *)connection {
5840 if (connection != nil) {
5841 [connection cancel];
5842 //[connection setDelegate:nil];
5843 [connection release];
5855 //[self _releaseConnection:installer_];
5856 [self _releaseConnection:trivial_];
5857 [self _releaseConnection:trivial_gz_];
5858 [self _releaseConnection:trivial_bz2_];
5859 //[self _releaseConnection:automatic_];
5866 - (void) viewDidAppear:(BOOL)animated {
5867 [super viewDidAppear:animated];
5868 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5871 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5872 return offset_ == 0 ? 1 : 2;
5875 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5876 switch (section + (offset_ == 0 ? 1 : 0)) {
5877 case 0: return UCLocalize("ENTERED_BY_USER");
5878 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5884 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5885 int count = [sources_ count];
5887 case 0: return (offset_ == 0 ? count : offset_);
5888 case 1: return count - offset_;
5894 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5896 switch (indexPath.section) {
5897 case 0: idx = indexPath.row; break;
5898 case 1: idx = indexPath.row + offset_; break;
5902 return [sources_ objectAtIndex:idx];
5905 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5906 Source *source = [self sourceAtIndexPath:indexPath];
5907 return [source description] == nil ? 56 : 73;
5910 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5911 static NSString *cellIdentifier = @"SourceCell";
5913 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5914 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5915 [cell setSource:[self sourceAtIndexPath:indexPath]];
5920 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5921 return UITableViewCellAccessoryDisclosureIndicator;
5924 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5925 Source *source = [self sourceAtIndexPath:indexPath];
5927 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5928 initWithDatabase:database_
5929 title:[source label]
5930 filter:@selector(isVisibleInSource:)
5934 [packages setDelegate:delegate_];
5936 [[self navigationController] pushViewController:packages animated:YES];
5939 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5940 Source *source = [self sourceAtIndexPath:indexPath];
5941 return [source record] != nil;
5944 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5945 Source *source = [self sourceAtIndexPath:indexPath];
5946 [Sources_ removeObjectForKey:[source key]];
5947 [delegate_ syncData];
5951 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5954 @"./", @"Distribution",
5955 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5957 [delegate_ syncData];
5960 - (NSString *) getWarning {
5961 NSString *href(href_);
5962 NSRange colon([href rangeOfString:@"://"]);
5963 if (colon.location != NSNotFound)
5964 href = [href substringFromIndex:(colon.location + 3)];
5965 href = [href stringByAddingPercentEscapes];
5966 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5967 href = [href stringByCachingURLWithCurrentCDN];
5969 NSURL *url([NSURL URLWithString:href]);
5971 NSStringEncoding encoding;
5972 NSError *error(nil);
5974 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5975 return [warning length] == 0 ? nil : warning;
5979 - (void) _endConnection:(NSURLConnection *)connection {
5980 // XXX: the memory management in this method is horribly awkward
5982 NSURLConnection **field = NULL;
5983 if (connection == trivial_)
5985 else if (connection == trivial_bz2_)
5986 field = &trivial_bz2_;
5987 else if (connection == trivial_gz_)
5988 field = &trivial_gz_;
5989 _assert(field != NULL);
5990 [connection release];
5995 trivial_bz2_ == nil &&
6001 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6004 UIAlertView *alert = [[[UIAlertView alloc]
6005 initWithTitle:UCLocalize("SOURCE_WARNING")
6008 cancelButtonTitle:UCLocalize("CANCEL")
6009 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6012 [alert setContext:@"warning"];
6013 [alert setNumberOfRows:1];
6017 } else if (error_ != nil) {
6018 UIAlertView *alert = [[[UIAlertView alloc]
6019 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6020 message:[error_ localizedDescription]
6022 cancelButtonTitle:UCLocalize("OK")
6023 otherButtonTitles:nil
6026 [alert setContext:@"urlerror"];
6029 UIAlertView *alert = [[[UIAlertView alloc]
6030 initWithTitle:UCLocalize("NOT_REPOSITORY")
6031 message:UCLocalize("NOT_REPOSITORY_EX")
6033 cancelButtonTitle:UCLocalize("OK")
6034 otherButtonTitles:nil
6037 [alert setContext:@"trivial"];
6041 [delegate_ setStatusBarShowsProgress:NO];
6042 [delegate_ removeProgressHUD:hud_];
6052 if (error_ != nil) {
6059 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6060 switch ([response statusCode]) {
6066 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6067 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6069 error_ = [error retain];
6070 [self _endConnection:connection];
6073 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6074 [self _endConnection:connection];
6077 - (NSString *) title { return UCLocalize("SOURCES"); }
6079 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6080 NSMutableURLRequest *request = [NSMutableURLRequest
6081 requestWithURL:[NSURL URLWithString:href]
6082 cachePolicy:NSURLRequestUseProtocolCachePolicy
6083 timeoutInterval:120.0
6086 [request setHTTPMethod:method];
6088 if (Machine_ != NULL)
6089 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6090 if (UniqueID_ != nil)
6091 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6093 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6095 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6098 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6099 NSString *context([alert context]);
6101 if ([context isEqualToString:@"source"]) {
6104 NSString *href = [[alert textField] text];
6106 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6108 if (![href hasSuffix:@"/"])
6109 href_ = [href stringByAppendingString:@"/"];
6112 href_ = [href_ retain];
6114 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6115 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6116 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6117 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6121 // XXX: this is stupid
6122 hud_ = [[delegate_ addProgressHUD] retain];
6123 [hud_ setText:UCLocalize("VERIFYING_URL")];
6132 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6133 } else if ([context isEqualToString:@"trivial"])
6134 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6135 else if ([context isEqualToString:@"urlerror"])
6136 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6137 else if ([context isEqualToString:@"warning"]) {
6152 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6156 - (id) initWithDatabase:(Database *)database {
6157 if ((self = [super init]) != nil) {
6158 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6159 [self updateButtonsForEditingStatus:NO animated:NO];
6161 database_ = database;
6162 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6164 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6165 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6166 [[self view] addSubview:list_];
6168 [list_ setDataSource:self];
6169 [list_ setDelegate:self];
6175 - (void) reloadData {
6177 if (!list.ReadMainList())
6180 [sources_ removeAllObjects];
6181 [sources_ addObjectsFromArray:[database_ sources]];
6183 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6186 int count([sources_ count]);
6188 for (int i = 0; i != count; i++) {
6189 if ([[sources_ objectAtIndex:i] record] == nil)
6194 [list_ setEditing:NO];
6195 [self updateButtonsForEditingStatus:NO animated:NO];
6199 - (void) addButtonClicked {
6200 /*[book_ pushPage:[[[AddSourceController alloc]
6205 UIAlertView *alert = [[[UIAlertView alloc]
6206 initWithTitle:UCLocalize("ENTER_APT_URL")
6209 cancelButtonTitle:UCLocalize("CANCEL")
6210 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6213 [alert setContext:@"source"];
6214 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6216 [alert setNumberOfRows:1];
6217 [alert addTextFieldWithValue:@"http://" label:@""];
6219 UITextInputTraits *traits = [[alert textField] textInputTraits];
6220 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6221 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6222 [traits setKeyboardType:UIKeyboardTypeURL];
6223 // XXX: UIReturnKeyDone
6224 [traits setReturnKeyType:UIReturnKeyNext];
6229 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6230 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6231 initWithTitle:UCLocalize("ADD")
6232 style:UIBarButtonItemStylePlain
6234 action:@selector(addButtonClicked)
6235 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6237 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6238 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6239 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6241 action:@selector(editButtonClicked)
6242 ] autorelease] animated:animated];
6244 if (IsWildcat_ && !editing)
6245 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6246 initWithTitle:UCLocalize("SETTINGS")
6247 style:UIBarButtonItemStylePlain
6249 action:@selector(settingsButtonClicked)
6253 - (void) settingsButtonClicked {
6254 [delegate_ showSettings];
6257 - (void) editButtonClicked {
6258 [list_ setEditing:![list_ isEditing] animated:YES];
6260 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6266 /* Installed Controller {{{ */
6267 @interface InstalledController : FilteredPackageController {
6271 - (id) initWithDatabase:(Database *)database;
6273 - (void) updateRoleButton;
6274 - (void) queueStatusDidChange;
6278 @implementation InstalledController
6284 - (NSString *) title { return UCLocalize("INSTALLED"); }
6286 - (id) initWithDatabase:(Database *)database {
6287 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6288 [self updateRoleButton];
6289 [self queueStatusDidChange];
6294 - (void) queueButtonClicked {
6299 - (void) queueStatusDidChange {
6303 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6304 initWithTitle:UCLocalize("QUEUE")
6305 style:UIBarButtonItemStyleDone
6307 action:@selector(queueButtonClicked)
6310 [[self navigationItem] setLeftBarButtonItem:nil];
6316 - (void) reloadData {
6317 [packages_ reloadData];
6320 - (void) updateRoleButton {
6321 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6322 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6323 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6324 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6326 action:@selector(roleButtonClicked)
6330 - (void) roleButtonClicked {
6331 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6332 [packages_ reloadData];
6335 [self updateRoleButton];
6338 - (void) setDelegate:(id)delegate {
6339 [super setDelegate:delegate];
6340 [packages_ setDelegate:delegate];
6346 /* Home Controller {{{ */
6347 @interface HomeController : CYBrowserController {
6352 @implementation HomeController
6354 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6355 [super _setMoreHeaders:request];
6358 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6359 if (UniqueID_ != nil)
6360 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6362 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6365 - (void) aboutButtonClicked {
6366 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6368 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6369 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6370 [alert setCancelButtonIndex:0];
6373 @"Copyright (C) 2008-2010\n"
6374 "Jay Freeman (saurik)\n"
6375 "saurik@saurik.com\n"
6376 "http://www.saurik.com/"
6382 - (void) viewWillAppear:(BOOL)animated {
6383 [super viewWillAppear:animated];
6384 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6387 - (void) viewWillDisappear:(BOOL)animated {
6388 [super viewWillDisappear:animated];
6389 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6393 if ((self = [super init]) != nil) {
6394 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6395 initWithTitle:UCLocalize("ABOUT")
6396 style:UIBarButtonItemStylePlain
6398 action:@selector(aboutButtonClicked)
6405 /* Manage Controller {{{ */
6406 @interface ManageController : CYBrowserController {
6409 - (void) queueStatusDidChange;
6412 @implementation ManageController
6415 if ((self = [super init]) != nil) {
6416 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6418 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6419 initWithTitle:UCLocalize("SETTINGS")
6420 style:UIBarButtonItemStylePlain
6422 action:@selector(settingsButtonClicked)
6425 [self queueStatusDidChange];
6429 - (void) settingsButtonClicked {
6430 [delegate_ showSettings];
6434 - (void) queueButtonClicked {
6438 - (void) applyLoadingTitle {
6439 // No "Loading" title.
6442 - (void) applyRightButton {
6447 - (void) queueStatusDidChange {
6449 if (!IsWildcat_ && Queuing_) {
6450 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6451 initWithTitle:UCLocalize("QUEUE")
6452 style:UIBarButtonItemStyleDone
6454 action:@selector(queueButtonClicked)
6457 [[self navigationItem] setRightBarButtonItem:nil];
6462 - (bool) isLoading {
6469 /* Refresh Bar {{{ */
6470 @interface RefreshBar : UINavigationBar {
6471 UIProgressIndicator *indicator_;
6472 UITextLabel *prompt_;
6473 UIProgressBar *progress_;
6474 UINavigationButton *cancel_;
6479 @implementation RefreshBar
6482 [indicator_ release];
6484 [progress_ release];
6489 - (void) positionViews {
6490 CGRect frame = [cancel_ frame];
6491 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6492 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6493 [cancel_ setFrame:frame];
6495 CGSize prgsize = {75, 100};
6497 [self frame].size.width - prgsize.width - 10,
6498 ([self frame].size.height - prgsize.height) / 2
6500 [progress_ setFrame:prgrect];
6502 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6503 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6504 CGRect indrect = {{indoffset, indoffset}, indsize};
6505 [indicator_ setFrame:indrect];
6507 CGSize prmsize = {215, indsize.height + 4};
6509 indoffset * 2 + indsize.width,
6510 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6512 [prompt_ setFrame:prmrect];
6515 - (void)setFrame:(CGRect)frame {
6516 [super setFrame:frame];
6518 [self positionViews];
6521 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6522 if ((self = [super initWithFrame:frame])) {
6523 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6525 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6526 [self setBarStyle:UIBarStyleBlack];
6528 UIBarStyle barstyle([self _barStyle:NO]);
6529 bool ugly(barstyle == UIBarStyleDefault);
6531 UIProgressIndicatorStyle style = ugly ?
6532 UIProgressIndicatorStyleMediumBrown :
6533 UIProgressIndicatorStyleMediumWhite;
6535 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6536 [indicator_ setStyle:style];
6537 [indicator_ startAnimation];
6538 [self addSubview:indicator_];
6540 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6541 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6542 [prompt_ setBackgroundColor:[UIColor clearColor]];
6543 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6544 [self addSubview:prompt_];
6546 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6547 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6548 [progress_ setStyle:0];
6549 [self addSubview:progress_];
6551 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6552 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6553 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6554 [cancel_ setBarStyle:barstyle];
6556 [self positionViews];
6561 [cancel_ removeFromSuperview];
6565 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6566 [progress_ setProgress:0];
6567 [self addSubview:cancel_];
6571 [cancel_ removeFromSuperview];
6574 - (void) setPrompt:(NSString *)prompt {
6575 [prompt_ setText:prompt];
6578 - (void) setProgress:(float)progress {
6579 [progress_ setProgress:progress];
6585 @class CYNavigationController;
6587 /* Cydia Tab Bar Controller {{{ */
6588 @interface CYTabBarController : UITabBarController {
6589 _transient Database *database_;
6594 @implementation CYTabBarController
6596 /* XXX: some logic should probably go here related to
6597 freeing the view controllers on tab change */
6599 - (void) reloadData {
6600 size_t count([[self viewControllers] count]);
6601 for (size_t i(0); i != count; ++i) {
6602 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6607 - (id) initWithDatabase:(Database *)database {
6608 if ((self = [super init]) != nil) {
6609 database_ = database;
6616 /* Cydia Navigation Controller {{{ */
6617 @interface CYNavigationController : UINavigationController {
6618 _transient Database *database_;
6619 _transient id<UINavigationControllerDelegate> delegate_;
6622 - (id) initWithDatabase:(Database *)database;
6623 - (void) reloadData;
6628 @implementation CYNavigationController
6630 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6631 // Inherit autorotation settings for modal parents.
6632 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6633 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6635 return [super shouldAutorotateToInterfaceOrientation:orientation];
6643 - (void) reloadData {
6644 size_t count([[self viewControllers] count]);
6645 for (size_t i(0); i != count; ++i) {
6646 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6651 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6652 delegate_ = delegate;
6655 - (id) initWithDatabase:(Database *)database {
6656 if ((self = [super init]) != nil) {
6657 database_ = database;
6663 /* Cydia:// Protocol {{{ */
6664 @interface CydiaURLProtocol : NSURLProtocol {
6669 @implementation CydiaURLProtocol
6671 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6672 NSURL *url([request URL]);
6675 NSString *scheme([[url scheme] lowercaseString]);
6676 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6681 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6685 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6686 id<NSURLProtocolClient> client([self client]);
6688 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6690 NSData *data(UIImagePNGRepresentation(icon));
6692 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6693 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6694 [client URLProtocol:self didLoadData:data];
6695 [client URLProtocolDidFinishLoading:self];
6699 - (void) startLoading {
6700 id<NSURLProtocolClient> client([self client]);
6701 NSURLRequest *request([self request]);
6703 NSURL *url([request URL]);
6704 NSString *href([url absoluteString]);
6706 NSString *path([href substringFromIndex:8]);
6707 NSRange slash([path rangeOfString:@"/"]);
6710 if (slash.location == NSNotFound) {
6714 command = [path substringToIndex:slash.location];
6715 path = [path substringFromIndex:(slash.location + 1)];
6718 Database *database([Database sharedInstance]);
6720 if ([command isEqualToString:@"package-icon"]) {
6723 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6724 Package *package([database packageWithName:path]);
6727 UIImage *icon([package icon]);
6728 [self _returnPNGWithImage:icon forRequest:request];
6729 } else if ([command isEqualToString:@"source-icon"]) {
6732 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6733 NSString *source(Simplify(path));
6734 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6736 icon = [UIImage applicationImageNamed:@"unknown.png"];
6737 [self _returnPNGWithImage:icon forRequest:request];
6738 } else if ([command isEqualToString:@"uikit-image"]) {
6741 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6742 UIImage *icon(_UIImageWithName(path));
6743 [self _returnPNGWithImage:icon forRequest:request];
6744 } else if ([command isEqualToString:@"section-icon"]) {
6747 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6748 NSString *section(Simplify(path));
6749 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6751 icon = [UIImage applicationImageNamed:@"unknown.png"];
6752 [self _returnPNGWithImage:icon forRequest:request];
6754 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6758 - (void) stopLoading {
6764 /* Sections Controller {{{ */
6765 @interface SectionsController : CYViewController <
6766 UITableViewDataSource,
6769 _transient Database *database_;
6770 NSMutableArray *sections_;
6771 NSMutableArray *filtered_;
6777 - (id) initWithDatabase:(Database *)database;
6778 - (void) reloadData;
6781 - (void) editButtonClicked;
6785 @implementation SectionsController
6788 [list_ setDataSource:nil];
6789 [list_ setDelegate:nil];
6791 [sections_ release];
6792 [filtered_ release];
6794 [accessory_ release];
6798 - (void) viewDidAppear:(BOOL)animated {
6799 [super viewDidAppear:animated];
6800 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6803 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6804 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6808 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6809 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6812 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6816 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6817 static NSString *reuseIdentifier = @"SectionCell";
6819 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6821 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6823 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6828 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6832 Section *section = [self sectionAtIndexPath:indexPath];
6833 NSString *name = [section name];
6836 if ([indexPath row] == 0) {
6839 title = UCLocalize("ALL_PACKAGES");
6842 name = [NSString stringWithString:name];
6843 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6846 title = UCLocalize("NO_SECTION");
6850 FilteredPackageController *table = [[[FilteredPackageController alloc]
6851 initWithDatabase:database_
6853 filter:@selector(isVisibleInSection:)
6857 [table setDelegate:delegate_];
6859 [[self navigationController] pushViewController:table animated:YES];
6862 - (NSString *) title { return UCLocalize("SECTIONS"); }
6864 - (id) initWithDatabase:(Database *)database {
6865 if ((self = [super init]) != nil) {
6866 database_ = database;
6868 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6870 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6871 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6873 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6874 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6875 [list_ setRowHeight:45.0f];
6876 [[self view] addSubview:list_];
6878 [list_ setDataSource:self];
6879 [list_ setDelegate:self];
6885 - (void) reloadData {
6886 NSArray *packages = [database_ packages];
6888 [sections_ removeAllObjects];
6889 [filtered_ removeAllObjects];
6891 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6894 for (Package *package in packages) {
6895 NSString *name([package section]);
6896 NSString *key(name == nil ? @"" : name);
6900 _profile(SectionsView$reloadData$Section)
6901 section = [sections objectForKey:key];
6902 if (section == nil) {
6903 _profile(SectionsView$reloadData$Section$Allocate)
6904 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6905 [sections setObject:section forKey:key];
6910 [section addToCount];
6912 _profile(SectionsView$reloadData$Filter)
6913 if (![package valid] || ![package visible])
6921 [sections_ addObjectsFromArray:[sections allValues]];
6923 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6925 for (Section *section in sections_) {
6926 size_t count([section row]);
6930 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6931 [section setCount:count];
6932 [filtered_ addObject:section];
6935 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6936 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
6937 style:UIBarButtonItemStylePlain
6939 action:@selector(editButtonClicked)
6940 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6946 - (void) resetView {
6948 [self editButtonClicked];
6951 - (void) editButtonClicked {
6952 if ((editing_ = !editing_))
6955 [delegate_ updateData];
6957 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6958 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6959 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6962 - (UIView *) accessoryView {
6968 /* Changes Controller {{{ */
6969 @interface ChangesController : CYViewController <
6970 UITableViewDataSource,
6973 _transient Database *database_;
6974 CFMutableArrayRef packages_;
6975 NSMutableArray *sections_;
6978 BOOL hasSentFirstLoad_;
6981 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6982 - (void) reloadData;
6986 @implementation ChangesController
6989 [list_ setDelegate:nil];
6990 [list_ setDataSource:nil];
6992 CFRelease(packages_);
6994 [sections_ release];
6999 - (void) viewDidAppear:(BOOL)animated {
7000 [super viewDidAppear:animated];
7001 if (!hasSentFirstLoad_) {
7002 hasSentFirstLoad_ = YES;
7003 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7005 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7009 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7010 NSInteger count([sections_ count]);
7011 return count == 0 ? 1 : count;
7014 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7015 if ([sections_ count] == 0)
7017 return [[sections_ objectAtIndex:section] name];
7020 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7021 if ([sections_ count] == 0)
7023 return [[sections_ objectAtIndex:section] count];
7026 - (Package *) packageAtIndex:(NSUInteger)index {
7027 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7030 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7031 Section *section([sections_ objectAtIndex:[path section]]);
7032 NSInteger row([path row]);
7033 return [self packageAtIndex:([section row] + row)];
7036 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7037 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7039 cell = [[[PackageCell alloc] init] autorelease];
7040 [cell setPackage:[self packageAtIndexPath:path]];
7044 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7045 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7048 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7049 Package *package([self packageAtIndexPath:path]);
7050 PackageController *view([delegate_ packageController]);
7051 [view setDelegate:delegate_];
7052 [view setPackage:package];
7053 [[self navigationController] pushViewController:view animated:YES];
7057 - (void) refreshButtonClicked {
7058 [delegate_ beginUpdate];
7059 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7062 - (void) upgradeButtonClicked {
7063 [delegate_ distUpgrade];
7066 - (NSString *) title { return UCLocalize("CHANGES"); }
7068 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7069 if ((self = [super init]) != nil) {
7070 database_ = database;
7071 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7073 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7075 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7077 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7078 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7079 [list_ setRowHeight:73.0f];
7080 [[self view] addSubview:list_];
7082 [list_ setDataSource:self];
7083 [list_ setDelegate:self];
7085 delegate_ = delegate;
7089 - (void) _reloadPackages:(NSArray *)packages {
7091 for (Package *package in packages)
7092 if ([package upgradableAndEssential:YES] || [package visible])
7093 CFArrayAppendValue(packages_, package);
7096 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7100 - (void) reloadData {
7101 NSArray *packages = [database_ packages];
7103 CFArrayRemoveAllValues(packages_);
7105 [sections_ removeAllObjects];
7108 UIProgressHUD *hud([delegate_ addProgressHUD]);
7109 [hud setText:UCLocalize("LOADING")];
7110 //NSLog(@"HUD:%@::%@", delegate_, hud);
7111 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7112 [delegate_ removeProgressHUD:hud];
7114 [self _reloadPackages:packages];
7117 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7118 Section *ignored = nil;
7119 Section *section = nil;
7123 bool unseens = false;
7125 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7127 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7128 Package *package = [self packageAtIndex:offset];
7130 BOOL uae = [package upgradableAndEssential:YES];
7134 time_t seen([package seen]);
7136 if (section == nil || last != seen) {
7140 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7143 _profile(ChangesController$reloadData$Allocate)
7144 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7145 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7146 [sections_ addObject:section];
7150 [section addToCount];
7151 } else if ([package ignored]) {
7152 if (ignored == nil) {
7153 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7155 [ignored addToCount];
7158 [upgradable addToCount];
7163 CFRelease(formatter);
7166 Section *last = [sections_ lastObject];
7167 size_t count = [last count];
7168 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7169 [sections_ removeLastObject];
7172 if ([ignored count] != 0)
7173 [sections_ insertObject:ignored atIndex:0];
7175 [sections_ insertObject:upgradable atIndex:0];
7180 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7181 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7182 style:UIBarButtonItemStylePlain
7184 action:@selector(upgradeButtonClicked)
7187 if (![delegate_ updating])
7188 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7189 initWithTitle:UCLocalize("REFRESH")
7190 style:UIBarButtonItemStylePlain
7192 action:@selector(refreshButtonClicked)
7198 /* Search Controller {{{ */
7199 @interface SearchController : FilteredPackageController <
7202 UISearchBar *search_;
7205 - (id) initWithDatabase:(Database *)database;
7206 - (void) reloadData;
7210 @implementation SearchController
7217 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7218 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7219 [search_ resignFirstResponder];
7223 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7224 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7228 - (NSString *) title { return nil; }
7230 - (id) initWithDatabase:(Database *)database {
7231 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7234 - (void)viewDidAppear:(BOOL)animated {
7235 [super viewDidAppear:animated];
7237 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7238 [search_ layoutSubviews];
7239 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7240 UITextField *textField = [search_ searchField];
7241 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7242 [search_ setDelegate:self];
7243 [textField setEnablesReturnKeyAutomatically:NO];
7244 [[self navigationItem] setTitleView:textField];
7248 - (void) _reloadData {
7251 - (void) reloadData {
7252 _profile(SearchController$reloadData)
7253 [packages_ reloadData];
7256 [packages_ resetCursor];
7259 - (void) didSelectPackage:(Package *)package {
7260 [search_ resignFirstResponder];
7261 [super didSelectPackage:package];
7266 /* Settings Controller {{{ */
7267 @interface SettingsController : CYViewController <
7268 UITableViewDataSource,
7271 _transient Database *database_;
7274 UITableView *table_;
7275 UISwitch *subscribedSwitch_;
7276 UISwitch *ignoredSwitch_;
7277 UITableViewCell *subscribedCell_;
7278 UITableViewCell *ignoredCell_;
7281 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7285 @implementation SettingsController
7289 if (package_ != nil)
7292 [subscribedSwitch_ release];
7293 [ignoredSwitch_ release];
7294 [subscribedCell_ release];
7295 [ignoredCell_ release];
7300 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7301 if (package_ == nil)
7307 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7308 if (package_ == nil)
7314 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7315 return UCLocalize("SHOW_ALL_CHANGES_EX");
7318 - (void) onSubscribed:(id)control {
7319 bool value([control isOn]);
7320 if (package_ == nil)
7322 if ([package_ setSubscribed:value])
7323 [delegate_ updateData];
7326 - (void) onIgnored:(id)control {
7327 // TODO: set Held state - possibly call out to dpkg, etc.
7330 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7331 if (package_ == nil)
7334 switch ([indexPath row]) {
7335 case 0: return subscribedCell_;
7336 case 1: return ignoredCell_;
7344 - (NSString *) title { return UCLocalize("SETTINGS"); }
7346 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7347 if ((self = [super init])) {
7348 database_ = database;
7349 name_ = [package retain];
7351 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7353 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7354 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7355 [[self view] addSubview:table_];
7357 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7358 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7359 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7361 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7362 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7363 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7365 subscribedCell_ = [[UITableViewCell alloc] init];
7366 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7367 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7368 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7370 ignoredCell_ = [[UITableViewCell alloc] init];
7371 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7372 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7373 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7375 [table_ setDataSource:self];
7376 [table_ setDelegate:self];
7381 - (void) reloadData {
7382 if (package_ != nil)
7383 [package_ autorelease];
7384 package_ = [database_ packageWithName:name_];
7385 if (package_ != nil) {
7387 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7388 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7391 [table_ reloadData];
7396 /* Signature Controller {{{ */
7397 @interface SignatureController : CYBrowserController {
7398 _transient Database *database_;
7402 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7406 @implementation SignatureController
7413 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7415 [super webView:view didClearWindowObject:window forFrame:frame];
7418 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7419 if ((self = [super init]) != nil) {
7420 database_ = database;
7421 package_ = [package retain];
7426 - (void) reloadData {
7427 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7433 /* Role Controller {{{ */
7434 @interface RoleController : CYViewController <
7435 UITableViewDataSource,
7438 _transient Database *database_;
7439 // XXX: ok, "roledelegate_"?...
7440 _transient id roledelegate_;
7441 UITableView *table_;
7442 UISegmentedControl *segment_;
7446 - (void) showDoneButton;
7447 - (void) resizeSegmentedControl;
7451 @implementation RoleController
7455 [container_ release];
7460 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7461 if ((self = [super init])) {
7462 database_ = database;
7463 roledelegate_ = delegate;
7465 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7467 NSArray *items = [NSArray arrayWithObjects:
7469 UCLocalize("HACKER"),
7470 UCLocalize("DEVELOPER"),
7472 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7473 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7474 [container_ addSubview:segment_];
7477 if ([Role_ isEqualToString:@"User"]) index = 0;
7478 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7479 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7481 [segment_ setSelectedSegmentIndex:index];
7482 [self showDoneButton];
7485 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7486 [self resizeSegmentedControl];
7488 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7489 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7490 [table_ setDelegate:self];
7491 [table_ setDataSource:self];
7492 [[self view] addSubview:table_];
7493 [table_ reloadData];
7497 - (void) resizeSegmentedControl {
7498 CGFloat width = [[self view] frame].size.width;
7499 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7502 - (void) viewWillAppear:(BOOL)animated {
7503 [super viewWillAppear:animated];
7505 [self resizeSegmentedControl];
7508 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7509 [self resizeSegmentedControl];
7512 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7513 [self resizeSegmentedControl];
7517 NSString *role(nil);
7519 switch ([segment_ selectedSegmentIndex]) {
7520 case 0: role = @"User"; break;
7521 case 1: role = @"Hacker"; break;
7522 case 2: role = @"Developer"; break;
7527 if (![role isEqualToString:Role_]) {
7528 bool rolling(Role_ == nil);
7531 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7535 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7540 [roledelegate_ loadData];
7542 [roledelegate_ updateData];
7546 - (void) segmentChanged:(UISegmentedControl *)control {
7547 [self showDoneButton];
7550 - (void) saveAndClose {
7553 [[self navigationItem] setRightBarButtonItem:nil];
7554 [[self navigationController] dismissModalViewControllerAnimated:YES];
7557 - (void) doneButtonClicked {
7558 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7559 [spinner startAnimating];
7560 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7561 [[self navigationItem] setRightBarButtonItem:spinItem];
7563 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7566 - (void) showDoneButton {
7567 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7568 initWithTitle:UCLocalize("DONE")
7569 style:UIBarButtonItemStyleDone
7571 action:@selector(doneButtonClicked)
7572 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7575 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7576 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7580 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7584 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7585 return nil; // This method is required by the protocol.
7588 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7590 return UCLocalize("ROLE_EX");
7592 return [NSString stringWithFormat:
7593 @"%@: %@\n%@: %@\n%@: %@",
7594 UCLocalize("USER"), UCLocalize("USER_EX"),
7595 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7596 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7601 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7602 return section == 3 ? 44.0f : 0;
7605 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7606 return section == 3 ? container_ : nil;
7611 /* Stash Controller {{{ */
7612 @interface CYStashController : CYViewController {
7613 // XXX: just delete these things
7614 _transient UIActivityIndicatorView *spinner_;
7615 _transient UILabel *status_;
7616 _transient UILabel *caption_;
7620 @implementation CYStashController
7622 if ((self = [super init])) {
7623 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7625 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7626 CGRect spinrect = [spinner_ frame];
7627 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7628 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7629 [spinner_ setFrame:spinrect];
7630 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7631 [[self view] addSubview:spinner_];
7632 [spinner_ startAnimating];
7635 captrect.size.width = [[self view] frame].size.width;
7636 captrect.size.height = 40.0f;
7637 captrect.origin.x = 0;
7638 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7639 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7640 [caption_ setText:@"Initializing Filesystem"];
7641 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7642 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7643 [caption_ setTextColor:[UIColor whiteColor]];
7644 [caption_ setBackgroundColor:[UIColor clearColor]];
7645 [caption_ setShadowColor:[UIColor blackColor]];
7646 [caption_ setTextAlignment:UITextAlignmentCenter];
7647 [[self view] addSubview:caption_];
7650 statusrect.size.width = [[self view] frame].size.width;
7651 statusrect.size.height = 30.0f;
7652 statusrect.origin.x = 0;
7653 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7654 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7655 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7656 [status_ setText:@"(Cydia will exit when complete.)"];
7657 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7658 [status_ setTextColor:[UIColor whiteColor]];
7659 [status_ setBackgroundColor:[UIColor clearColor]];
7660 [status_ setShadowColor:[UIColor blackColor]];
7661 [status_ setTextAlignment:UITextAlignmentCenter];
7662 [[self view] addSubview:status_];
7666 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7667 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7672 /* Cydia Container {{{ */
7673 @interface CYContainer : UIViewController <ProgressDelegate> {
7674 _transient Database *database_;
7675 RefreshBar *refreshbar_;
7679 // XXX: ok, "updatedelegate_"?...
7680 _transient NSObject<CydiaDelegate> *updatedelegate_;
7681 // XXX: can't we query for this variable when we need it?
7682 _transient UITabBarController *root_;
7685 - (void) setTabBarController:(UITabBarController *)controller;
7687 - (void) dropBar:(BOOL)animated;
7688 - (void) beginUpdate;
7689 - (void) raiseBar:(BOOL)animated;
7694 @implementation CYContainer
7696 - (BOOL) _reallyWantsFullScreenLayout {
7700 // NOTE: UIWindow only sends the top controller these messages,
7701 // So we have to forward them on.
7703 - (void) viewDidAppear:(BOOL)animated {
7704 [super viewDidAppear:animated];
7705 [root_ viewDidAppear:animated];
7708 - (void) viewWillAppear:(BOOL)animated {
7709 [super viewWillAppear:animated];
7710 [root_ viewWillAppear:animated];
7713 - (void) viewDidDisappear:(BOOL)animated {
7714 [super viewDidDisappear:animated];
7715 [root_ viewDidDisappear:animated];
7718 - (void) viewWillDisappear:(BOOL)animated {
7719 [super viewWillDisappear:animated];
7720 [root_ viewWillDisappear:animated];
7723 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7724 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7727 - (void) setTabBarController:(UITabBarController *)controller {
7729 [[self view] addSubview:[root_ view]];
7732 - (void) setUpdate:(NSDate *)date {
7736 - (void) beginUpdate {
7738 [refreshbar_ start];
7743 detachNewThreadSelector:@selector(performUpdate)
7749 - (void) performUpdate { _pooled
7751 status.setDelegate(self);
7752 [database_ updateWithStatus:status];
7755 performSelectorOnMainThread:@selector(completeUpdate)
7761 - (void) completeUpdate {
7766 [self raiseBar:YES];
7768 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7771 - (void) cancelUpdate {
7773 [self raiseBar:YES];
7775 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7778 - (void) cancelPressed {
7779 [self cancelUpdate];
7786 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7787 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7790 - (void) startProgress {
7793 - (void) setProgressTitle:(NSString *)title {
7795 performSelectorOnMainThread:@selector(_setProgressTitle:)
7801 - (bool) isCancelling:(size_t)received {
7805 - (void) setProgressPercent:(float)percent {
7807 performSelectorOnMainThread:@selector(_setProgressPercent:)
7808 withObject:[NSNumber numberWithFloat:percent]
7813 - (void) addProgressOutput:(NSString *)output {
7815 performSelectorOnMainThread:@selector(_addProgressOutput:)
7821 - (void) _setProgressTitle:(NSString *)title {
7822 [refreshbar_ setPrompt:title];
7825 - (void) _setProgressPercent:(NSNumber *)percent {
7826 [refreshbar_ setProgress:[percent floatValue]];
7829 - (void) _addProgressOutput:(NSString *)output {
7832 - (void) setUpdateDelegate:(id)delegate {
7833 updatedelegate_ = delegate;
7836 - (CGFloat) statusBarHeight {
7837 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7838 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7840 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7844 - (void) dropBar:(BOOL)animated {
7849 [[self view] addSubview:refreshbar_];
7851 CGFloat sboffset = [self statusBarHeight];
7853 CGRect barframe = [refreshbar_ frame];
7854 barframe.origin.y = sboffset;
7855 [refreshbar_ setFrame:barframe];
7858 [UIView beginAnimations:nil context:NULL];
7859 CGRect viewframe = [[root_ view] frame];
7860 viewframe.origin.y += barframe.size.height + sboffset;
7861 viewframe.size.height -= barframe.size.height + sboffset;
7862 [[root_ view] setFrame:viewframe];
7864 [UIView commitAnimations];
7866 // Ensure bar has the proper width for our view, it might have changed
7867 barframe.size.width = viewframe.size.width;
7868 [refreshbar_ setFrame:barframe];
7870 // XXX: fix Apple's layout bug
7871 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7874 - (void) raiseBar:(BOOL)animated {
7879 [refreshbar_ removeFromSuperview];
7881 CGFloat sboffset = [self statusBarHeight];
7884 [UIView beginAnimations:nil context:NULL];
7885 CGRect barframe = [refreshbar_ frame];
7886 CGRect viewframe = [[root_ view] frame];
7887 viewframe.origin.y -= barframe.size.height + sboffset;
7888 viewframe.size.height += barframe.size.height + sboffset;
7889 [[root_ view] setFrame:viewframe];
7891 [UIView commitAnimations];
7893 // XXX: fix Apple's layout bug
7894 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7897 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7898 // XXX: fix Apple's layout bug
7899 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7902 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7908 // XXX: fix Apple's layout bug
7909 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7912 - (void) statusBarFrameChanged:(NSNotification *)notification {
7920 [refreshbar_ release];
7921 [[NSNotificationCenter defaultCenter] removeObserver:self];
7925 - (id) initWithDatabase:(Database *)database {
7926 if ((self = [super init]) != nil) {
7927 database_ = database;
7929 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7930 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7932 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7949 @interface Cydia : UIApplication <
7950 ConfirmationControllerDelegate,
7951 ProgressControllerDelegate,
7953 UINavigationControllerDelegate,
7954 UITabBarControllerDelegate
7956 // XXX: evaluate all fields for _transient
7959 CYContainer *container_;
7960 CYTabBarController *tabbar_;
7962 NSMutableArray *essential_;
7963 NSMutableArray *broken_;
7965 Database *database_;
7971 SectionsController *sections_;
7972 ChangesController *changes_;
7973 ManageController *manage_;
7974 SearchController *search_;
7975 SourceTable *sources_;
7976 InstalledController *installed_;
7979 CYStashController *stash_;
7984 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7985 - (void) setPage:(CYViewController *)page;
7990 static _finline void _setHomePage(Cydia *self) {
7991 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7994 @implementation Cydia
7996 - (void) beginUpdate {
7997 [container_ beginUpdate];
8001 return [container_ updating];
8004 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8009 if ([broken_ count] != 0) {
8010 int count = [broken_ count];
8012 UIAlertView *alert = [[[UIAlertView alloc]
8013 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8014 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8016 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8017 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8020 [alert setContext:@"fixhalf"];
8022 } else if (!Ignored_ && [essential_ count] != 0) {
8023 int count = [essential_ count];
8025 UIAlertView *alert = [[[UIAlertView alloc]
8026 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8027 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8029 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8030 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8033 [alert setContext:@"upgrade"];
8038 - (void) _saveConfig {
8041 NSString *error(nil);
8042 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8044 NSError *error(nil);
8045 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8046 NSLog(@"failure to save metadata data: %@", error);
8049 NSLog(@"failure to serialize metadata: %@", error);
8057 - (void) _updateData {
8060 /* XXX: this is just stupid */
8061 if (tag_ != 1 && sections_ != nil)
8062 [sections_ reloadData];
8063 if (tag_ != 2 && changes_ != nil)
8064 [changes_ reloadData];
8065 if (tag_ != 4 && search_ != nil)
8066 [search_ reloadData];
8068 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8071 - (int)indexOfTabWithTag:(int)tag {
8073 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8074 if ([[controller tabBarItem] tag] == tag)
8082 - (void) _refreshIfPossible {
8083 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8085 bool recently = false;
8086 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8087 if (update != nil) {
8088 NSTimeInterval interval([update timeIntervalSinceNow]);
8089 if (interval <= 0 && interval > -(15*60))
8093 // Don't automatic refresh if:
8094 // - We already refreshed recently.
8095 // - We already auto-refreshed this launch.
8096 // - Auto-refresh is disabled.
8097 if (recently || loaded_ || ManualRefresh) {
8098 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8100 // If we are cancelling due to ManualRefresh or a recent refresh
8101 // we need to make sure it knows it's already loaded.
8105 // We are going to load, so remember that.
8109 SCNetworkReachabilityFlags flags; {
8110 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8111 SCNetworkReachabilityGetFlags(reachability, &flags);
8112 CFRelease(reachability);
8115 // XXX: this elaborate mess is what Apple is using to determine this? :(
8116 // XXX: do we care if the user has to intervene? maybe that's ok?
8118 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8119 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8120 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8121 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8122 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8123 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8127 // If we can reach the server, auto-refresh!
8129 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8134 - (void) refreshIfPossible {
8135 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8138 - (void) _reloadData {
8139 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8140 [hud setText:UCLocalize("RELOADING_DATA")];
8142 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8145 [self removeProgressHUD:hud];
8149 [essential_ removeAllObjects];
8150 [broken_ removeAllObjects];
8152 NSArray *packages([database_ packages]);
8153 for (Package *package in packages) {
8155 [broken_ addObject:package];
8156 if ([package upgradableAndEssential:NO]) {
8157 if ([package essential])
8158 [essential_ addObject:package];
8163 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8165 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8166 [changesItem setBadgeValue:badge];
8167 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8169 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8170 [self setApplicationBadge:badge];
8172 [self setApplicationBadgeString:badge];
8174 [changesItem setBadgeValue:nil];
8175 [changesItem setAnimatedBadge:NO];
8177 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8178 [self removeApplicationBadge];
8179 else // XXX: maybe use setApplicationBadgeString also?
8180 [self setApplicationIconBadgeNumber:0];
8185 [self refreshIfPossible];
8188 - (void) updateData {
8197 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8198 _assert(file != NULL);
8200 for (NSString *key in [Sources_ allKeys]) {
8201 NSDictionary *source([Sources_ objectForKey:key]);
8203 fprintf(file, "%s %s %s\n",
8204 [[source objectForKey:@"Type"] UTF8String],
8205 [[source objectForKey:@"URI"] UTF8String],
8206 [[source objectForKey:@"Distribution"] UTF8String]
8214 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8215 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8217 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8218 [container_ presentModalViewController:navigation animated:YES];
8221 detachNewThreadSelector:@selector(update_)
8224 title:UCLocalize("UPDATING_SOURCES")
8228 - (void) reloadData {
8229 @synchronized (self) {
8235 pkgProblemResolver *resolver = [database_ resolver];
8237 resolver->InstallProtect();
8238 if (!resolver->Resolve(true))
8242 - (CGRect) popUpBounds {
8243 return [[tabbar_ view] bounds];
8247 if (![database_ prepare])
8250 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8251 [page setDelegate:self];
8252 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8253 [confirm_ setDelegate:self];
8256 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8257 [container_ presentModalViewController:confirm_ animated:YES];
8263 @synchronized (self) {
8268 - (void) clearPackage:(Package *)package {
8269 @synchronized (self) {
8276 - (void) installPackages:(NSArray *)packages {
8277 @synchronized (self) {
8278 for (Package *package in packages)
8285 - (void) installPackage:(Package *)package {
8286 @synchronized (self) {
8293 - (void) removePackage:(Package *)package {
8294 @synchronized (self) {
8301 - (void) distUpgrade {
8302 @synchronized (self) {
8303 if (![database_ upgrade])
8310 @synchronized (self) {
8315 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8316 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8318 if (navigation != nil) {
8319 [navigation pushViewController:progress animated:YES];
8321 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8323 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8324 [container_ presentModalViewController:navigation animated:YES];
8328 detachNewThreadSelector:@selector(perform)
8331 title:UCLocalize("RUNNING")
8335 - (void) progressControllerIsComplete:(ProgressController *)progress {
8339 - (void) setPage:(CYViewController *)page {
8340 [page setDelegate:self];
8342 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8343 [navController setViewControllers:[NSArray arrayWithObject:page]];
8344 for (CYNavigationController *page in [tabbar_ viewControllers])
8345 if (page != navController)
8346 [page setViewControllers:nil];
8349 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8350 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8351 [browser loadURL:url];
8355 - (SectionsController *) sectionsController {
8356 if (sections_ == nil)
8357 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8361 - (ChangesController *) changesController {
8362 if (changes_ == nil)
8363 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8367 - (ManageController *) manageController {
8368 if (manage_ == nil) {
8369 manage_ = (ManageController *) [[self
8370 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8371 withClass:[ManageController class]
8374 queueDelegate_ = manage_;
8379 - (SearchController *) searchController {
8381 search_ = [[SearchController alloc] initWithDatabase:database_];
8385 - (SourceTable *) sourcesController {
8386 if (sources_ == nil)
8387 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8391 - (InstalledController *) installedController {
8392 if (installed_ == nil) {
8393 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8395 queueDelegate_ = installed_;
8400 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8401 int tag = [[viewController tabBarItem] tag];
8403 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8405 } else if (tag_ == 1) {
8406 [[self sectionsController] resetView];
8410 case kCydiaTag: _setHomePage(self); break;
8412 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8413 case kChangesTag: [self setPage:[self changesController]]; break;
8414 case kManageTag: [self setPage:[self manageController]]; break;
8415 case kInstalledTag: [self setPage:[self installedController]]; break;
8416 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8417 case kSearchTag: [self setPage:[self searchController]]; break;
8425 - (void) showSettings {
8426 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8427 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8429 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8430 [container_ presentModalViewController:nav animated:YES];
8433 - (void) setPackageController:(PackageController *)view {
8435 [view setPackage:nil];
8439 - (PackageController *) _packageController {
8440 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8443 - (PackageController *) packageController {
8444 return [self _packageController];
8447 // Returns the navigation controller for the queuing badge.
8448 - (id) queueBadgeController {
8449 int index = [self indexOfTabWithTag:kManageTag];
8451 index = [self indexOfTabWithTag:kInstalledTag];
8453 return [[tabbar_ viewControllers] objectAtIndex:index];
8456 - (void) cancelAndClear:(bool)clear {
8457 @synchronized (self) {
8463 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8467 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8471 [queueDelegate_ queueStatusDidChange];
8475 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8476 NSString *context([alert context]);
8478 if ([context isEqualToString:@"fixhalf"]) {
8479 if (button == [alert firstOtherButtonIndex]) {
8480 @synchronized (self) {
8481 for (Package *broken in broken_) {
8484 NSString *id = [broken id];
8485 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8486 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8487 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8488 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8494 } else if (button == [alert cancelButtonIndex]) {
8495 [broken_ removeAllObjects];
8499 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8500 } else if ([context isEqualToString:@"upgrade"]) {
8501 if (button == [alert firstOtherButtonIndex]) {
8502 @synchronized (self) {
8503 for (Package *essential in essential_)
8504 [essential install];
8509 } else if (button == [alert firstOtherButtonIndex] + 1) {
8511 } else if (button == [alert cancelButtonIndex]) {
8515 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8519 - (void) system:(NSString *)command { _pooled
8520 system([command UTF8String]);
8523 - (void) applicationWillSuspend {
8525 [super applicationWillSuspend];
8528 - (BOOL) hudIsShowing {
8529 return (hudcount_ > 0);
8532 - (void) applicationSuspend:(__GSEvent *)event {
8533 // Use external process status API internally.
8534 // This is probably a really bad idea.
8535 uint64_t status = 0;
8537 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8538 notify_get_state(notify_token, &status);
8539 notify_cancel(notify_token);
8542 if (![self hudIsShowing] && status == 0)
8543 [super applicationSuspend:event];
8546 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8547 if (![self hudIsShowing])
8548 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8551 - (void) _setSuspended:(BOOL)value {
8552 if (![self hudIsShowing])
8553 [super _setSuspended:value];
8556 - (UIProgressHUD *) addProgressHUD {
8557 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8558 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8560 [window_ setUserInteractionEnabled:NO];
8563 UIViewController *target = container_;
8564 while ([target modalViewController] != nil) target = [target modalViewController];
8565 [[target view] addSubview:hud];
8571 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8573 [hud removeFromSuperview];
8574 [window_ setUserInteractionEnabled:YES];
8578 - (CYViewController *) pageForPackage:(NSString *)name {
8579 if (Package *package = [database_ packageWithName:name]) {
8580 PackageController *view([self packageController]);
8581 [view setPackage:package];
8584 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8585 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8586 return [self _pageForURL:url withClass:[CYBrowserController class]];
8590 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8594 NSString *href([url absoluteString]);
8595 if ([href hasPrefix:@"apptapp://package/"])
8596 return [self pageForPackage:[href substringFromIndex:18]];
8598 NSString *scheme([[url scheme] lowercaseString]);
8599 if (![scheme isEqualToString:@"cydia"])
8601 NSString *path([url absoluteString]);
8602 if ([path length] < 8)
8604 path = [path substringFromIndex:8];
8605 if (![path hasPrefix:@"/"])
8606 path = [@"/" stringByAppendingString:path];
8608 if ([path isEqualToString:@"/add-source"])
8609 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8610 else if ([path isEqualToString:@"/storage"])
8611 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8612 else if ([path isEqualToString:@"/sources"])
8613 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8614 else if ([path isEqualToString:@"/packages"])
8615 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8616 else if ([path hasPrefix:@"/url/"])
8617 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8618 else if ([path hasPrefix:@"/launch/"])
8619 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8620 else if ([path hasPrefix:@"/package-settings/"])
8621 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8622 else if ([path hasPrefix:@"/package-signature/"])
8623 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8624 else if ([path hasPrefix:@"/package/"])
8625 return [self pageForPackage:[path substringFromIndex:9]];
8626 else if ([path hasPrefix:@"/files/"]) {
8627 NSString *name = [path substringFromIndex:7];
8629 if (Package *package = [database_ packageWithName:name]) {
8630 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8631 [files setPackage:package];
8639 - (BOOL) openCydiaURL:(NSURL *)url {
8640 CYViewController *page = nil;
8643 NSLog(@"open url: %@", url);
8645 if ((page = [self pageForURL:url hasTag:&tag])) {
8646 [self setPage:page];
8648 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8654 - (void) applicationOpenURL:(NSURL *)url {
8655 [super applicationOpenURL:url];
8656 NSLog(@"first: %@", url);
8657 if (!loaded_) starturl_ = [url retain];
8658 else [self openCydiaURL:url];
8661 - (void) applicationWillResignActive:(UIApplication *)application {
8662 // Stop refreshing if you get a phone call or lock the device.
8663 if ([container_ updating])
8664 [container_ cancelUpdate];
8666 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8667 [super applicationWillResignActive:application];
8670 - (void) addStashController {
8671 stash_ = [[CYStashController alloc] init];
8672 [window_ addSubview:[stash_ view]];
8675 - (void) removeStashController {
8676 [[stash_ view] removeFromSuperview];
8681 [self setIdleTimerDisabled:YES];
8683 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8684 [self setStatusBarShowsProgress:YES];
8685 UpdateExternalStatus(1);
8687 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8689 UpdateExternalStatus(0);
8690 [self setStatusBarShowsProgress:NO];
8692 [self removeStashController];
8694 if (ExecFork() == 0) {
8695 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8696 perror("launchctl stop");
8700 - (void) setupTabBarController {
8701 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8702 [tabbar_ setDelegate:self];
8704 NSMutableArray *items([NSMutableArray arrayWithObjects:
8705 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8706 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8707 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8708 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8712 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8713 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8715 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8718 NSMutableArray *controllers([NSMutableArray array]);
8720 for (UITabBarItem *item in items) {
8721 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8722 [controller setTabBarItem:item];
8723 [controllers addObject:controller];
8726 [tabbar_ setViewControllers:controllers];
8729 - (void) applicationDidFinishLaunching:(id)unused {
8730 [CYBrowserController _initialize];
8732 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8734 Font12_ = [[UIFont systemFontOfSize:12] retain];
8735 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8736 Font14_ = [[UIFont systemFontOfSize:14] retain];
8737 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8738 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8742 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8743 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8745 UIScreen *screen([UIScreen mainScreen]);
8747 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8748 [window_ orderFront:self];
8749 [window_ makeKey:self];
8750 [window_ setHidden:NO];
8753 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8754 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8755 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8756 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8757 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8758 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8759 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8760 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8761 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8764 [self addStashController];
8765 // XXX: this would be much cleaner as a yieldToSelector:
8766 // that way the removeStashController could happen right here inline
8767 // we also could no longer require the useless stash_ field anymore
8768 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8772 database_ = [Database sharedInstance];
8774 [self setupTabBarController];
8776 container_ = [[CYContainer alloc] initWithDatabase:database_];
8777 [container_ setUpdateDelegate:self];
8778 [container_ setTabBarController:tabbar_];
8779 [window_ addSubview:[container_ view]];
8781 // Show pinstripes while loading data.
8782 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8784 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8791 [self showSettings];
8795 [window_ setUserInteractionEnabled:NO];
8797 UIView *container = [[[UIView alloc] init] autorelease];
8798 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8800 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8801 [spinner startAnimating];
8802 [container addSubview:spinner];
8804 UILabel *label = [[[UILabel alloc] init] autorelease];
8805 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8806 [label setBackgroundColor:[UIColor clearColor]];
8807 [label setTextColor:[UIColor blackColor]];
8808 [label setShadowColor:[UIColor whiteColor]];
8809 [label setShadowOffset:CGSizeMake(0, 1)];
8810 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8811 [container addSubview:label];
8813 CGSize viewsize = [[tabbar_ view] frame].size;
8814 CGSize spinnersize = [spinner bounds].size;
8815 CGSize textsize = [[label text] sizeWithFont:[label font]];
8816 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8818 CGRect containrect = {
8819 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8820 CGSizeMake(bothwidth, spinnersize.height)
8823 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8831 [container setFrame:containrect];
8832 [spinner setFrame:spinrect];
8833 [label setFrame:textrect];
8834 [[container_ view] addSubview:container];
8839 // Show the initial page
8840 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
8841 [tabbar_ setSelectedIndex:0];
8845 [starturl_ release];
8848 [window_ setUserInteractionEnabled:YES];
8850 // XXX: does this actually slow anything down?
8851 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8852 [container removeFromSuperview];
8855 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8856 if (item != nil && IsWildcat_) {
8857 [sheet showFromBarButtonItem:item animated:YES];
8859 [sheet showInView:window_];
8866 id Alloc_(id self, SEL selector) {
8867 id object = alloc_(self, selector);
8868 lprintf("[%s]A-%p\n", self->isa->name, object);
8873 id Dealloc_(id self, SEL selector) {
8874 id object = dealloc_(self, selector);
8875 lprintf("[%s]D-%p\n", self->isa->name, object);
8879 Class $WebDefaultUIKitDelegate;
8881 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8882 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8883 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8884 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8887 static NSNumber *shouldPlayKeyboardSounds;
8891 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8893 case 1104: // Keyboard Button Clicked
8894 case 1105: // Keyboard Delete Repeated
8895 if (shouldPlayKeyboardSounds == nil) {
8896 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8897 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8900 if (![shouldPlayKeyboardSounds boolValue])
8904 _UIHardware$_playSystemSound$(self, _cmd, sound);
8908 int main(int argc, char *argv[]) { _pooled
8911 if (Class $UIDevice = objc_getClass("UIDevice")) {
8912 UIDevice *device([$UIDevice currentDevice]);
8913 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8917 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8919 /* Library Hacks {{{ */
8920 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8922 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8923 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8924 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8925 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8926 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8929 $UIHardware = objc_getClass("UIHardware");
8930 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8931 if (UIHardware$_playSystemSound$ != NULL) {
8932 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8933 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8936 /* Set Locale {{{ */
8937 Locale_ = CFLocaleCopyCurrent();
8938 Languages_ = [NSLocale preferredLanguages];
8939 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8940 //NSLog(@"%@", [Languages_ description]);
8943 if (Languages_ == nil || [Languages_ count] == 0)
8944 // XXX: consider just setting to C and then falling through?
8947 lang = [[Languages_ objectAtIndex:0] UTF8String];
8948 setenv("LANG", lang, true);
8951 //std::setlocale(LC_ALL, lang);
8952 NSLog(@"Setting Language: %s", lang);
8955 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8957 /* Parse Arguments {{{ */
8958 bool substrate(false);
8964 for (int argi(1); argi != argc; ++argi)
8965 if (strcmp(argv[argi], "--") == 0) {
8967 argv[argi] = argv[0];
8973 for (int argi(1); argi != arge; ++argi)
8974 if (strcmp(args[argi], "--substrate") == 0)
8977 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8981 App_ = [[NSBundle mainBundle] bundlePath];
8982 Home_ = NSHomeDirectory();
8988 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8989 alloc_ = alloc->method_imp;
8990 alloc->method_imp = (IMP) &Alloc_;*/
8992 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8993 dealloc_ = dealloc->method_imp;
8994 dealloc->method_imp = (IMP) &Dealloc_;*/
8996 /* System Information {{{ */
9000 size = sizeof(maxproc);
9001 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9002 perror("sysctlbyname(\"kern.maxproc\", ?)");
9003 else if (maxproc < 64) {
9005 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9006 perror("sysctlbyname(\"kern.maxproc\", #)");
9009 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9010 char *osversion = new char[size];
9011 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9012 perror("sysctlbyname(\"kern.osversion\", ?)");
9014 System_ = [NSString stringWithUTF8String:osversion];
9016 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9017 char *machine = new char[size];
9018 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9019 perror("sysctlbyname(\"hw.machine\", ?)");
9023 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9024 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9025 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9026 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9030 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9031 NSData *data((NSData *) ecid);
9032 size_t length([data length]);
9033 uint8_t bytes[length];
9034 [data getBytes:bytes];
9035 char string[length * 2 + 1];
9036 for (size_t i(0); i != length; ++i)
9037 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9038 ChipID_ = [NSString stringWithUTF8String:string];
9042 IOObjectRelease(service);
9046 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9048 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9049 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9050 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9052 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9053 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9054 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9056 if (mcc != NULL && mnc != NULL)
9057 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9064 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9065 Build_ = [system objectForKey:@"ProductBuildVersion"];
9066 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9067 Product_ = [info objectForKey:@"SafariProductVersion"];
9068 Safari_ = [info objectForKey:@"CFBundleVersion"];
9071 /* Load Database {{{ */
9073 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9075 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9077 if (Metadata_ == NULL)
9078 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9080 Settings_ = [Metadata_ objectForKey:@"Settings"];
9082 Packages_ = [Metadata_ objectForKey:@"Packages"];
9083 Sections_ = [Metadata_ objectForKey:@"Sections"];
9084 Sources_ = [Metadata_ objectForKey:@"Sources"];
9086 Token_ = [Metadata_ objectForKey:@"Token"];
9089 if (Settings_ != nil)
9090 Role_ = [Settings_ objectForKey:@"Role"];
9092 if (Sections_ == nil) {
9093 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9094 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9097 if (Sources_ == nil) {
9098 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9099 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9104 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9107 if (Packages_ != nil) {
9108 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9110 [Metadata_ removeObjectForKey:@"Packages"];
9115 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9117 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9118 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9119 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9120 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9121 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9122 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9124 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9126 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9127 unlink("/tmp/.cydia.fw");
9129 } else if (access("/User", F_OK) != 0 || version < 2) {
9132 system("/usr/libexec/cydia/firmware.sh");
9136 _assert([[NSFileManager defaultManager]
9137 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9138 withIntermediateDirectories:YES
9143 if (access("/tmp/cydia.chk", F_OK) == 0) {
9144 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9145 _assert(errno == ENOENT);
9146 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9147 _assert(errno == ENOENT);
9150 /* APT Initialization {{{ */
9151 _assert(pkgInitConfig(*_config));
9152 _assert(pkgInitSystem(*_config, _system));
9155 _config->Set("APT::Acquire::Translation", lang);
9157 // XXX: this timeout might be important :(
9158 //_config->Set("Acquire::http::Timeout", 15);
9160 _config->Set("Acquire::http::MaxParallel", 3);
9162 /* Color Choices {{{ */
9163 space_ = CGColorSpaceCreateDeviceRGB();
9165 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9166 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9167 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9168 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9169 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9170 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9171 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9172 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9173 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9175 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9176 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9178 /* UIKit Configuration {{{ */
9179 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9180 if ($GSFontSetUseLegacyFontMetrics != NULL)
9181 $GSFontSetUseLegacyFontMetrics(YES);
9183 // XXX: I have a feeling this was important
9184 //UIKeyboardDisableAutomaticAppearance();
9187 Colon_ = UCLocalize("COLON_DELIMITED");
9188 Elision_ = UCLocalize("ELISION");
9189 Error_ = UCLocalize("ERROR");
9190 Warning_ = UCLocalize("WARNING");
9193 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9195 CGColorSpaceRelease(space_);