1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
122 #include <Cytore.hpp>
124 #include "UICaboodle/BrowserView.h"
125 #include "SDURLCache/SDURLCache.h"
127 #include "substrate.h"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
202 #define CYPoolStart() \
203 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
205 #define CYPoolEnd() \
209 // Hash Functions/Structures {{{
210 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
218 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
220 void NSLogPoint(const char *fix, const CGPoint &point) {
221 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
224 void NSLogRect(const char *fix, const CGRect &rect) {
225 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
228 static _finline NSString *CydiaURL(NSString *path) {
230 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
231 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
232 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
233 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
234 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
235 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
238 static _finline void UpdateExternalStatus(uint64_t newStatus) {
240 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
241 notify_set_state(notify_token, newStatus);
242 notify_cancel(notify_token);
244 notify_post("com.saurik.Cydia.status");
247 /* [NSObject yieldToSelector:(withObject:)] {{{*/
248 @interface NSObject (Cydia)
249 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
250 - (id) yieldToSelector:(SEL)selector;
253 @implementation NSObject (Cydia)
258 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
259 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
260 id object([[context objectAtIndex:1] nonretainedObjectValue]);
261 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
263 /* XXX: deal with exceptions */
264 id value([self performSelector:selector withObject:object]);
266 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
267 [context removeAllObjects];
268 if ([signature methodReturnLength] != 0 && value != nil)
269 [context addObject:value];
274 performSelectorOnMainThread:@selector(doNothing)
280 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
281 volatile bool stopped(false);
283 NSMutableArray *context([NSMutableArray arrayWithObjects:
284 [NSValue valueWithPointer:selector],
285 [NSValue valueWithNonretainedObject:object],
286 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
289 NSThread *thread([[[NSThread alloc]
291 selector:@selector(_yieldToContext:)
297 NSRunLoop *loop([NSRunLoop currentRunLoop]);
298 NSDate *future([NSDate distantFuture]);
300 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
302 return [context count] == 0 ? nil : [context objectAtIndex:0];
305 - (id) yieldToSelector:(SEL)selector {
306 return [self yieldToSelector:selector withObject:nil];
312 /* Cydia Action Sheet {{{ */
313 @interface CYActionSheet : UIAlertView {
317 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
320 @implementation CYActionSheet
322 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
323 if ((self = [super init])) {
324 [self setTitle:title];
325 [self setDelegate:self];
326 for (NSString *button in buttons) [self addButtonWithTitle:button];
327 [self setCancelButtonIndex:index];
331 - (void) _updateFrameForDisplay {
332 [super _updateFrameForDisplay];
333 if ([self cancelButtonIndex] == -1) {
334 NSArray *buttons = [self buttons];
335 if ([buttons count]) {
336 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
337 for (UIThreePartButton *button in buttons)
338 [button setBackground:background forState:0];
343 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
344 button_ = buttonIndex + 1;
348 [self dismissWithClickedButtonIndex:-1 animated:YES];
351 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
352 [self setRunsModal:YES];
361 /* NSForcedOrderingSearch doesn't work on the iPhone */
362 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
363 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
364 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
366 /* Information Dictionaries {{{ */
367 @interface NSMutableArray (Cydia)
368 - (void) addInfoDictionary:(NSDictionary *)info;
371 @implementation NSMutableArray (Cydia)
373 - (void) addInfoDictionary:(NSDictionary *)info {
374 [self addObject:info];
379 @interface NSMutableDictionary (Cydia)
380 - (void) addInfoDictionary:(NSDictionary *)info;
383 @implementation NSMutableDictionary (Cydia)
385 - (void) addInfoDictionary:(NSDictionary *)info {
386 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
392 #define lprintf(args...) fprintf(stderr, args)
395 #define TraceLogging (1 && !ForRelease)
396 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
397 #define ProfileTimes (0 && !ForRelease)
398 #define ForSaurik (0 && !ForRelease)
399 #define LogBrowser (0 && !ForRelease)
400 #define TrackResize (0 && !ForRelease)
401 #define ManualRefresh (1 && !ForRelease)
402 #define ShowInternals (0 && !ForRelease)
403 #define IgnoreInstall (0 && !ForRelease)
404 #define AlwaysReload (0 && !ForRelease)
408 #define _trace(args...)
413 #define _profile(name) {
416 #define PrintTimes() do {} while (false)
420 typedef uint32_t (*SKRadixFunction)(id, void *);
422 @interface NSMutableArray (Radix)
423 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
431 @implementation NSMutableArray (Radix)
433 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
434 size_t count([self count]);
435 struct RadixItem_ *swap(new RadixItem_[count * 2]);
437 for (size_t i(0); i != count; ++i) {
438 RadixItem_ &item(swap[i]);
441 id object([self objectAtIndex:i]);
442 item.key = function(object, argument);
445 struct RadixItem_ *lhs(swap), *rhs(swap + count);
447 static const size_t width = 32;
448 static const size_t bits = 11;
449 static const size_t slots = 1 << bits;
450 static const size_t passes = (width + (bits - 1)) / bits;
452 size_t *hist(new size_t[slots]);
454 for (size_t pass(0); pass != passes; ++pass) {
455 memset(hist, 0, sizeof(size_t) * slots);
457 for (size_t i(0); i != count; ++i) {
458 uint32_t key(lhs[i].key);
460 key &= _not(uint32_t) >> width - bits;
465 for (size_t i(0); i != slots; ++i) {
466 size_t local(offset);
471 for (size_t i(0); i != count; ++i) {
472 uint32_t key(lhs[i].key);
474 key &= _not(uint32_t) >> width - bits;
475 rhs[hist[key]++] = lhs[i];
478 RadixItem_ *tmp(lhs);
485 const void **values(new const void *[count]);
486 for (size_t i(0); i != count; ++i)
487 values[i] = [self objectAtIndex:lhs[i].index];
488 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
496 /* Insertion Sort {{{ */
498 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
499 const char *ptr = (const char *)list;
501 CFIndex half = count / 2;
502 const char *probe = ptr + elementSize * half;
503 CFComparisonResult cr = comparator(element, probe, context);
504 if (0 == cr) return (probe - (const char *)list) / elementSize;
505 ptr = (cr < 0) ? ptr : probe + elementSize;
506 count = (cr < 0) ? half : (half + (count & 1) - 1);
508 return (ptr - (const char *)list) / elementSize;
511 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
512 const char *ptr = (const char *)list;
514 CFIndex half = count / 2;
515 const char *probe = ptr + elementSize * half;
516 CFComparisonResult cr = comparator(element, probe, context);
517 if (0 == cr) return (probe - (const char *)list) / elementSize;
518 ptr = (cr < 0) ? ptr : probe + elementSize;
519 count = (cr < 0) ? half : (half + (count & 1) - 1);
521 return (ptr - (const char *)list) / elementSize;
524 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
525 if (range.length == 0)
527 const void **values(new const void *[range.length]);
528 CFArrayGetValues(array, range, values);
530 #if HistogramInsertionSort > 0
531 uint32_t total(0), *offsets(new uint32_t[range.length]);
534 for (CFIndex index(1); index != range.length; ++index) {
535 const void *value(values[index]);
536 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
537 CFIndex correct(index);
538 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
539 #if HistogramInsertionSort > 1
540 NSLog(@"%@ < %@", value, values[correct - 1]);
545 if (correct != index) {
546 size_t offset(index - correct);
547 #if HistogramInsertionSort
551 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
553 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
554 values[correct] = value;
558 CFArrayReplaceValues(array, range, values, range.length);
561 #if HistogramInsertionSort > 0
562 for (CFIndex index(0); index != range.length; ++index)
563 if (offsets[index] != 0)
564 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
565 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
572 /* Apple Bug Fixes {{{ */
573 @implementation UIWebDocumentView (Cydia)
575 - (void) _setScrollerOffset:(CGPoint)offset {
576 UIScroller *scroller([self _scroller]);
578 CGSize size([scroller contentSize]);
579 CGSize bounds([scroller bounds].size);
582 max.x = size.width - bounds.width;
583 max.y = size.height - bounds.height;
591 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
592 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
594 [scroller setOffset:offset];
600 @implementation WebScriptObject (NSFastEnumeration)
602 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
603 size_t length([self count] - state->state);
606 else if (length > count)
608 for (size_t i(0); i != length; ++i)
609 objects[i] = [self objectAtIndex:state->state++];
610 state->itemsPtr = objects;
611 state->mutationsPtr = (unsigned long *) self;
617 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
618 size_t length([self length] - state->state);
621 else if (length > count)
623 for (size_t i(0); i != length; ++i)
624 objects[i] = [self item:state->state++];
625 state->itemsPtr = objects;
626 state->mutationsPtr = (unsigned long *) self;
630 /* Cydia NSString Additions {{{ */
631 @interface NSString (Cydia)
632 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
633 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
634 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
635 - (NSComparisonResult) compareByPath:(NSString *)other;
636 - (NSString *) stringByCachingURLWithCurrentCDN;
637 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
640 @implementation NSString (Cydia)
642 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
643 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
646 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
647 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
648 memcpy(data, bytes, length);
649 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
652 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
653 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
656 - (NSComparisonResult) compareByPath:(NSString *)other {
657 NSString *prefix = [self commonPrefixWithString:other options:0];
658 size_t length = [prefix length];
660 NSRange lrange = NSMakeRange(length, [self length] - length);
661 NSRange rrange = NSMakeRange(length, [other length] - length);
663 lrange = [self rangeOfString:@"/" options:0 range:lrange];
664 rrange = [other rangeOfString:@"/" options:0 range:rrange];
666 NSComparisonResult value;
668 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
669 value = NSOrderedSame;
670 else if (lrange.location == NSNotFound)
671 value = NSOrderedAscending;
672 else if (rrange.location == NSNotFound)
673 value = NSOrderedDescending;
675 value = NSOrderedSame;
677 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
678 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
679 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
680 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
682 NSComparisonResult result = [lpath compare:rpath];
683 return result == NSOrderedSame ? value : result;
686 - (NSString *) stringByCachingURLWithCurrentCDN {
688 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
689 withString:@"://cache.cydia.saurik.com/"
693 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
694 return [(id)CFURLCreateStringByAddingPercentEscapes(
699 kCFStringEncodingUTF8
706 /* C++ NSString Wrapper Cache {{{ */
707 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
708 return size == 0 ? NULL :
709 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
710 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
713 static _finline CFStringRef CYStringCreate(const char *data) {
714 return CYStringCreate(data, strlen(data));
723 _finline void clear_() {
724 if (cache_ != NULL) {
731 _finline bool empty() const {
735 _finline size_t size() const {
739 _finline char *data() const {
743 _finline void clear() {
748 _finline CYString() :
755 _finline ~CYString() {
759 void operator =(const CYString &rhs) {
763 if (rhs.cache_ == nil)
766 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
769 void copy(apr_pool_t *pool) {
770 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
771 memcpy(temp, data_, size_);
776 void set(apr_pool_t *pool, const char *data, size_t size) {
782 data_ = const_cast<char *>(data);
790 _finline void set(apr_pool_t *pool, const char *data) {
791 set(pool, data, data == NULL ? 0 : strlen(data));
794 _finline void set(apr_pool_t *pool, const std::string &rhs) {
795 set(pool, rhs.data(), rhs.size());
798 bool operator ==(const CYString &rhs) const {
799 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
802 _finline operator CFStringRef() {
804 cache_ = CYStringCreate(data_, size_);
808 _finline operator id() {
809 return (NSString *) static_cast<CFStringRef>(*this);
812 _finline operator const char *() {
813 return reinterpret_cast<const char *>(data_);
817 /* C++ NSString Algorithm Adapters {{{ */
819 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
822 struct NSStringMapHash :
823 std::unary_function<NSString *, size_t>
825 _finline size_t operator ()(NSString *value) const {
826 return CFStringHashNSString((CFStringRef) value);
830 struct NSStringMapLess :
831 std::binary_function<NSString *, NSString *, bool>
833 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
834 return [lhs compare:rhs] == NSOrderedAscending;
838 struct NSStringMapEqual :
839 std::binary_function<NSString *, NSString *, bool>
841 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
842 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
843 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
844 //[lhs isEqualToString:rhs];
849 /* Perl-Compatible RegEx {{{ */
859 Pcre(const char *regex) :
864 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
867 lprintf("%d:%s\n", offset, error);
871 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
872 matches_ = new int[(capture_ + 1) * 3];
880 NSString *operator [](size_t match) {
881 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
884 bool operator ()(NSString *data) {
885 // XXX: length is for characters, not for bytes
886 return operator ()([data UTF8String], [data length]);
889 bool operator ()(const char *data, size_t size) {
891 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
895 /* Mime Addresses {{{ */
896 @interface Address : NSObject {
902 - (NSString *) address;
904 - (void) setAddress:(NSString *)address;
906 + (Address *) addressWithString:(NSString *)string;
907 - (Address *) initWithString:(NSString *)string;
910 @implementation Address
919 - (NSString *) name {
923 - (NSString *) address {
927 - (void) setAddress:(NSString *)address {
929 [address_ autorelease];
933 address_ = [address retain];
936 + (Address *) addressWithString:(NSString *)string {
937 return [[[Address alloc] initWithString:string] autorelease];
940 + (NSArray *) _attributeKeys {
941 return [NSArray arrayWithObjects:@"address", @"name", nil];
944 - (NSArray *) attributeKeys {
945 return [[self class] _attributeKeys];
948 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
949 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
952 - (Address *) initWithString:(NSString *)string {
953 if ((self = [super init]) != nil) {
954 const char *data = [string UTF8String];
955 size_t size = [string length];
957 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
959 if (address_r(data, size)) {
960 name_ = [address_r[1] retain];
961 address_ = [address_r[2] retain];
963 name_ = [string retain];
971 /* CoreGraphics Primitives {{{ */
976 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
977 CGFloat color[] = {red, green, blue, alpha};
978 return CGColorCreate(space, color);
987 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
988 color_(Create_(space, red, green, blue, alpha))
990 Set(space, red, green, blue, alpha);
995 CGColorRelease(color_);
1002 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1004 color_ = Create_(space, red, green, blue, alpha);
1007 operator CGColorRef() {
1013 /* Random Global Variables {{{ */
1014 static const int PulseInterval_ = 50000;
1017 static NSArray *Finishes_;
1019 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1020 #define NotifyConfig_ "/etc/notify.conf"
1022 static bool Queuing_;
1024 static CYColor Blue_;
1025 static CYColor Blueish_;
1026 static CYColor Black_;
1027 static CYColor Off_;
1028 static CYColor White_;
1029 static CYColor Gray_;
1030 static CYColor Green_;
1031 static CYColor Purple_;
1032 static CYColor Purplish_;
1034 static UIColor *InstallingColor_;
1035 static UIColor *RemovingColor_;
1037 static NSString *App_;
1038 static NSString *Home_;
1040 static BOOL Advanced_;
1041 static BOOL Ignored_;
1043 static UIFont *Font12_;
1044 static UIFont *Font12Bold_;
1045 static UIFont *Font14_;
1046 static UIFont *Font18Bold_;
1047 static UIFont *Font22Bold_;
1049 static const char *Machine_ = NULL;
1050 static NSString *System_ = nil;
1051 static NSString *SerialNumber_ = nil;
1052 static NSString *ChipID_ = nil;
1053 static NSString *Token_ = nil;
1054 static NSString *UniqueID_ = nil;
1055 static NSString *PLMN_ = nil;
1056 static NSString *Build_ = nil;
1057 static NSString *Product_ = nil;
1058 static NSString *Safari_ = nil;
1060 static CFLocaleRef Locale_;
1061 static NSArray *Languages_;
1062 static CGColorSpaceRef space_;
1064 static NSDictionary *SectionMap_;
1065 static NSMutableDictionary *Metadata_;
1066 static _transient NSMutableDictionary *Settings_;
1067 static _transient NSString *Role_;
1068 static _transient NSMutableDictionary *Packages_;
1069 static _transient NSMutableDictionary *Sections_;
1070 static _transient NSMutableDictionary *Sources_;
1071 static bool Changed_;
1074 static bool IsWildcat_;
1077 /* Display Helpers {{{ */
1078 inline float Interpolate(float begin, float end, float fraction) {
1079 return (end - begin) * fraction + begin;
1082 /* XXX: localize this! */
1083 NSString *SizeString(double size) {
1084 bool negative = size < 0;
1089 while (size > 1024) {
1094 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1096 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1099 static _finline const char *StripVersion_(const char *version) {
1100 const char *colon(strchr(version, ':'));
1101 return colon == NULL ? version : colon + 1;
1104 NSString *LocalizeSection(NSString *section) {
1105 static Pcre title_r("^(.*?) \\((.*)\\)$");
1106 if (title_r(section)) {
1107 NSString *parent(title_r[1]);
1108 NSString *child(title_r[2]);
1110 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1111 LocalizeSection(parent),
1112 LocalizeSection(child)
1116 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1119 NSString *Simplify(NSString *title) {
1120 const char *data = [title UTF8String];
1121 size_t size = [title length];
1123 static Pcre square_r("^\\[(.*)\\]$");
1124 if (square_r(data, size))
1125 return Simplify(square_r[1]);
1127 static Pcre paren_r("^\\((.*)\\)$");
1128 if (paren_r(data, size))
1129 return Simplify(paren_r[1]);
1131 static Pcre title_r("^(.*?) \\((.*)\\)$");
1132 if (title_r(data, size))
1133 return Simplify(title_r[1]);
1139 NSString *GetLastUpdate() {
1140 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1143 return UCLocalize("NEVER_OR_UNKNOWN");
1145 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1146 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1148 CFRelease(formatter);
1150 return [(NSString *) formatted autorelease];
1153 bool isSectionVisible(NSString *section) {
1154 NSDictionary *metadata([Sections_ objectForKey:section]);
1155 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1156 return hidden == nil || ![hidden boolValue];
1161 /* Delegate Prototypes {{{ */
1165 @interface NSObject (ProgressDelegate)
1168 @protocol ProgressDelegate
1169 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1170 - (void) setProgressTitle:(NSString *)title;
1171 - (void) setProgressPercent:(float)percent;
1172 - (void) startProgress;
1173 - (void) addProgressOutput:(NSString *)output;
1174 - (bool) isCancelling:(size_t)received;
1177 @protocol ConfigurationDelegate
1178 - (void) repairWithSelector:(SEL)selector;
1179 - (void) setConfigurationData:(NSString *)data;
1182 @class PackageController;
1184 @protocol CydiaDelegate
1185 - (void) retainNetworkActivityIndicator;
1186 - (void) releaseNetworkActivityIndicator;
1187 - (void) setPackageController:(PackageController *)view;
1188 - (void) clearPackage:(Package *)package;
1189 - (void) installPackage:(Package *)package;
1190 - (void) installPackages:(NSArray *)packages;
1191 - (void) removePackage:(Package *)package;
1192 - (void) beginUpdate;
1194 - (void) distUpgrade;
1196 - (void) updateData;
1198 - (void) showSettings;
1199 - (UIProgressHUD *) addProgressHUD;
1200 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1201 - (CYViewController *) pageForPackage:(NSString *)name;
1202 - (PackageController *) packageController;
1203 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1206 static id<CydiaDelegate> CydiaApp;
1209 /* Status Delegation {{{ */
1211 public pkgAcquireStatus
1214 _transient NSObject<ProgressDelegate> *delegate_;
1222 void setDelegate(id delegate) {
1223 delegate_ = delegate;
1226 NSObject<ProgressDelegate> *getDelegate() const {
1230 virtual bool MediaChange(std::string media, std::string drive) {
1234 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1237 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1238 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1239 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1242 virtual void Done(pkgAcquire::ItemDesc &item) {
1245 virtual void Fail(pkgAcquire::ItemDesc &item) {
1247 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1248 item.Owner->Status == pkgAcquire::Item::StatDone
1252 std::string &error(item.Owner->ErrorText);
1256 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1257 NSArray *fields([description componentsSeparatedByString:@" "]);
1258 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1260 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1261 withObject:[NSArray arrayWithObjects:
1262 [NSString stringWithUTF8String:error.c_str()],
1269 virtual bool Pulse(pkgAcquire *Owner) {
1270 bool value = pkgAcquireStatus::Pulse(Owner);
1273 double(CurrentBytes + CurrentItems) /
1274 double(TotalBytes + TotalItems)
1277 [delegate_ setProgressPercent:percent];
1278 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1281 virtual void Start() {
1282 [delegate_ startProgress];
1285 virtual void Stop() {
1289 /* Progress Delegation {{{ */
1294 _transient id<ProgressDelegate> delegate_;
1298 virtual void Update() {
1299 /*if (abs(Percent - percent_) > 2)
1300 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1304 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1305 [delegate_ setProgressPercent:(Percent / 100)];*/
1315 void setDelegate(id delegate) {
1316 delegate_ = delegate;
1319 id getDelegate() const {
1323 virtual void Done() {
1325 //[delegate_ setProgressPercent:1];
1330 /* Database Interface {{{ */
1331 typedef std::map< unsigned long, _H<Source> > SourceMap;
1333 @interface Database : NSObject {
1339 pkgCacheFile cache_;
1340 pkgDepCache::Policy *policy_;
1341 pkgRecords *records_;
1342 pkgProblemResolver *resolver_;
1343 pkgAcquire *fetcher_;
1345 SPtr<pkgPackageManager> manager_;
1346 pkgSourceList *list_;
1349 CFMutableArrayRef packages_;
1351 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1360 + (Database *) sharedInstance;
1363 - (void) _readCydia:(NSNumber *)fd;
1364 - (void) _readStatus:(NSNumber *)fd;
1365 - (void) _readOutput:(NSNumber *)fd;
1369 - (Package *) packageWithName:(NSString *)name;
1371 - (pkgCacheFile &) cache;
1372 - (pkgDepCache::Policy *) policy;
1373 - (pkgRecords *) records;
1374 - (pkgProblemResolver *) resolver;
1375 - (pkgAcquire &) fetcher;
1376 - (pkgSourceList &) list;
1377 - (NSArray *) packages;
1378 - (NSArray *) sources;
1379 - (void) reloadData;
1387 - (void) updateWithStatus:(Status &)status;
1389 - (void) setDelegate:(id)delegate;
1390 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1393 /* Delegate Helpers {{{ */
1394 @implementation NSObject (ProgressDelegate)
1396 - (void) _setProgressErrorPackage:(NSArray *)args {
1397 [self performSelector:@selector(setProgressError:forPackage:)
1398 withObject:[args objectAtIndex:0]
1399 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1403 - (void) _setProgressErrorTitle:(NSArray *)args {
1404 [self performSelector:@selector(setProgressError:withTitle:)
1405 withObject:[args objectAtIndex:0]
1406 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1410 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1411 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1412 withObject:[NSArray arrayWithObjects:error, title, nil]
1417 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1418 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1420 [self performSelector:@selector(setProgressError:withTitle:)
1422 withObject:(package == nil ? id : [package name])
1429 // Cytore Definitions {{{
1430 struct PackageValue :
1433 Cytore::Offset<PackageValue> next_;
1435 uint32_t index_ : 23;
1436 uint32_t subscribed_ : 1;
1453 Cytore::Offset<PackageValue> packages_[1 << 16];
1456 static Cytore::File<MetaValue> MetaFile_;
1458 // Cytore Helper Functions {{{
1459 static PackageValue *PackageFind(const char *name, size_t length) {
1460 SplitHash nhash = { hashlittle(name, length) };
1462 PackageValue *metadata;
1464 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1465 offset: if (offset->IsNull()) {
1466 *offset = MetaFile_.New<PackageValue>(length + 1);
1467 metadata = &MetaFile_.Get(*offset);
1469 memcpy(metadata->name_, name, length + 1);
1470 metadata->nhash_ = nhash.u16[1];
1472 metadata = &MetaFile_.Get(*offset);
1474 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1475 offset = &metadata->next_;
1483 static void PackageImport(const void *key, const void *value, void *context) {
1485 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1486 NSLog(@"failed to import package %@", key);
1490 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1491 NSDictionary *package((NSDictionary *) value);
1493 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1494 if ([subscribed boolValue] && !metadata->subscribed_)
1495 metadata->subscribed_ = true;
1497 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1498 time_t time([date timeIntervalSince1970]);
1499 if (metadata->first_ > time || metadata->first_ == 0)
1500 metadata->first_ = time;
1503 NSDate *date([package objectForKey:@"LastSeen"]);
1504 NSString *version([package objectForKey:@"LastVersion"]);
1506 if (date != nil && version != nil) {
1507 time_t time([date timeIntervalSince1970]);
1508 if (metadata->last_ < time || metadata->last_ == 0)
1509 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1510 size_t length(strlen(buffer));
1511 uint16_t vhash(hashlittle(buffer, length));
1513 size_t capped(std::min<size_t>(8, length));
1514 char *latest(buffer + length - capped);
1516 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1517 metadata->vhash_ = vhash;
1519 metadata->last_ = time;
1525 /* Source Class {{{ */
1526 @interface Source : NSObject {
1527 CYString depiction_;
1528 CYString description_;
1534 CYString distribution_;
1539 NSString *authority_;
1541 CYString defaultIcon_;
1543 NSDictionary *record_;
1547 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1549 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1551 - (NSString *) depictionForPackage:(NSString *)package;
1552 - (NSString *) supportForPackage:(NSString *)package;
1554 - (NSDictionary *) record;
1558 - (NSString *) distribution;
1559 - (NSString *) type;
1561 - (NSString *) host;
1563 - (NSString *) name;
1564 - (NSString *) description;
1565 - (NSString *) label;
1566 - (NSString *) origin;
1567 - (NSString *) version;
1569 - (NSString *) defaultIcon;
1573 @implementation Source
1577 distribution_.clear();
1580 description_.clear();
1586 defaultIcon_.clear();
1588 if (record_ != nil) {
1598 if (authority_ != nil) {
1599 [authority_ release];
1605 // XXX: this is a very inefficient way to call these deconstructors
1610 + (NSArray *) _attributeKeys {
1611 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1614 - (NSArray *) attributeKeys {
1615 return [[self class] _attributeKeys];
1618 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1619 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1622 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1625 trusted_ = index->IsTrusted();
1627 uri_.set(pool, index->GetURI());
1628 distribution_.set(pool, index->GetDist());
1629 type_.set(pool, index->GetType());
1631 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1632 if (dindex != NULL) {
1634 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1637 pkgTagFile tags(&fd);
1639 pkgTagSection section;
1646 {"default-icon", &defaultIcon_},
1647 {"depiction", &depiction_},
1648 {"description", &description_},
1650 {"origin", &origin_},
1651 {"support", &support_},
1652 {"version", &version_},
1655 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1656 const char *start, *end;
1658 if (section.Find(names[i].name_, start, end)) {
1659 CYString &value(*names[i].value_);
1660 value.set(pool, start, end - start);
1666 record_ = [Sources_ objectForKey:[self key]];
1668 record_ = [record_ retain];
1670 NSURL *url([NSURL URLWithString:uri_]);
1674 host_ = [[host_ lowercaseString] retain];
1679 authority_ = [url path];
1681 if (authority_ != nil)
1682 authority_ = [authority_ retain];
1685 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1686 if ((self = [super init]) != nil) {
1687 [self setMetaIndex:index inPool:pool];
1691 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1692 NSDictionary *lhr = [self record];
1693 NSDictionary *rhr = [source record];
1696 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1698 NSString *lhs = [self name];
1699 NSString *rhs = [source name];
1701 if ([lhs length] != 0 && [rhs length] != 0) {
1702 unichar lhc = [lhs characterAtIndex:0];
1703 unichar rhc = [rhs characterAtIndex:0];
1705 if (isalpha(lhc) && !isalpha(rhc))
1706 return NSOrderedAscending;
1707 else if (!isalpha(lhc) && isalpha(rhc))
1708 return NSOrderedDescending;
1711 return [lhs compare:rhs options:LaxCompareOptions_];
1714 - (NSString *) depictionForPackage:(NSString *)package {
1715 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1718 - (NSString *) supportForPackage:(NSString *)package {
1719 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1722 - (NSDictionary *) record {
1730 - (NSString *) uri {
1734 - (NSString *) distribution {
1735 return distribution_;
1738 - (NSString *) type {
1742 - (NSString *) key {
1743 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1746 - (NSString *) host {
1750 - (NSString *) name {
1751 return origin_.empty() ? authority_ : origin_;
1754 - (NSString *) description {
1755 return description_;
1758 - (NSString *) label {
1759 return label_.empty() ? authority_ : label_;
1762 - (NSString *) origin {
1766 - (NSString *) version {
1770 - (NSString *) defaultIcon {
1771 return defaultIcon_;
1776 /* Relationship Class {{{ */
1777 @interface Relationship : NSObject {
1782 - (NSString *) type;
1784 - (NSString *) name;
1788 @implementation Relationship
1796 - (NSString *) type {
1804 - (NSString *) name {
1811 /* Package Class {{{ */
1812 struct ParsedPackage {
1817 CYString depiction_;
1827 @interface Package : NSObject {
1829 uint32_t essential_ : 1;
1830 uint32_t obsolete_ : 1;
1831 uint32_t ignored_ : 1;
1835 _transient Database *database_;
1837 pkgCache::VerIterator version_;
1838 pkgCache::PkgIterator iterator_;
1839 pkgCache::VerFileIterator file_;
1845 CYString installed_;
1848 _transient NSString *section$_;
1852 PackageValue *metadata_;
1853 ParsedPackage *parsed_;
1855 NSMutableArray *tags_;
1859 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1860 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1862 - (pkgCache::PkgIterator) iterator;
1865 - (NSString *) section;
1866 - (NSString *) simpleSection;
1868 - (NSString *) longSection;
1869 - (NSString *) shortSection;
1873 - (Address *) maintainer;
1875 - (NSString *) longDescription;
1876 - (NSString *) shortDescription;
1879 - (PackageValue *) metadata;
1882 - (bool) subscribed;
1883 - (bool) setSubscribed:(bool)subscribed;
1887 - (NSString *) latest;
1888 - (NSString *) installed;
1889 - (BOOL) uninstalled;
1892 - (BOOL) upgradableAndEssential:(BOOL)essential;
1895 - (BOOL) unfiltered;
1899 - (BOOL) halfConfigured;
1900 - (BOOL) halfInstalled;
1902 - (NSString *) mode;
1905 - (NSString *) name;
1907 - (NSString *) homepage;
1908 - (NSString *) depiction;
1909 - (Address *) author;
1911 - (NSString *) support;
1913 - (NSArray *) files;
1914 - (NSArray *) warnings;
1915 - (NSArray *) applications;
1917 - (Source *) source;
1918 - (NSString *) role;
1920 - (BOOL) matches:(NSString *)text;
1922 - (bool) hasSupportingRole;
1923 - (BOOL) hasTag:(NSString *)tag;
1924 - (NSString *) primaryPurpose;
1925 - (NSArray *) purposes;
1926 - (bool) isCommercial;
1928 - (void) setIndex:(size_t)index;
1930 - (CYString &) cyname;
1932 - (uint32_t) compareBySection:(NSArray *)sections;
1937 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1938 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1939 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1940 - (bool) isVisibleInSection:(NSString *)section;
1941 - (bool) isVisibleInSource:(Source *)source;
1945 uint32_t PackageChangesRadix(Package *self, void *) {
1950 uint32_t timestamp : 30;
1951 uint32_t ignored : 1;
1952 uint32_t upgradable : 1;
1956 bool upgradable([self upgradableAndEssential:YES]);
1957 value.bits.upgradable = upgradable ? 1 : 0;
1960 value.bits.timestamp = 0;
1961 value.bits.ignored = [self ignored] ? 0 : 1;
1962 value.bits.upgradable = 1;
1964 value.bits.timestamp = [self seen] >> 2;
1965 value.bits.ignored = 0;
1966 value.bits.upgradable = 0;
1969 return _not(uint32_t) - value.key;
1972 uint32_t PackagePrefixRadix(Package *self, void *context) {
1973 size_t offset(reinterpret_cast<size_t>(context));
1974 CYString &name([self cyname]);
1976 size_t size(name.size());
1979 char *text(name.data());
1982 if (!isdigit(text[0]))
1986 while (size != digits && isdigit(text[digits]))
1994 if (offset == 0 && zeros != 0) {
1995 memset(data, '0', zeros);
1996 memcpy(data + zeros, text, 4 - zeros);
1998 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1999 if (size <= offset - zeros)
2002 text += offset - zeros;
2003 size -= offset - zeros;
2006 memcpy(data, text, 4);
2008 memcpy(data, text, size);
2009 memset(data + size, 0, 4 - size);
2012 for (size_t i(0); i != 4; ++i)
2013 if (isalpha(data[i]))
2021 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2023 /* XXX: ntohl may be more honest */
2024 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2027 CYString &(*PackageName)(Package *self, SEL sel);
2029 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2030 _profile(PackageNameCompare)
2031 CYString &lhi(PackageName(lhs, @selector(cyname)));
2032 CYString &rhi(PackageName(rhs, @selector(cyname)));
2033 CFStringRef lhn(lhi), rhn(rhi);
2036 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2037 else if (rhn == NULL)
2038 return NSOrderedDescending;
2040 _profile(PackageNameCompare$NumbersLast)
2041 if (!lhi.empty() && !rhi.empty()) {
2042 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2043 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2044 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2045 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2046 return lha ? NSOrderedAscending : NSOrderedDescending;
2050 CFIndex length = CFStringGetLength(lhn);
2052 _profile(PackageNameCompare$Compare)
2053 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2058 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2059 return PackageNameCompare(*lhs, *rhs, context);
2062 struct PackageNameOrdering :
2063 std::binary_function<Package *, Package *, bool>
2065 _finline bool operator ()(Package *lhs, Package *rhs) const {
2066 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2070 @implementation Package
2072 - (NSString *) description {
2073 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2077 if (parsed_ != NULL)
2091 + (NSString *) webScriptNameForSelector:(SEL)selector {
2092 if (selector == @selector(hasTag:))
2098 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2099 return [self webScriptNameForSelector:selector] == nil;
2102 + (NSArray *) _attributeKeys {
2103 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];
2106 - (NSArray *) attributeKeys {
2107 return [[self class] _attributeKeys];
2110 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2111 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2115 if (parsed_ != NULL)
2117 @synchronized (database_) {
2118 if ([database_ era] != era_ || file_.end())
2121 ParsedPackage *parsed(new ParsedPackage);
2124 _profile(Package$parse)
2125 pkgRecords::Parser *parser;
2127 _profile(Package$parse$Lookup)
2128 parser = &[database_ records]->Lookup(file_);
2133 _profile(Package$parse$Find)
2138 {"icon", &parsed->icon_},
2139 {"depiction", &parsed->depiction_},
2140 {"homepage", &parsed->homepage_},
2141 {"website", &website},
2142 {"bugs", &parsed->bugs_},
2143 {"support", &parsed->support_},
2144 {"sponsor", &parsed->sponsor_},
2145 {"author", &parsed->author_},
2148 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2149 const char *start, *end;
2151 if (parser->Find(names[i].name_, start, end)) {
2152 CYString &value(*names[i].value_);
2153 _profile(Package$parse$Value)
2154 value.set(pool_, start, end - start);
2160 _profile(Package$parse$Tagline)
2161 const char *start, *end;
2162 if (parser->ShortDesc(start, end)) {
2163 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2166 while (stop != start && stop[-1] == '\r')
2168 parsed->tagline_.set(pool_, start, stop - start);
2172 _profile(Package$parse$Retain)
2173 if (parsed->homepage_.empty())
2174 parsed->homepage_ = website;
2175 if (parsed->homepage_ == parsed->depiction_)
2176 parsed->homepage_.clear();
2181 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2182 if ((self = [super init]) != nil) {
2183 _profile(Package$initWithVersion)
2186 database_ = database;
2187 era_ = [database era];
2191 pkgCache::PkgIterator iterator(version.ParentPkg());
2192 iterator_ = iterator;
2194 _profile(Package$initWithVersion$Version)
2195 if (!version_.end())
2196 file_ = version_.FileList();
2198 pkgCache &cache([database_ cache]);
2199 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2203 _profile(Package$initWithVersion$Cache)
2204 name_.set(NULL, iterator.Display());
2206 latest_.set(NULL, StripVersion_(version_.VerStr()));
2208 pkgCache::VerIterator current(iterator.CurrentVer());
2210 installed_.set(NULL, StripVersion_(current.VerStr()));
2213 _profile(Package$initWithVersion$Tags)
2214 pkgCache::TagIterator tag(iterator.TagList());
2216 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2218 const char *name(tag.Name());
2219 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2221 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2222 role_ = (NSString *) CYStringCreate(name + 6);
2224 if (strncmp(name, "cydia::", 7) == 0) {
2225 if (strcmp(name + 7, "essential") == 0)
2227 else if (strcmp(name + 7, "obsolete") == 0)
2232 } while (!tag.end());
2236 _profile(Package$initWithVersion$Metadata)
2237 const char *mixed(iterator.Name());
2238 size_t size(strlen(mixed));
2239 char lower[size + 1];
2241 for (size_t i(0); i != size; ++i)
2242 lower[i] = mixed[i] | 0x20;
2245 PackageValue *metadata(PackageFind(lower, size));
2246 metadata_ = metadata;
2248 id_.set(NULL, metadata->name_, size);
2250 const char *latest(version_.VerStr());
2251 size_t length(strlen(latest));
2253 uint16_t vhash(hashlittle(latest, length));
2255 size_t capped(std::min<size_t>(8, length));
2256 latest = latest + length - capped;
2258 if (metadata->first_ == 0)
2259 metadata->first_ = now_;
2261 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2262 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2263 metadata->vhash_ = vhash;
2264 metadata->last_ = now_;
2265 } else if (metadata->last_ == 0)
2266 metadata->last_ = metadata->first_;
2269 _profile(Package$initWithVersion$Section)
2270 section_.set(NULL, iterator.Section());
2273 _profile(Package$initWithVersion$Flags)
2274 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2275 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2280 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2281 pkgCache::VerIterator version;
2283 _profile(Package$packageWithIterator$GetCandidateVer)
2284 version = [database policy]->GetCandidateVer(iterator);
2292 _profile(Package$packageWithIterator$Allocate)
2293 package = [Package allocWithZone:zone];
2296 _profile(Package$packageWithIterator$Initialize)
2298 initWithVersion:version
2305 _profile(Package$packageWithIterator$Autorelease)
2306 package = [package autorelease];
2312 - (pkgCache::PkgIterator) iterator {
2316 - (NSString *) section {
2317 if (section$_ == nil) {
2318 if (section_.empty())
2321 _profile(Package$section)
2322 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2323 NSString *name(section_);
2324 section$_ = [SectionMap_ objectForKey:name] ?: name;
2329 - (NSString *) simpleSection {
2330 if (NSString *section = [self section])
2331 return Simplify(section);
2336 - (NSString *) longSection {
2337 return LocalizeSection([self section]);
2340 - (NSString *) shortSection {
2341 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2344 - (NSString *) uri {
2347 pkgIndexFile *index;
2348 pkgCache::PkgFileIterator file(file_.File());
2349 if (![database_ list].FindIndex(file, index))
2351 return [NSString stringWithUTF8String:iterator_->Path];
2352 //return [NSString stringWithUTF8String:file.Site()];
2353 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2357 - (Address *) maintainer {
2358 @synchronized (database_) {
2359 if ([database_ era] != era_ || file_.end())
2362 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2363 const std::string &maintainer(parser->Maintainer());
2364 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2368 @synchronized (database_) {
2369 if ([database_ era] != era_ || version_.end())
2372 return version_->InstalledSize;
2375 - (NSString *) longDescription {
2376 @synchronized (database_) {
2377 if ([database_ era] != era_ || file_.end())
2380 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2381 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2383 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2384 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2385 if ([lines count] < 2)
2388 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2389 for (size_t i(1), e([lines count]); i != e; ++i) {
2390 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2391 [trimmed addObject:trim];
2394 return [trimmed componentsJoinedByString:@"\n"];
2397 - (NSString *) shortDescription {
2398 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2402 _profile(Package$index)
2403 CFStringRef name((CFStringRef) [self name]);
2404 if (CFStringGetLength(name) == 0)
2406 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2407 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2409 return toupper(character);
2413 - (PackageValue *) metadata {
2418 PackageValue *metadata([self metadata]);
2419 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2422 - (bool) subscribed {
2423 return [self metadata]->subscribed_;
2426 - (bool) setSubscribed:(bool)subscribed {
2427 PackageValue *metadata([self metadata]);
2428 if (metadata->subscribed_ == subscribed)
2430 metadata->subscribed_ = subscribed;
2438 - (NSString *) latest {
2442 - (NSString *) installed {
2446 - (BOOL) uninstalled {
2447 return installed_.empty();
2451 return !version_.end();
2454 - (BOOL) upgradableAndEssential:(BOOL)essential {
2455 _profile(Package$upgradableAndEssential)
2456 pkgCache::VerIterator current(iterator_.CurrentVer());
2458 return essential && essential_;
2460 return !version_.end() && version_ != current;
2464 - (BOOL) essential {
2469 return [database_ cache][iterator_].InstBroken();
2472 - (BOOL) unfiltered {
2473 _profile(Package$unfiltered$obsolete)
2478 _profile(Package$unfiltered$hasSupportingRole)
2479 if (![self hasSupportingRole])
2487 if (![self unfiltered])
2490 NSString *section([self section]);
2492 _profile(Package$visible$isSectionVisible)
2493 if (section != nil && !isSectionVisible(section))
2501 unsigned char current(iterator_->CurrentState);
2502 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2505 - (BOOL) halfConfigured {
2506 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2509 - (BOOL) halfInstalled {
2510 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2514 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2515 return state.Mode != pkgDepCache::ModeKeep;
2518 - (NSString *) mode {
2519 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2521 switch (state.Mode) {
2522 case pkgDepCache::ModeDelete:
2523 if ((state.iFlags & pkgDepCache::Purge) != 0)
2527 case pkgDepCache::ModeKeep:
2528 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2529 return @"REINSTALL";
2530 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2534 case pkgDepCache::ModeInstall:
2535 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2536 return @"REINSTALL";
2537 else*/ switch (state.Status) {
2539 return @"DOWNGRADE";
2545 return @"NEW_INSTALL";
2556 - (NSString *) name {
2557 return name_.empty() ? id_ : name_;
2560 - (UIImage *) icon {
2561 NSString *section = [self simpleSection];
2564 if (parsed_ != NULL)
2565 if (NSString *href = parsed_->icon_)
2566 if ([href hasPrefix:@"file:///"])
2567 // XXX: correct escaping
2568 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2569 if (icon == nil) if (section != nil)
2570 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2571 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2572 if ([dicon hasPrefix:@"file:///"])
2573 // XXX: correct escaping
2574 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2576 icon = [UIImage applicationImageNamed:@"unknown.png"];
2580 - (NSString *) homepage {
2581 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2584 - (NSString *) depiction {
2585 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2588 - (Address *) sponsor {
2589 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2592 - (Address *) author {
2593 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2596 - (NSString *) support {
2597 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2600 - (NSArray *) files {
2601 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2602 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2605 fin.open([path UTF8String]);
2610 while (std::getline(fin, line))
2611 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2616 - (NSArray *) warnings {
2617 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2618 const char *name(iterator_.Name());
2620 size_t length(strlen(name));
2621 if (length < 2) invalid:
2622 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2623 else for (size_t i(0); i != length; ++i)
2625 /* XXX: technically this is not allowed */
2626 (name[i] < 'A' || name[i] > 'Z') &&
2627 (name[i] < 'a' || name[i] > 'z') &&
2628 (name[i] < '0' || name[i] > '9') &&
2629 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2632 if (strcmp(name, "cydia") != 0) {
2635 bool _private = false;
2638 bool repository = [[self section] isEqualToString:@"Repositories"];
2640 if (NSArray *files = [self files])
2641 for (NSString *file in files)
2642 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2644 else if (!user && [file isEqualToString:@"/User"])
2646 else if (!_private && [file isEqualToString:@"/private"])
2648 else if (!stash && [file isEqualToString:@"/var/stash"])
2651 /* XXX: this is not sensitive enough. only some folders are valid. */
2652 if (cydia && !repository)
2653 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2655 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2657 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2659 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2662 return [warnings count] == 0 ? nil : warnings;
2665 - (NSArray *) applications {
2666 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2668 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2670 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2671 if (NSArray *files = [self files])
2672 for (NSString *file in files)
2673 if (application_r(file)) {
2674 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2675 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2676 if ([id isEqualToString:me])
2679 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2681 display = application_r[1];
2683 NSString *bundle([file stringByDeletingLastPathComponent]);
2684 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2685 if (icon == nil || [icon length] == 0)
2687 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2689 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2690 [applications addObject:application];
2692 [application addObject:id];
2693 [application addObject:display];
2694 [application addObject:url];
2697 return [applications count] == 0 ? nil : applications;
2700 - (Source *) source {
2701 if (source_ == nil) {
2702 @synchronized (database_) {
2703 if ([database_ era] != era_ || file_.end())
2704 source_ = (Source *) [NSNull null];
2706 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2710 return source_ == (Source *) [NSNull null] ? nil : source_;
2713 - (NSString *) role {
2717 - (BOOL) matches:(NSString *)text {
2723 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2724 if (range.location != NSNotFound)
2727 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2728 if (range.location != NSNotFound)
2731 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2732 if (range.location != NSNotFound)
2738 - (bool) hasSupportingRole {
2741 if ([role_ isEqualToString:@"enduser"])
2743 if ([Role_ isEqualToString:@"User"])
2745 if ([role_ isEqualToString:@"hacker"])
2747 if ([Role_ isEqualToString:@"Hacker"])
2749 if ([role_ isEqualToString:@"developer"])
2751 if ([Role_ isEqualToString:@"Developer"])
2756 - (BOOL) hasTag:(NSString *)tag {
2757 return tags_ == nil ? NO : [tags_ containsObject:tag];
2760 - (NSString *) primaryPurpose {
2761 for (NSString *tag in tags_)
2762 if ([tag hasPrefix:@"purpose::"])
2763 return [tag substringFromIndex:9];
2767 - (NSArray *) purposes {
2768 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2769 for (NSString *tag in tags_)
2770 if ([tag hasPrefix:@"purpose::"])
2771 [purposes addObject:[tag substringFromIndex:9]];
2772 return [purposes count] == 0 ? nil : purposes;
2775 - (bool) isCommercial {
2776 return [self hasTag:@"cydia::commercial"];
2779 - (void) setIndex:(size_t)index {
2780 if (metadata_->index_ != index)
2781 metadata_->index_ = index;
2784 - (CYString &) cyname {
2785 return name_.empty() ? id_ : name_;
2788 - (uint32_t) compareBySection:(NSArray *)sections {
2789 NSString *section([self section]);
2790 for (size_t i(0), e([sections count]); i != e; ++i) {
2791 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2795 return _not(uint32_t);
2799 @synchronized (database_) {
2800 pkgProblemResolver *resolver = [database_ resolver];
2801 resolver->Clear(iterator_);
2803 pkgCacheFile &cache([database_ cache]);
2804 cache->SetReInstall(iterator_, false);
2805 cache->MarkKeep(iterator_, false);
2809 @synchronized (database_) {
2810 pkgProblemResolver *resolver = [database_ resolver];
2811 resolver->Clear(iterator_);
2812 resolver->Protect(iterator_);
2814 pkgCacheFile &cache([database_ cache]);
2815 cache->SetReInstall(iterator_, false);
2816 cache->MarkInstall(iterator_, false);
2818 pkgDepCache::StateCache &state((*cache)[iterator_]);
2819 if (!state.Install())
2820 cache->SetReInstall(iterator_, true);
2824 @synchronized (database_) {
2825 pkgProblemResolver *resolver = [database_ resolver];
2826 resolver->Clear(iterator_);
2827 resolver->Remove(iterator_);
2828 resolver->Protect(iterator_);
2830 pkgCacheFile &cache([database_ cache]);
2831 cache->SetReInstall(iterator_, false);
2832 cache->MarkDelete(iterator_, true);
2835 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2836 _profile(Package$isUnfilteredAndSearchedForBy)
2839 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2840 value &= [self unfiltered];
2843 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2844 value &= [self matches:search];
2851 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2852 if ([search length] == 0)
2855 _profile(Package$isUnfilteredAndSelectedForBy)
2858 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2859 value &= [self unfiltered];
2862 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2863 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2870 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2871 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2874 - (bool) isVisibleInSection:(NSString *)name {
2875 NSString *section([self section]);
2879 section == nil && [name length] == 0 ||
2880 [name isEqualToString:section]
2881 ) && [self visible];
2884 - (bool) isVisibleInSource:(Source *)source {
2885 return [self source] == source && [self visible];
2890 /* Section Class {{{ */
2891 @interface Section : NSObject {
2896 NSString *localized_;
2899 - (NSComparisonResult) compareByLocalized:(Section *)section;
2900 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2901 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2902 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2903 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2904 - (NSString *) name;
2911 - (void) addToCount;
2913 - (void) setCount:(size_t)count;
2914 - (NSString *) localized;
2918 @implementation Section
2922 if (localized_ != nil)
2923 [localized_ release];
2927 - (NSComparisonResult) compareByLocalized:(Section *)section {
2928 NSString *lhs(localized_);
2929 NSString *rhs([section localized]);
2931 /*if ([lhs length] != 0 && [rhs length] != 0) {
2932 unichar lhc = [lhs characterAtIndex:0];
2933 unichar rhc = [rhs characterAtIndex:0];
2935 if (isalpha(lhc) && !isalpha(rhc))
2936 return NSOrderedAscending;
2937 else if (!isalpha(lhc) && isalpha(rhc))
2938 return NSOrderedDescending;
2941 return [lhs compare:rhs options:LaxCompareOptions_];
2944 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2945 if ((self = [self initWithName:name localize:NO]) != nil) {
2946 if (localized != nil)
2947 localized_ = [localized retain];
2951 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2952 return [self initWithName:name row:0 localize:localize];
2955 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2956 if ((self = [super init]) != nil) {
2957 name_ = [name retain];
2961 localized_ = [LocalizeSection(name_) retain];
2965 /* XXX: localize the index thingees */
2966 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2967 if ((self = [super init]) != nil) {
2968 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2974 - (NSString *) name {
2994 - (void) addToCount {
2998 - (void) setCount:(size_t)count {
3002 - (NSString *) localized {
3009 static NSString *Colon_;
3010 static NSString *Elision_;
3011 static NSString *Error_;
3012 static NSString *Warning_;
3014 /* Database Implementation {{{ */
3015 @implementation Database
3017 + (Database *) sharedInstance {
3018 static Database *instance;
3019 if (instance == nil)
3020 instance = [[Database alloc] init];
3028 - (void) releasePackages {
3029 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3030 CFArrayRemoveAllValues(packages_);
3034 // XXX: actually implement this thing
3036 [self releasePackages];
3037 apr_pool_destroy(pool_);
3038 NSRecycleZone(zone_);
3042 - (void) _readCydia:(NSNumber *)fd { _pooled
3043 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3044 std::istream is(&ib);
3047 static Pcre finish_r("^finish:([^:]*)$");
3049 while (std::getline(is, line)) {
3050 const char *data(line.c_str());
3051 size_t size = line.size();
3052 lprintf("C:%s\n", data);
3054 if (finish_r(data, size)) {
3055 NSString *finish = finish_r[1];
3056 int index = [Finishes_ indexOfObject:finish];
3057 if (index != INT_MAX && index > Finish_)
3065 - (void) _readStatus:(NSNumber *)fd { _pooled
3066 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3067 std::istream is(&ib);
3070 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3071 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3073 while (std::getline(is, line)) {
3074 const char *data(line.c_str());
3075 size_t size(line.size());
3076 lprintf("S:%s\n", data);
3078 if (conffile_r(data, size)) {
3079 [delegate_ setConfigurationData:conffile_r[1]];
3080 } else if (strncmp(data, "status: ", 8) == 0) {
3081 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3082 [delegate_ setProgressTitle:string];
3083 } else if (pmstatus_r(data, size)) {
3084 std::string type([pmstatus_r[1] UTF8String]);
3085 NSString *id = pmstatus_r[2];
3087 float percent([pmstatus_r[3] floatValue]);
3088 [delegate_ setProgressPercent:(percent / 100)];
3090 NSString *string = pmstatus_r[4];
3092 if (type == "pmerror")
3093 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3094 withObject:[NSArray arrayWithObjects:string, id, nil]
3097 else if (type == "pmstatus") {
3098 [delegate_ setProgressTitle:string];
3099 } else if (type == "pmconffile")
3100 [delegate_ setConfigurationData:string];
3102 lprintf("E:unknown pmstatus\n");
3104 lprintf("E:unknown status\n");
3110 - (void) _readOutput:(NSNumber *)fd { _pooled
3111 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3112 std::istream is(&ib);
3115 while (std::getline(is, line)) {
3116 lprintf("O:%s\n", line.c_str());
3117 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3127 - (Package *) packageWithName:(NSString *)name {
3128 @synchronized (self) {
3129 if (static_cast<pkgDepCache *>(cache_) == NULL)
3131 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3132 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3136 if ((self = [super init]) != nil) {
3143 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3144 apr_pool_create(&pool_, NULL);
3146 size_t capacity(MetaFile_->active_);
3152 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3156 _assert(pipe(fds) != -1);
3159 _config->Set("APT::Keep-Fds::", cydiafd_);
3160 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3163 detachNewThreadSelector:@selector(_readCydia:)
3165 withObject:[NSNumber numberWithInt:fds[0]]
3168 _assert(pipe(fds) != -1);
3172 detachNewThreadSelector:@selector(_readStatus:)
3174 withObject:[NSNumber numberWithInt:fds[0]]
3177 _assert(pipe(fds) != -1);
3178 _assert(dup2(fds[0], 0) != -1);
3179 _assert(close(fds[0]) != -1);
3181 input_ = fdopen(fds[1], "a");
3183 _assert(pipe(fds) != -1);
3184 _assert(dup2(fds[1], 1) != -1);
3185 _assert(close(fds[1]) != -1);
3188 detachNewThreadSelector:@selector(_readOutput:)
3190 withObject:[NSNumber numberWithInt:fds[0]]
3195 - (pkgCacheFile &) cache {
3199 - (pkgDepCache::Policy *) policy {
3203 - (pkgRecords *) records {
3207 - (pkgProblemResolver *) resolver {
3211 - (pkgAcquire &) fetcher {
3215 - (pkgSourceList &) list {
3219 - (NSArray *) packages {
3220 return (NSArray *) packages_;
3223 - (NSArray *) sources {
3224 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3225 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3226 [sources addObject:i->second];
3230 - (NSArray *) issues {
3231 if (cache_->BrokenCount() == 0)
3234 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3236 for (Package *package in [self packages]) {
3237 if (![package broken])
3239 pkgCache::PkgIterator pkg([package iterator]);
3241 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3242 [entry addObject:[package name]];
3243 [issues addObject:entry];
3245 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3249 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3250 pkgCache::DepIterator start;
3251 pkgCache::DepIterator end;
3252 dep.GlobOr(start, end); // ++dep
3254 if (!cache_->IsImportantDep(end))
3256 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3259 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3260 [entry addObject:failure];
3261 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3263 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3264 if (Package *package = [self packageWithName:name])
3265 name = [package name];
3266 [failure addObject:name];
3268 pkgCache::PkgIterator target(start.TargetPkg());
3269 if (target->ProvidesList != 0)
3270 [failure addObject:@"?"];
3272 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3274 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3275 else if (!cache_[target].CandidateVerIter(cache_).end())
3276 [failure addObject:@"-"];
3277 else if (target->ProvidesList == 0)
3278 [failure addObject:@"!"];
3280 [failure addObject:@"%"];
3284 if (start.TargetVer() != 0)
3285 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3296 - (bool) popErrorWithTitle:(NSString *)title {
3298 std::string message;
3300 while (!_error->empty()) {
3302 bool warning(!_error->PopMessage(error));
3306 size_t size(error.size());
3307 if (size == 0 || error[size - 1] != '\n')
3309 error.resize(size - 1);
3311 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3313 if (!message.empty())
3318 if (fatal && !message.empty())
3319 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3324 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3325 return [self popErrorWithTitle:title] || !success;
3328 - (void) reloadData { CYPoolStart() {
3329 @synchronized (self) {
3332 [self releasePackages];
3353 apr_pool_clear(pool_);
3355 NSRecycleZone(zone_);
3356 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3358 int chk(creat("/tmp/cydia.chk", 0644));
3362 NSString *title(UCLocalize("DATABASE"));
3365 if (!cache_.Open(progress_, true)) { pop:
3367 bool warning(!_error->PopMessage(error));
3368 lprintf("cache_.Open():[%s]\n", error.c_str());
3370 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3371 [delegate_ repairWithSelector:@selector(configure)];
3372 else if (error == "The package lists or status file could not be parsed or opened.")
3373 [delegate_ repairWithSelector:@selector(update)];
3374 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3375 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3376 // else if (error == "The list of sources could not be read.")
3378 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3387 unlink("/tmp/cydia.chk");
3389 now_ = [[NSDate date] timeIntervalSince1970];
3391 policy_ = new pkgDepCache::Policy();
3392 records_ = new pkgRecords(cache_);
3393 resolver_ = new pkgProblemResolver(cache_);
3394 fetcher_ = new pkgAcquire(&status_);
3397 list_ = new pkgSourceList();
3398 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3401 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3402 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3406 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3409 if (cache_->BrokenCount() != 0) {
3410 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3413 if (cache_->BrokenCount() != 0) {
3414 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3418 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3422 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3423 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3424 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3425 // XXX: this could be more intelligent
3426 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3427 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3429 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3434 /*std::vector<Package *> packages;
3435 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3436 [packages_ release];
3441 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3442 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3443 //packages.push_back(package);
3444 CFArrayAppendValue(packages_, [package retain]);
3448 /*if (packages.empty())
3449 packages_ = [[NSArray alloc] init];
3451 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3454 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3455 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3456 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3464 /*if (!packages.empty())
3465 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3466 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3468 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3470 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3472 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3476 size_t count(CFArrayGetCount(packages_));
3477 MetaFile_->active_ = count;
3479 for (size_t index(0); index != count; ++index)
3480 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3484 } } CYPoolEnd() _trace(); }
3487 @synchronized (self) {
3489 resolver_ = new pkgProblemResolver(cache_);
3491 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3492 if (!cache_[iterator].Keep()) {
3493 cache_->MarkKeep(iterator, false);
3494 cache_->SetReInstall(iterator, false);
3499 - (void) configure {
3500 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3502 system([dpkg UTF8String]);
3507 // XXX: I don't remember this condition
3512 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3514 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3516 if ([self popErrorWithTitle:title])
3520 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3523 public pkgArchiveCleaner
3526 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3531 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3538 fetcher_->Shutdown();
3540 pkgRecords records(cache_);
3542 lock_ = new FileFd();
3543 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3545 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3547 if ([self popErrorWithTitle:title])
3551 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3554 manager_ = (_system->CreatePM(cache_));
3555 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3562 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3564 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3566 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3568 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3569 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3572 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3577 [CydiaApp retainNetworkActivityIndicator];
3579 bool failed = false;
3580 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3581 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3583 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3586 std::string uri = (*item)->DescURI();
3587 std::string error = (*item)->ErrorText;
3589 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3592 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3593 withObject:[NSArray arrayWithObjects:
3594 [NSString stringWithUTF8String:error.c_str()],
3600 [CydiaApp releaseNetworkActivityIndicator];
3608 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3610 if (_error->PendingError()) {
3615 if (result == pkgPackageManager::Failed) {
3620 if (result != pkgPackageManager::Completed) {
3625 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3627 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3629 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3630 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3633 if (![before isEqualToArray:after])
3638 NSString *title(UCLocalize("UPGRADE"));
3639 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3645 [self updateWithStatus:status_];
3648 - (void) updateWithStatus:(Status &)status {
3649 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3650 NSString *title(UCLocalize("REFRESHING_DATA"));
3653 if (!list.ReadMainList())
3654 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3657 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3658 if ([self popErrorWithTitle:title])
3661 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3662 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3663 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3665 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3669 - (void) setDelegate:(id)delegate {
3670 delegate_ = delegate;
3671 status_.setDelegate(delegate);
3672 progress_.setDelegate(delegate);
3675 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3676 SourceMap::const_iterator i(sources_.find(file->ID));
3677 return i == sources_.end() ? nil : i->second;
3683 /* Confirmation Controller {{{ */
3684 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3685 if (!iterator.end())
3686 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3687 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3689 pkgCache::PkgIterator package(dep.TargetPkg());
3692 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3700 /* Web Scripting {{{ */
3701 @interface CydiaObject : NSObject {
3703 _transient id delegate_;
3706 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3709 @implementation CydiaObject
3712 [indirect_ release];
3716 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3717 if ((self = [super init]) != nil) {
3718 indirect_ = [indirect retain];
3722 - (void) setDelegate:(id)delegate {
3723 delegate_ = delegate;
3726 + (NSArray *) _attributeKeys {
3727 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3730 - (NSArray *) attributeKeys {
3731 return [[self class] _attributeKeys];
3734 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3735 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3738 - (NSString *) device {
3739 return [[UIDevice currentDevice] uniqueIdentifier];
3742 #if 0 // XXX: implement!
3743 - (NSString *) mac {
3744 if (![indirect_ promptForSensitive:@"Mac Address"])
3748 - (NSString *) serial {
3749 if (![indirect_ promptForSensitive:@"Serial #"])
3753 - (NSString *) firewire {
3754 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3758 - (NSString *) imei {
3759 if (![indirect_ promptForSensitive:@"IMEI"])
3764 + (NSString *) webScriptNameForSelector:(SEL)selector {
3765 if (selector == @selector(close))
3767 else if (selector == @selector(getInstalledPackages))
3768 return @"getInstalledPackages";
3769 else if (selector == @selector(getPackageById:))
3770 return @"getPackageById";
3771 else if (selector == @selector(installPackages:))
3772 return @"installPackages";
3773 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3774 return @"setButtonImage";
3775 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3776 return @"setButtonTitle";
3777 else if (selector == @selector(setPopupHook:))
3778 return @"setPopupHook";
3779 else if (selector == @selector(setSpecial:))
3780 return @"setSpecial";
3781 else if (selector == @selector(setToken:))
3783 else if (selector == @selector(setViewportWidth:))
3784 return @"setViewportWidth";
3785 else if (selector == @selector(supports:))
3787 else if (selector == @selector(stringWithFormat:arguments:))
3789 else if (selector == @selector(localizedStringForKey:value:table:))
3791 else if (selector == @selector(du:))
3793 else if (selector == @selector(statfs:))
3799 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3800 return [self webScriptNameForSelector:selector] == nil;
3803 - (BOOL) supports:(NSString *)feature {
3804 return [feature isEqualToString:@"window.open"];
3807 - (NSArray *) getInstalledPackages {
3808 NSArray *packages([[Database sharedInstance] packages]);
3809 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3810 for (Package *package in packages)
3811 if ([package installed] != nil)
3812 [installed addObject:package];
3816 - (Package *) getPackageById:(NSString *)id {
3817 Package *package([[Database sharedInstance] packageWithName:id]);
3822 - (NSArray *) statfs:(NSString *)path {
3825 if (path == nil || statfs([path UTF8String], &stat) == -1)
3828 return [NSArray arrayWithObjects:
3829 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3830 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3831 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3835 - (NSNumber *) du:(NSString *)path {
3836 NSNumber *value(nil);
3839 _assert(pipe(fds) != -1);
3841 pid_t pid(ExecFork());
3843 _assert(dup2(fds[1], 1) != -1);
3844 _assert(close(fds[0]) != -1);
3845 _assert(close(fds[1]) != -1);
3846 /* XXX: this should probably not use du */
3847 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3852 _assert(close(fds[1]) != -1);
3854 if (FILE *du = fdopen(fds[0], "r")) {
3856 while (fgets(line, sizeof(line), du) != NULL) {
3857 size_t length(strlen(line));
3858 while (length != 0 && line[length - 1] == '\n')
3859 line[--length] = '\0';
3860 if (char *tab = strchr(line, '\t')) {
3862 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3867 } else _assert(close(fds[0]));
3871 if (waitpid(pid, &status, 0) == -1)
3874 else _assert(false);
3883 - (void) installPackages:(NSArray *)packages {
3884 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3887 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3888 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3891 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3892 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3895 - (void) setSpecial:(id)function {
3896 [indirect_ setSpecial:function];
3899 - (void) setToken:(NSString *)token {
3902 Token_ = [token retain];
3904 [Metadata_ setObject:Token_ forKey:@"Token"];
3908 - (void) setPopupHook:(id)function {
3909 [indirect_ setPopupHook:function];
3912 - (void) setViewportWidth:(float)width {
3913 [indirect_ setViewportWidth:width];
3916 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3917 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3918 unsigned count([arguments count]);
3920 for (unsigned i(0); i != count; ++i)
3921 values[i] = [arguments objectAtIndex:i];
3922 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3925 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3926 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3928 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3930 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3936 /* Cydia Browser Controller {{{ */
3937 @interface CYBrowserController : BrowserController {
3938 CydiaObject *cydia_;
3943 @implementation CYBrowserController
3950 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3953 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3954 [super webView:view didClearWindowObject:window forFrame:frame];
3956 WebDataSource *source([frame dataSource]);
3957 NSURLResponse *response([source response]);
3958 NSURL *url([response URL]);
3959 NSString *scheme([url scheme]);
3961 NSHTTPURLResponse *http;
3962 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3963 http = (NSHTTPURLResponse *) response;
3967 NSDictionary *headers([http allHeaderFields]);
3968 NSString *host([url host]);
3969 [self setHeaders:headers forHost:host];
3972 [host isEqualToString:@"cydia.saurik.com"] ||
3973 [host hasSuffix:@".cydia.saurik.com"] ||
3974 [scheme isEqualToString:@"file"]
3976 [window setValue:cydia_ forKey:@"cydia"];
3979 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3980 if (System_ != NULL)
3981 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3982 if (Machine_ != NULL)
3983 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3985 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3987 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3990 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3991 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3992 [self _setMoreHeaders:copy];
3996 - (void) setDelegate:(id)delegate {
3997 [super setDelegate:delegate];
3998 [cydia_ setDelegate:delegate];
4002 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4003 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4005 WebView *webview([[webview_ _documentView] webView]);
4007 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4009 NSString *application = package == nil ? @"Cydia" : [NSString
4010 stringWithFormat:@"Cydia/%@",
4015 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4017 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4018 if (Product_ != nil)
4019 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4021 [webview setApplicationNameForUserAgent:application];
4028 /* Confirmation {{{ */
4029 @protocol ConfirmationControllerDelegate
4030 - (void) cancelAndClear:(bool)clear;
4031 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4035 @interface ConfirmationController : CYBrowserController {
4036 _transient Database *database_;
4037 UIAlertView *essential_;
4044 - (id) initWithDatabase:(Database *)database;
4048 @implementation ConfirmationController
4055 if (essential_ != nil)
4056 [essential_ release];
4060 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4061 NSString *context([alert context]);
4063 if ([context isEqualToString:@"remove"]) {
4064 if (button == [alert cancelButtonIndex]) {
4065 [self dismissModalViewControllerAnimated:YES];
4066 } else if (button == [alert firstOtherButtonIndex]) {
4069 [delegate_ confirmWithNavigationController:[self navigationController]];
4072 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4073 } else if ([context isEqualToString:@"unable"]) {
4074 [self dismissModalViewControllerAnimated:YES];
4075 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4077 [super alertView:alert clickedButtonAtIndex:button];
4081 - (void) _doContinue {
4082 [self dismissModalViewControllerAnimated:YES];
4083 [delegate_ cancelAndClear:NO];
4086 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4087 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4091 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4092 [super webView:view didClearWindowObject:window forFrame:frame];
4093 [window setValue:changes_ forKey:@"changes"];
4094 [window setValue:issues_ forKey:@"issues"];
4095 [window setValue:sizes_ forKey:@"sizes"];
4096 [window setValue:self forKey:@"queue"];
4099 - (id) initWithDatabase:(Database *)database {
4100 if ((self = [super init]) != nil) {
4101 database_ = database;
4103 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4105 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4106 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4107 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4108 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4109 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4113 pkgDepCache::Policy *policy([database_ policy]);
4115 pkgCacheFile &cache([database_ cache]);
4116 NSArray *packages = [database_ packages];
4117 for (Package *package in packages) {
4118 pkgCache::PkgIterator iterator = [package iterator];
4119 pkgDepCache::StateCache &state(cache[iterator]);
4121 NSString *name([package name]);
4123 if (state.NewInstall())
4124 [installing addObject:name];
4125 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4126 [reinstalling addObject:name];
4127 else if (state.Upgrade())
4128 [upgrading addObject:name];
4129 else if (state.Downgrade())
4130 [downgrading addObject:name];
4131 else if (state.Delete()) {
4132 if ([package essential])
4134 [removing addObject:name];
4137 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4138 substrate_ |= DepSubstrate(iterator.CurrentVer());
4143 else if (Advanced_) {
4144 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4146 essential_ = [[UIAlertView alloc]
4147 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4148 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4150 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4151 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4154 [essential_ setContext:@"remove"];
4156 essential_ = [[UIAlertView alloc]
4157 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4158 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4160 cancelButtonTitle:UCLocalize("OKAY")
4161 otherButtonTitles:nil
4164 [essential_ setContext:@"unable"];
4167 changes_ = [[NSArray alloc] initWithObjects:
4175 issues_ = [database_ issues];
4177 issues_ = [issues_ retain];
4179 sizes_ = [[NSArray alloc] initWithObjects:
4180 SizeString([database_ fetcher].FetchNeeded()),
4181 SizeString([database_ fetcher].PartialPresent()),
4184 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4186 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4187 initWithTitle:UCLocalize("CANCEL")
4188 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4189 style:UIBarButtonItemStylePlain
4191 action:@selector(cancelButtonClicked)
4196 - (void) applyRightButton {
4197 #if !AlwaysReload && !IgnoreInstall
4198 if (issues_ == nil && ![self isLoading])
4199 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4200 initWithTitle:UCLocalize("CONFIRM")
4201 style:UIBarButtonItemStylePlain
4203 action:@selector(confirmButtonClicked)
4206 [super applyRightButton];
4208 [[self navigationItem] setRightBarButtonItem:nil];
4212 - (void) cancelButtonClicked {
4213 [self dismissModalViewControllerAnimated:YES];
4214 [delegate_ cancelAndClear:YES];
4218 - (void) confirmButtonClicked {
4222 if (essential_ != nil)
4227 [delegate_ confirmWithNavigationController:[self navigationController]];
4235 /* Progress Data {{{ */
4236 @interface ProgressData : NSObject {
4238 // XXX: should these really both be _transient?
4239 _transient id target_;
4240 _transient id object_;
4243 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4250 @implementation ProgressData
4252 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4253 if ((self = [super init]) != nil) {
4254 selector_ = selector;
4274 /* Progress Controller {{{ */
4275 @interface ProgressController : CYViewController <
4276 ConfigurationDelegate,
4279 _transient Database *database_;
4280 UIProgressBar *progress_;
4281 UITextView *output_;
4282 UITextLabel *status_;
4283 UIPushButton *close_;
4285 SHA1SumValue springlist_;
4286 SHA1SumValue notifyconf_;
4290 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4292 - (void) _retachThread;
4293 - (void) _detachNewThreadData:(ProgressData *)data;
4294 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4300 @protocol ProgressControllerDelegate
4301 - (void) progressControllerIsComplete:(ProgressController *)sender;
4304 @implementation ProgressController
4307 [database_ setDelegate:nil];
4308 [progress_ release];
4317 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4318 if ((self = [super init]) != nil) {
4319 database_ = database;
4320 [database_ setDelegate:self];
4321 delegate_ = delegate;
4323 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4325 progress_ = [[UIProgressBar alloc] init];
4326 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4327 [progress_ setStyle:0];
4329 status_ = [[UITextLabel alloc] init];
4330 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4331 [status_ setColor:[UIColor whiteColor]];
4332 [status_ setBackgroundColor:[UIColor clearColor]];
4333 [status_ setCentersHorizontally:YES];
4334 //[status_ setFont:font];
4336 output_ = [[UITextView alloc] init];
4338 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4339 //[output_ setTextFont:@"Courier New"];
4340 [output_ setFont:[[output_ font] fontWithSize:12]];
4341 [output_ setTextColor:[UIColor whiteColor]];
4342 [output_ setBackgroundColor:[UIColor clearColor]];
4343 [output_ setMarginTop:0];
4344 [output_ setAllowsRubberBanding:YES];
4345 [output_ setEditable:NO];
4346 [[self view] addSubview:output_];
4348 close_ = [[UIPushButton alloc] init];
4349 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4350 [close_ setAutosizesToFit:NO];
4351 [close_ setDrawsShadow:YES];
4352 [close_ setStretchBackground:YES];
4353 [close_ setEnabled:YES];
4354 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4355 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4356 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4357 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4361 - (void) positionViews {
4362 CGRect bounds = [[self view] bounds];
4363 CGSize prgsize = [UIProgressBar defaultSize];
4366 (bounds.size.width - prgsize.width) / 2,
4367 bounds.size.height - prgsize.height - 20
4370 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4372 [progress_ setFrame:prgrect];
4373 [status_ setFrame:CGRectMake(
4375 bounds.size.height - prgsize.height - 50,
4376 bounds.size.width - 20,
4379 [output_ setFrame:CGRectMake(
4382 bounds.size.width - 20,
4383 bounds.size.height - 62
4385 [close_ setFrame:CGRectMake(
4386 (bounds.size.width - closewidth) / 2,
4387 bounds.size.height - prgsize.height - 50,
4393 - (void) viewWillAppear:(BOOL)animated {
4394 [super viewDidAppear:animated];
4395 [[self navigationItem] setHidesBackButton:YES];
4396 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4398 [self positionViews];
4401 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4402 [self positionViews];
4405 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4406 NSString *context([alert context]);
4408 if ([context isEqualToString:@"conffile"]) {
4409 FILE *input = [database_ input];
4410 if (button == [alert cancelButtonIndex])
4411 fprintf(input, "N\n");
4412 else if (button == [alert firstOtherButtonIndex])
4413 fprintf(input, "Y\n");
4418 - (void) closeButtonPushed {
4421 UpdateExternalStatus(0);
4425 [self dismissModalViewControllerAnimated:YES];
4429 [delegate_ terminateWithSuccess];
4430 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4431 [delegate_ suspendWithAnimation:YES];
4433 [delegate_ suspend];*/
4445 system("/usr/bin/sbreload");
4451 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4452 SBReboot(SBSSpringBoardServerPort());
4454 reboot2(RB_AUTOBOOT);
4459 - (void) _retachThread {
4460 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4462 [[self view] addSubview:close_];
4463 [progress_ removeFromSuperview];
4464 [status_ removeFromSuperview];
4466 [database_ popErrorWithTitle:title_];
4467 [delegate_ progressControllerIsComplete:self];
4471 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4474 MMap mmap(file, MMap::ReadOnly);
4476 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4477 if (!(notifyconf_ == sha1.Result()))
4484 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4487 MMap mmap(file, MMap::ReadOnly);
4489 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4490 if (!(springlist_ == sha1.Result()))
4496 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4497 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4498 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4499 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4500 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4504 system("su -c /usr/bin/uicache mobile");
4507 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4509 [delegate_ setStatusBarShowsProgress:NO];
4512 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4513 [[data target] performSelector:[data selector] withObject:[data object]];
4514 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4517 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4518 UpdateExternalStatus(1);
4525 title_ = [title retain];
4527 [[self navigationItem] setTitle:title_];
4529 [status_ setText:nil];
4530 [output_ setText:@""];
4531 [progress_ setProgress:0];
4533 [close_ removeFromSuperview];
4534 [[self view] addSubview:progress_];
4535 [[self view] addSubview:status_];
4537 [delegate_ setStatusBarShowsProgress:YES];
4542 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4545 MMap mmap(file, MMap::ReadOnly);
4547 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4548 notifyconf_ = sha1.Result();
4554 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4557 MMap mmap(file, MMap::ReadOnly);
4559 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4560 springlist_ = sha1.Result();
4565 detachNewThreadSelector:@selector(_detachNewThreadData:)
4567 withObject:[[[ProgressData alloc]
4568 initWithSelector:selector
4575 - (void) repairWithSelector:(SEL)selector {
4577 detachNewThreadSelector:selector
4580 title:UCLocalize("REPAIRING")
4584 - (void) setConfigurationData:(NSString *)data {
4586 performSelectorOnMainThread:@selector(_setConfigurationData:)
4592 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4593 CYActionSheet *sheet([[[CYActionSheet alloc]
4595 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4596 defaultButtonIndex:0
4599 [sheet setMessage:error];
4600 [sheet yieldToPopupAlertAnimated:YES];
4604 - (void) setProgressTitle:(NSString *)title {
4606 performSelectorOnMainThread:@selector(_setProgressTitle:)
4612 - (void) setProgressPercent:(float)percent {
4614 performSelectorOnMainThread:@selector(_setProgressPercent:)
4615 withObject:[NSNumber numberWithFloat:percent]
4620 - (void) startProgress {
4623 - (void) addProgressOutput:(NSString *)output {
4625 performSelectorOnMainThread:@selector(_addProgressOutput:)
4631 - (bool) isCancelling:(size_t)received {
4635 - (void) _setConfigurationData:(NSString *)data {
4636 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4638 if (!conffile_r(data)) {
4639 lprintf("E:invalid conffile\n");
4643 NSString *ofile = conffile_r[1];
4644 //NSString *nfile = conffile_r[2];
4646 UIAlertView *alert = [[[UIAlertView alloc]
4647 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4648 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4650 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4651 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4652 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4656 [alert setContext:@"conffile"];
4660 - (void) _setProgressTitle:(NSString *)title {
4661 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4662 for (size_t i(0), e([words count]); i != e; ++i) {
4663 NSString *word([words objectAtIndex:i]);
4664 if (Package *package = [database_ packageWithName:word])
4665 [words replaceObjectAtIndex:i withObject:[package name]];
4668 [status_ setText:[words componentsJoinedByString:@" "]];
4671 - (void) _setProgressPercent:(NSNumber *)percent {
4672 [progress_ setProgress:[percent floatValue]];
4675 - (void) _addProgressOutput:(NSString *)output {
4676 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4677 CGSize size = [output_ contentSize];
4678 CGPoint offset = [output_ contentOffset];
4679 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4680 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4681 [output_ scrollRectToVisible:rect animated:YES];
4685 - (BOOL) isRunning {
4692 /* Cell Content View {{{ */
4693 @protocol ContentDelegate
4694 - (void) drawContentRect:(CGRect)rect;
4697 @interface ContentView : UIView {
4698 _transient id<ContentDelegate> delegate_;
4703 @implementation ContentView
4705 - (id) initWithFrame:(CGRect)frame {
4706 if ((self = [super initWithFrame:frame]) != nil) {
4707 [self setNeedsDisplayOnBoundsChange:YES];
4711 - (void) setDelegate:(id<ContentDelegate>)delegate {
4712 delegate_ = delegate;
4715 - (void) drawRect:(CGRect)rect {
4716 [super drawRect:rect];
4717 [delegate_ drawContentRect:rect];
4722 /* Cydia TableView Cell {{{ */
4723 @interface CYTableViewCell : UITableViewCell {
4724 ContentView *content_;
4730 @implementation CYTableViewCell
4737 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4738 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4740 if (view == content_) {
4741 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4742 highlighted_ = highlighted;
4745 [super _updateHighlightColorsForView:view highlighted:highlighted];
4748 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4749 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4750 highlighted_ = selected;
4752 [super setSelected:selected animated:animated];
4753 [content_ setNeedsDisplay];
4758 /* Package Cell {{{ */
4759 @interface PackageCell : CYTableViewCell <
4764 NSString *description_;
4772 - (PackageCell *) init;
4773 - (void) setPackage:(Package *)package;
4775 + (int) heightForPackage:(Package *)package;
4776 - (void) drawContentRect:(CGRect)rect;
4780 @implementation PackageCell
4782 - (void) clearPackage {
4793 if (description_ != nil) {
4794 [description_ release];
4798 if (source_ != nil) {
4803 if (badge_ != nil) {
4808 if (placard_ != nil) {
4818 [self clearPackage];
4822 - (PackageCell *) init {
4823 CGRect frame(CGRectMake(0, 0, 320, 74));
4824 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4825 UIView *content([self contentView]);
4826 CGRect bounds([content bounds]);
4828 content_ = [[ContentView alloc] initWithFrame:bounds];
4829 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4830 [content addSubview:content_];
4832 [content_ setDelegate:self];
4833 [content_ setOpaque:YES];
4837 - (void) _setBackgroundColor {
4839 if (NSString *mode = [package_ mode]) {
4840 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4841 color = remove ? RemovingColor_ : InstallingColor_;
4843 color = [UIColor whiteColor];
4845 [content_ setBackgroundColor:color];
4846 [self setNeedsDisplay];
4849 - (void) setPackage:(Package *)package {
4850 [self clearPackage];
4853 Source *source = [package source];
4855 icon_ = [[package icon] retain];
4856 name_ = [[package name] retain];
4859 description_ = [package longDescription];
4860 if (description_ == nil)
4861 description_ = [package shortDescription];
4862 if (description_ != nil)
4863 description_ = [description_ retain];
4865 commercial_ = [package isCommercial];
4867 package_ = [package retain];
4869 NSString *label = nil;
4870 bool trusted = false;
4872 if (source != nil) {
4873 label = [source label];
4874 trusted = [source trusted];
4875 } else if ([[package id] isEqualToString:@"firmware"])
4876 label = UCLocalize("APPLE");
4878 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4880 NSString *from(label);
4882 NSString *section = [package simpleSection];
4883 if (section != nil && ![section isEqualToString:label]) {
4884 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4885 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4888 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4889 source_ = [from retain];
4891 if (NSString *purpose = [package primaryPurpose])
4892 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4893 badge_ = [badge_ retain];
4895 if ([package installed] != nil)
4896 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4897 placard_ = [placard_ retain];
4899 [self _setBackgroundColor];
4900 [content_ setNeedsDisplay];
4903 - (void) drawContentRect:(CGRect)rect {
4904 bool highlighted(highlighted_);
4905 float width([self bounds].size.width);
4908 CGContextRef context(UIGraphicsGetCurrentContext());
4909 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4910 CGContextFillRect(context, rect);
4915 rect.size = [icon_ size];
4917 rect.size.width /= 2;
4918 rect.size.height /= 2;
4920 rect.origin.x = 25 - rect.size.width / 2;
4921 rect.origin.y = 25 - rect.size.height / 2;
4923 [icon_ drawInRect:rect];
4926 if (badge_ != nil) {
4928 rect.size = [badge_ size];
4930 rect.size.width /= 2;
4931 rect.size.height /= 2;
4933 rect.origin.x = 36 - rect.size.width / 2;
4934 rect.origin.y = 36 - rect.size.height / 2;
4936 [badge_ drawInRect:rect];
4943 UISetColor(commercial_ ? Purple_ : Black_);
4944 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4945 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4948 UISetColor(commercial_ ? Purplish_ : Gray_);
4949 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4951 if (placard_ != nil)
4952 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4955 + (int) heightForPackage:(Package *)package {
4961 /* Section Cell {{{ */
4962 @interface SectionCell : CYTableViewCell <
4974 - (void) setSection:(Section *)section editing:(BOOL)editing;
4978 @implementation SectionCell
4980 - (void) clearSection {
4981 if (basic_ != nil) {
4986 if (section_ != nil) {
4996 if (count_ != nil) {
5003 [self clearSection];
5009 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5010 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5011 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5012 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5013 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5015 UIView *content([self contentView]);
5016 CGRect bounds([content bounds]);
5018 content_ = [[ContentView alloc] initWithFrame:bounds];
5019 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5020 [content addSubview:content_];
5021 [content_ setBackgroundColor:[UIColor whiteColor]];
5023 [content_ setDelegate:self];
5027 - (void) onSwitch:(id)sender {
5028 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5029 if (metadata == nil) {
5030 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5031 [Sections_ setObject:metadata forKey:basic_];
5034 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5038 - (void) setSection:(Section *)section editing:(BOOL)editing {
5039 if (editing != editing_) {
5041 [switch_ removeFromSuperview];
5043 [self addSubview:switch_];
5047 [self clearSection];
5049 if (section == nil) {
5050 name_ = [UCLocalize("ALL_PACKAGES") retain];
5053 basic_ = [section name];
5055 basic_ = [basic_ retain];
5057 section_ = [section localized];
5058 if (section_ != nil)
5059 section_ = [section_ retain];
5061 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5062 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5065 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5068 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5069 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5071 [content_ setNeedsDisplay];
5074 - (void) setFrame:(CGRect)frame {
5075 [super setFrame:frame];
5077 CGRect rect([switch_ frame]);
5078 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5081 - (void) drawContentRect:(CGRect)rect {
5082 bool highlighted(highlighted_);
5084 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5089 float width(rect.size.width);
5095 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5097 CGSize size = [count_ sizeWithFont:Font14_];
5101 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5107 /* File Table {{{ */
5108 @interface FileTable : CYViewController <
5109 UITableViewDataSource,
5112 _transient Database *database_;
5115 NSMutableArray *files_;
5119 - (id) initWithDatabase:(Database *)database;
5120 - (void) setPackage:(Package *)package;
5124 @implementation FileTable
5127 if (package_ != nil)
5136 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5137 return files_ == nil ? 0 : [files_ count];
5140 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5144 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5145 static NSString *reuseIdentifier = @"Cell";
5147 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5149 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5150 [cell setFont:[UIFont systemFontOfSize:16]];
5152 [cell setText:[files_ objectAtIndex:indexPath.row]];
5153 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5158 - (id) initWithDatabase:(Database *)database {
5159 if ((self = [super init]) != nil) {
5160 database_ = database;
5162 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5164 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5166 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5167 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5168 [list_ setRowHeight:24.0f];
5169 [[self view] addSubview:list_];
5171 [list_ setDataSource:self];
5172 [list_ setDelegate:self];
5176 - (void) setPackage:(Package *)package {
5177 if (package_ != nil) {
5178 [package_ autorelease];
5187 [files_ removeAllObjects];
5189 if (package != nil) {
5190 package_ = [package retain];
5191 name_ = [[package id] retain];
5193 if (NSArray *files = [package files])
5194 [files_ addObjectsFromArray:files];
5196 if ([files_ count] != 0) {
5197 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5198 [files_ removeObjectAtIndex:0];
5199 [files_ sortUsingSelector:@selector(compareByPath:)];
5201 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5202 [stack addObject:@"/"];
5204 for (int i(0), e([files_ count]); i != e; ++i) {
5205 NSString *file = [files_ objectAtIndex:i];
5206 while (![file hasPrefix:[stack lastObject]])
5207 [stack removeLastObject];
5208 NSString *directory = [stack lastObject];
5209 [stack addObject:[file stringByAppendingString:@"/"]];
5210 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5211 ([stack count] - 2) * 3, "",
5212 [file substringFromIndex:[directory length]]
5221 - (void) reloadData {
5222 [self setPackage:[database_ packageWithName:name_]];
5227 /* Package Controller {{{ */
5228 @interface PackageController : CYBrowserController <
5229 UIActionSheetDelegate
5231 _transient Database *database_;
5235 NSMutableArray *buttons_;
5236 UIBarButtonItem *button_;
5239 - (id) initWithDatabase:(Database *)database;
5240 - (void) setPackage:(Package *)package;
5244 @implementation PackageController
5247 if (package_ != nil)
5261 if ([self retainCount] == 1)
5262 [delegate_ setPackageController:self];
5266 /* XXX: this is not safe at all... localization of /fail/ */
5267 - (void) _clickButtonWithName:(NSString *)name {
5268 if ([name isEqualToString:UCLocalize("CLEAR")])
5269 [delegate_ clearPackage:package_];
5270 else if ([name isEqualToString:UCLocalize("INSTALL")])
5271 [delegate_ installPackage:package_];
5272 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5273 [delegate_ installPackage:package_];
5274 else if ([name isEqualToString:UCLocalize("REMOVE")])
5275 [delegate_ removePackage:package_];
5276 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5277 [delegate_ installPackage:package_];
5278 else _assert(false);
5281 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5282 NSString *context([sheet context]);
5284 if ([context isEqualToString:@"modify"]) {
5285 if (button != [sheet cancelButtonIndex]) {
5286 NSString *buttonName = [buttons_ objectAtIndex:button];
5287 [self _clickButtonWithName:buttonName];
5290 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5294 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5295 [super webView:view didClearWindowObject:window forFrame:frame];
5296 [window setValue:package_ forKey:@"package"];
5299 - (bool) _allowJavaScriptPanel {
5304 - (void) _customButtonClicked {
5305 int count([buttons_ count]);
5310 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5312 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5313 [buttons addObjectsFromArray:buttons_];
5315 UIActionSheet *sheet = [[[UIActionSheet alloc]
5318 cancelButtonTitle:nil
5319 destructiveButtonTitle:nil
5320 otherButtonTitles:nil
5323 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5325 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5326 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5328 [sheet setContext:@"modify"];
5330 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5334 // We don't want to allow non-commercial packages to do custom things to the install button,
5335 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5336 - (void) customButtonClicked {
5338 [super customButtonClicked];
5340 [self _customButtonClicked];
5343 - (void) reloadButtonClicked {
5344 // Don't reload a package view by clicking the button.
5347 - (void) applyLoadingTitle {
5348 // Don't show "Loading" as the title. Ever.
5351 - (UIBarButtonItem *) rightButton {
5356 - (id) initWithDatabase:(Database *)database {
5357 if ((self = [super init]) != nil) {
5358 database_ = database;
5359 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5360 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5364 - (void) setPackage:(Package *)package {
5365 if (package_ != nil) {
5366 [package_ autorelease];
5375 [buttons_ removeAllObjects];
5377 if (package != nil) {
5380 package_ = [package retain];
5381 name_ = [[package id] retain];
5382 commercial_ = [package isCommercial];
5384 if ([package_ mode] != nil)
5385 [buttons_ addObject:UCLocalize("CLEAR")];
5386 if ([package_ source] == nil);
5387 else if ([package_ upgradableAndEssential:NO])
5388 [buttons_ addObject:UCLocalize("UPGRADE")];
5389 else if ([package_ uninstalled])
5390 [buttons_ addObject:UCLocalize("INSTALL")];
5392 [buttons_ addObject:UCLocalize("REINSTALL")];
5393 if (![package_ uninstalled])
5394 [buttons_ addObject:UCLocalize("REMOVE")];
5401 switch ([buttons_ count]) {
5402 case 0: title = nil; break;
5403 case 1: title = [buttons_ objectAtIndex:0]; break;
5404 default: title = UCLocalize("MODIFY"); break;
5407 button_ = [[UIBarButtonItem alloc]
5409 style:UIBarButtonItemStylePlain
5411 action:@selector(customButtonClicked)
5417 - (bool) isLoading {
5418 return commercial_ ? [super isLoading] : false;
5421 - (void) reloadData {
5422 [self setPackage:[database_ packageWithName:name_]];
5427 /* Package Table {{{ */
5428 @interface PackageTable : UIView <
5429 UITableViewDataSource,
5432 _transient Database *database_;
5434 NSMutableArray *packages_;
5435 NSMutableArray *sections_;
5437 NSMutableArray *index_;
5438 NSMutableDictionary *indices_;
5439 // XXX: this target_ seems to be delegate_. :(
5440 _transient id target_;
5442 // XXX: why do we even have this delegate_?
5443 _transient id delegate_;
5446 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5448 - (void) setDelegate:(id)delegate;
5450 - (void) reloadData;
5451 - (void) resetCursor;
5453 - (UITableView *) list;
5455 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5457 - (void) deselectWithAnimation:(BOOL)animated;
5461 @implementation PackageTable
5464 [packages_ release];
5465 [sections_ release];
5473 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5474 NSInteger count([sections_ count]);
5475 return count == 0 ? 1 : count;
5478 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5479 if ([sections_ count] == 0)
5481 return [[sections_ objectAtIndex:section] name];
5484 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5485 if ([sections_ count] == 0)
5487 return [[sections_ objectAtIndex:section] count];
5490 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5491 @synchronized (database_) {
5492 if ([database_ era] != era_)
5495 Section *section([sections_ objectAtIndex:[path section]]);
5496 NSInteger row([path row]);
5497 Package *package([packages_ objectAtIndex:([section row] + row)]);
5498 return [[package retain] autorelease];
5501 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5502 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5504 cell = [[[PackageCell alloc] init] autorelease];
5505 [cell setPackage:[self packageAtIndexPath:path]];
5509 - (void) deselectWithAnimation:(BOOL)animated {
5510 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5513 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5514 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5517 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5518 Package *package([self packageAtIndexPath:path]);
5519 package = [database_ packageWithName:[package id]];
5520 [target_ performSelector:action_ withObject:package];
5524 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5525 return [packages_ count] > 20 ? index_ : nil;
5528 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5532 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5533 if ((self = [super initWithFrame:frame]) != nil) {
5534 database_ = database;
5539 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5540 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5542 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5543 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5545 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5546 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5547 [list_ setRowHeight:73.0f];
5548 [self addSubview:list_];
5550 [list_ setDataSource:self];
5551 [list_ setDelegate:self];
5555 - (void) setDelegate:(id)delegate {
5556 delegate_ = delegate;
5559 - (bool) hasPackage:(Package *)package {
5563 - (void) reloadData {
5564 era_ = [database_ era];
5565 NSArray *packages = [database_ packages];
5567 [packages_ removeAllObjects];
5568 [sections_ removeAllObjects];
5570 _profile(PackageTable$reloadData$Filter)
5571 for (Package *package in packages)
5572 if ([self hasPackage:package])
5573 [packages_ addObject:package];
5576 [index_ removeAllObjects];
5577 [indices_ removeAllObjects];
5579 Section *section = nil;
5581 _profile(PackageTable$reloadData$Section)
5582 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5586 _profile(PackageTable$reloadData$Section$Package)
5587 package = [packages_ objectAtIndex:offset];
5588 index = [package index];
5591 if (section == nil || [section index] != index) {
5592 _profile(PackageTable$reloadData$Section$Allocate)
5593 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5596 [index_ addObject:[section name]];
5597 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5599 _profile(PackageTable$reloadData$Section$Add)
5600 [sections_ addObject:section];
5604 [section addToCount];
5608 _profile(PackageTable$reloadData$List)
5613 - (void) resetCursor {
5614 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5617 - (UITableView *) list {
5621 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5622 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5627 /* Filtered Package Table {{{ */
5628 @interface FilteredPackageTable : PackageTable {
5634 - (void) setObject:(id)object;
5635 - (void) setObject:(id)object forFilter:(SEL)filter;
5637 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5641 @implementation FilteredPackageTable
5649 - (void) setFilter:(SEL)filter {
5652 /* XXX: this is an unsafe optimization of doomy hell */
5653 Method method(class_getInstanceMethod([Package class], filter));
5654 _assert(method != NULL);
5655 imp_ = method_getImplementation(method);
5656 _assert(imp_ != NULL);
5659 - (void) setObject:(id)object {
5665 object_ = [object retain];
5668 - (void) setObject:(id)object forFilter:(SEL)filter {
5669 [self setFilter:filter];
5670 [self setObject:object];
5673 - (bool) hasPackage:(Package *)package {
5674 _profile(FilteredPackageTable$hasPackage)
5675 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5679 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5680 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5681 [self setFilter:filter];
5682 object_ = [object retain];
5690 /* Filtered Package Controller {{{ */
5691 @interface FilteredPackageController : CYViewController {
5692 _transient Database *database_;
5693 FilteredPackageTable *packages_;
5697 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5701 @implementation FilteredPackageController
5704 [packages_ release];
5710 - (void) viewDidAppear:(BOOL)animated {
5711 [super viewDidAppear:animated];
5712 [packages_ deselectWithAnimation:animated];
5715 - (void) didSelectPackage:(Package *)package {
5716 PackageController *view([delegate_ packageController]);
5717 [view setPackage:package];
5718 [view setDelegate:delegate_];
5719 [[self navigationController] pushViewController:view animated:YES];
5722 - (NSString *) title { return title_; }
5724 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5725 if ((self = [super init]) != nil) {
5726 database_ = database;
5727 title_ = [title copy];
5728 [[self navigationItem] setTitle:title_];
5730 packages_ = [[FilteredPackageTable alloc]
5731 initWithFrame:[[self view] bounds]
5734 action:@selector(didSelectPackage:)
5739 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5740 [[self view] addSubview:packages_];
5744 - (void) reloadData {
5745 [packages_ reloadData];
5748 - (void) setDelegate:(id)delegate {
5749 [super setDelegate:delegate];
5750 [packages_ setDelegate:delegate];
5757 /* Source Cell {{{ */
5758 @interface SourceCell : CYTableViewCell <
5763 NSString *description_;
5767 - (void) setSource:(Source *)source;
5771 @implementation SourceCell
5773 - (void) clearSource {
5776 [description_ release];
5785 - (void) setSource:(Source *)source {
5789 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5791 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5792 icon_ = [icon_ retain];
5794 origin_ = [[source name] retain];
5795 label_ = [[source uri] retain];
5796 description_ = [[source description] retain];
5798 [content_ setNeedsDisplay];
5806 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5807 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5808 UIView *content([self contentView]);
5809 CGRect bounds([content bounds]);
5811 content_ = [[ContentView alloc] initWithFrame:bounds];
5812 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5813 [content_ setBackgroundColor:[UIColor whiteColor]];
5814 [content addSubview:content_];
5816 [content_ setDelegate:self];
5817 [content_ setOpaque:YES];
5821 - (void) drawContentRect:(CGRect)rect {
5822 bool highlighted(highlighted_);
5823 float width(rect.size.width);
5826 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5833 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5837 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5841 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5846 /* Source Table {{{ */
5847 @interface SourceController : CYViewController <
5848 UITableViewDataSource,
5851 _transient Database *database_;
5853 NSMutableArray *sources_;
5857 UIProgressHUD *hud_;
5860 //NSURLConnection *installer_;
5861 NSURLConnection *trivial_;
5862 NSURLConnection *trivial_bz2_;
5863 NSURLConnection *trivial_gz_;
5864 //NSURLConnection *automatic_;
5869 - (id) initWithDatabase:(Database *)database;
5871 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5875 @implementation SourceController
5877 - (void) _releaseConnection:(NSURLConnection *)connection {
5878 if (connection != nil) {
5879 [connection cancel];
5880 //[connection setDelegate:nil];
5881 [connection release];
5893 //[self _releaseConnection:installer_];
5894 [self _releaseConnection:trivial_];
5895 [self _releaseConnection:trivial_gz_];
5896 [self _releaseConnection:trivial_bz2_];
5897 //[self _releaseConnection:automatic_];
5904 - (void) viewDidAppear:(BOOL)animated {
5905 [super viewDidAppear:animated];
5906 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5909 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5910 return offset_ == 0 ? 1 : 2;
5913 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5914 switch (section + (offset_ == 0 ? 1 : 0)) {
5915 case 0: return UCLocalize("ENTERED_BY_USER");
5916 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5922 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5923 int count = [sources_ count];
5925 case 0: return (offset_ == 0 ? count : offset_);
5926 case 1: return count - offset_;
5932 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5934 switch (indexPath.section) {
5935 case 0: idx = indexPath.row; break;
5936 case 1: idx = indexPath.row + offset_; break;
5940 return [sources_ objectAtIndex:idx];
5943 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5944 Source *source = [self sourceAtIndexPath:indexPath];
5945 return [source description] == nil ? 56 : 73;
5948 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5949 static NSString *cellIdentifier = @"SourceCell";
5951 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5952 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5953 [cell setSource:[self sourceAtIndexPath:indexPath]];
5958 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5959 return UITableViewCellAccessoryDisclosureIndicator;
5962 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5963 Source *source = [self sourceAtIndexPath:indexPath];
5965 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5966 initWithDatabase:database_
5967 title:[source label]
5968 filter:@selector(isVisibleInSource:)
5972 [packages setDelegate:delegate_];
5974 [[self navigationController] pushViewController:packages animated:YES];
5977 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5978 Source *source = [self sourceAtIndexPath:indexPath];
5979 return [source record] != nil;
5982 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5983 Source *source = [self sourceAtIndexPath:indexPath];
5984 [Sources_ removeObjectForKey:[source key]];
5985 [delegate_ syncData];
5989 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5992 @"./", @"Distribution",
5993 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5995 [delegate_ syncData];
5998 - (NSString *) getWarning {
5999 NSString *href(href_);
6000 NSRange colon([href rangeOfString:@"://"]);
6001 if (colon.location != NSNotFound)
6002 href = [href substringFromIndex:(colon.location + 3)];
6003 href = [href stringByAddingPercentEscapes];
6004 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
6005 href = [href stringByCachingURLWithCurrentCDN];
6007 NSURL *url([NSURL URLWithString:href]);
6009 NSStringEncoding encoding;
6010 NSError *error(nil);
6012 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
6013 return [warning length] == 0 ? nil : warning;
6017 - (void) _endConnection:(NSURLConnection *)connection {
6018 // XXX: the memory management in this method is horribly awkward
6020 NSURLConnection **field = NULL;
6021 if (connection == trivial_)
6023 else if (connection == trivial_bz2_)
6024 field = &trivial_bz2_;
6025 else if (connection == trivial_gz_)
6026 field = &trivial_gz_;
6027 _assert(field != NULL);
6028 [connection release];
6033 trivial_bz2_ == nil &&
6039 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6042 UIAlertView *alert = [[[UIAlertView alloc]
6043 initWithTitle:UCLocalize("SOURCE_WARNING")
6046 cancelButtonTitle:UCLocalize("CANCEL")
6047 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6050 [alert setContext:@"warning"];
6051 [alert setNumberOfRows:1];
6055 } else if (error_ != nil) {
6056 UIAlertView *alert = [[[UIAlertView alloc]
6057 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6058 message:[error_ localizedDescription]
6060 cancelButtonTitle:UCLocalize("OK")
6061 otherButtonTitles:nil
6064 [alert setContext:@"urlerror"];
6067 UIAlertView *alert = [[[UIAlertView alloc]
6068 initWithTitle:UCLocalize("NOT_REPOSITORY")
6069 message:UCLocalize("NOT_REPOSITORY_EX")
6071 cancelButtonTitle:UCLocalize("OK")
6072 otherButtonTitles:nil
6075 [alert setContext:@"trivial"];
6079 [delegate_ setStatusBarShowsProgress:NO];
6080 [delegate_ removeProgressHUD:hud_];
6090 if (error_ != nil) {
6097 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6098 switch ([response statusCode]) {
6104 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6105 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6107 error_ = [error retain];
6108 [self _endConnection:connection];
6111 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6112 [self _endConnection:connection];
6115 - (NSString *) title { return UCLocalize("SOURCES"); }
6117 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6118 NSMutableURLRequest *request = [NSMutableURLRequest
6119 requestWithURL:[NSURL URLWithString:href]
6120 cachePolicy:NSURLRequestUseProtocolCachePolicy
6121 timeoutInterval:120.0
6124 [request setHTTPMethod:method];
6126 if (Machine_ != NULL)
6127 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6128 if (UniqueID_ != nil)
6129 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6131 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6133 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6136 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6137 NSString *context([alert context]);
6139 if ([context isEqualToString:@"source"]) {
6142 NSString *href = [[alert textField] text];
6144 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6146 if (![href hasSuffix:@"/"])
6147 href_ = [href stringByAppendingString:@"/"];
6150 href_ = [href_ retain];
6152 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6153 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6154 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6155 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6159 // XXX: this is stupid
6160 hud_ = [[delegate_ addProgressHUD] retain];
6161 [hud_ setText:UCLocalize("VERIFYING_URL")];
6170 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6171 } else if ([context isEqualToString:@"trivial"])
6172 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6173 else if ([context isEqualToString:@"urlerror"])
6174 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6175 else if ([context isEqualToString:@"warning"]) {
6190 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6194 - (id) initWithDatabase:(Database *)database {
6195 if ((self = [super init]) != nil) {
6196 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6197 [self updateButtonsForEditingStatus:NO animated:NO];
6199 database_ = database;
6200 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6202 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6203 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6204 [[self view] addSubview:list_];
6206 [list_ setDataSource:self];
6207 [list_ setDelegate:self];
6213 - (void) reloadData {
6215 if (!list.ReadMainList())
6218 [sources_ removeAllObjects];
6219 [sources_ addObjectsFromArray:[database_ sources]];
6221 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6224 int count([sources_ count]);
6226 for (int i = 0; i != count; i++) {
6227 if ([[sources_ objectAtIndex:i] record] == nil)
6232 [list_ setEditing:NO];
6233 [self updateButtonsForEditingStatus:NO animated:NO];
6237 - (void) addButtonClicked {
6238 /*[book_ pushPage:[[[AddSourceController alloc]
6243 UIAlertView *alert = [[[UIAlertView alloc]
6244 initWithTitle:UCLocalize("ENTER_APT_URL")
6247 cancelButtonTitle:UCLocalize("CANCEL")
6248 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6251 [alert setContext:@"source"];
6252 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6254 [alert setNumberOfRows:1];
6255 [alert addTextFieldWithValue:@"http://" label:@""];
6257 UITextInputTraits *traits = [[alert textField] textInputTraits];
6258 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6259 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6260 [traits setKeyboardType:UIKeyboardTypeURL];
6261 // XXX: UIReturnKeyDone
6262 [traits setReturnKeyType:UIReturnKeyNext];
6267 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6268 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6269 initWithTitle:UCLocalize("ADD")
6270 style:UIBarButtonItemStylePlain
6272 action:@selector(addButtonClicked)
6273 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6275 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6276 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6277 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6279 action:@selector(editButtonClicked)
6280 ] autorelease] animated:animated];
6282 if (IsWildcat_ && !editing)
6283 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6284 initWithTitle:UCLocalize("SETTINGS")
6285 style:UIBarButtonItemStylePlain
6287 action:@selector(settingsButtonClicked)
6291 - (void) settingsButtonClicked {
6292 [delegate_ showSettings];
6295 - (void) editButtonClicked {
6296 [list_ setEditing:![list_ isEditing] animated:YES];
6298 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6304 /* Installed Controller {{{ */
6305 @interface InstalledController : FilteredPackageController {
6309 - (id) initWithDatabase:(Database *)database;
6311 - (void) updateRoleButton;
6312 - (void) queueStatusDidChange;
6316 @implementation InstalledController
6322 - (NSString *) title { return UCLocalize("INSTALLED"); }
6324 - (id) initWithDatabase:(Database *)database {
6325 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6326 [self updateRoleButton];
6327 [self queueStatusDidChange];
6332 - (void) queueButtonClicked {
6337 - (void) queueStatusDidChange {
6341 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6342 initWithTitle:UCLocalize("QUEUE")
6343 style:UIBarButtonItemStyleDone
6345 action:@selector(queueButtonClicked)
6348 [[self navigationItem] setLeftBarButtonItem:nil];
6354 - (void) reloadData {
6355 [packages_ reloadData];
6358 - (void) updateRoleButton {
6359 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6360 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6361 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6362 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6364 action:@selector(roleButtonClicked)
6368 - (void) roleButtonClicked {
6369 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6370 [packages_ reloadData];
6373 [self updateRoleButton];
6376 - (void) setDelegate:(id)delegate {
6377 [super setDelegate:delegate];
6378 [packages_ setDelegate:delegate];
6384 /* Home Controller {{{ */
6385 @interface HomeController : CYBrowserController {
6390 @implementation HomeController
6392 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6393 [super _setMoreHeaders:request];
6396 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6397 if (UniqueID_ != nil)
6398 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6400 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6403 - (void) aboutButtonClicked {
6404 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6406 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6407 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6408 [alert setCancelButtonIndex:0];
6411 @"Copyright (C) 2008-2010\n"
6412 "Jay Freeman (saurik)\n"
6413 "saurik@saurik.com\n"
6414 "http://www.saurik.com/"
6420 - (void) viewWillAppear:(BOOL)animated {
6421 [super viewWillAppear:animated];
6422 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6425 - (void) viewWillDisappear:(BOOL)animated {
6426 [super viewWillDisappear:animated];
6427 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6431 if ((self = [super init]) != nil) {
6432 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6433 initWithTitle:UCLocalize("ABOUT")
6434 style:UIBarButtonItemStylePlain
6436 action:@selector(aboutButtonClicked)
6443 /* Manage Controller {{{ */
6444 @interface ManageController : CYBrowserController {
6447 - (void) queueStatusDidChange;
6450 @implementation ManageController
6453 if ((self = [super init]) != nil) {
6454 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6456 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6457 initWithTitle:UCLocalize("SETTINGS")
6458 style:UIBarButtonItemStylePlain
6460 action:@selector(settingsButtonClicked)
6463 [self queueStatusDidChange];
6467 - (void) settingsButtonClicked {
6468 [delegate_ showSettings];
6472 - (void) queueButtonClicked {
6476 - (void) applyLoadingTitle {
6477 // No "Loading" title.
6480 - (void) applyRightButton {
6485 - (void) queueStatusDidChange {
6487 if (!IsWildcat_ && Queuing_) {
6488 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6489 initWithTitle:UCLocalize("QUEUE")
6490 style:UIBarButtonItemStyleDone
6492 action:@selector(queueButtonClicked)
6495 [[self navigationItem] setRightBarButtonItem:nil];
6500 - (bool) isLoading {
6507 /* Refresh Bar {{{ */
6508 @interface RefreshBar : UINavigationBar {
6509 UIProgressIndicator *indicator_;
6510 UITextLabel *prompt_;
6511 UIProgressBar *progress_;
6512 UINavigationButton *cancel_;
6517 @implementation RefreshBar
6520 [indicator_ release];
6522 [progress_ release];
6527 - (void) positionViews {
6528 CGRect frame = [cancel_ frame];
6529 frame.size = [cancel_ sizeThatFits:frame.size];
6530 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6531 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6532 [cancel_ setFrame:frame];
6534 CGSize prgsize = {75, 100};
6536 [self frame].size.width - prgsize.width - 10,
6537 ([self frame].size.height - prgsize.height) / 2
6539 [progress_ setFrame:prgrect];
6541 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6542 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6543 CGRect indrect = {{indoffset, indoffset}, indsize};
6544 [indicator_ setFrame:indrect];
6546 CGSize prmsize = {215, indsize.height + 4};
6548 indoffset * 2 + indsize.width,
6549 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6551 [prompt_ setFrame:prmrect];
6554 - (void)setFrame:(CGRect)frame {
6555 [super setFrame:frame];
6557 [self positionViews];
6560 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6561 if ((self = [super initWithFrame:frame])) {
6562 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6564 [self setBarStyle:UIBarStyleBlack];
6566 UIBarStyle barstyle([self _barStyle:NO]);
6567 bool ugly(barstyle == UIBarStyleDefault);
6569 UIProgressIndicatorStyle style = ugly ?
6570 UIProgressIndicatorStyleMediumBrown :
6571 UIProgressIndicatorStyleMediumWhite;
6573 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6574 [indicator_ setStyle:style];
6575 [indicator_ startAnimation];
6576 [self addSubview:indicator_];
6578 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6579 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6580 [prompt_ setBackgroundColor:[UIColor clearColor]];
6581 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6582 [self addSubview:prompt_];
6584 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6585 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6586 [progress_ setStyle:0];
6587 [self addSubview:progress_];
6589 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6590 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6591 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6592 [cancel_ setBarStyle:barstyle];
6594 [self positionViews];
6599 [cancel_ removeFromSuperview];
6603 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6604 [progress_ setProgress:0];
6605 [self addSubview:cancel_];
6609 [cancel_ removeFromSuperview];
6612 - (void) setPrompt:(NSString *)prompt {
6613 [prompt_ setText:prompt];
6616 - (void) setProgress:(float)progress {
6617 [progress_ setProgress:progress];
6623 @class CYNavigationController;
6625 /* Cydia Tab Bar Controller {{{ */
6626 @interface CYTabBarController : UITabBarController <
6629 _transient Database *database_;
6630 RefreshBar *refreshbar_;
6634 // XXX: ok, "updatedelegate_"?...
6635 _transient NSObject<CydiaDelegate> *updatedelegate_;
6640 - (void) dropBar:(BOOL)animated;
6641 - (void) beginUpdate;
6642 - (void) raiseBar:(BOOL)animated;
6647 @implementation CYTabBarController
6649 /* XXX: some logic should probably go here related to
6650 freeing the view controllers on tab change */
6652 - (void) reloadData {
6653 size_t count([[self viewControllers] count]);
6654 for (size_t i(0); i != count; ++i) {
6655 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6660 - (id) initWithDatabase:(Database *)database {
6661 if ((self = [super init]) != nil) {
6662 database_ = database;
6664 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6665 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6667 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6671 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6672 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
6675 - (void) setUpdate:(NSDate *)date {
6679 - (void) beginUpdate {
6680 [refreshbar_ start];
6683 [updatedelegate_ retainNetworkActivityIndicator];
6687 detachNewThreadSelector:@selector(performUpdate)
6693 - (void) performUpdate { _pooled
6695 status.setDelegate(self);
6696 [database_ updateWithStatus:status];
6699 performSelectorOnMainThread:@selector(completeUpdate)
6705 - (void) stopUpdateWithSelector:(SEL)selector {
6707 [updatedelegate_ releaseNetworkActivityIndicator];
6709 [self raiseBar:YES];
6712 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6715 - (void) completeUpdate {
6718 [self stopUpdateWithSelector:@selector(reloadData)];
6721 - (void) cancelUpdate {
6722 [self stopUpdateWithSelector:@selector(updateData)];
6725 - (void) cancelPressed {
6726 [self cancelUpdate];
6733 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6734 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6737 - (void) startProgress {
6740 - (void) setProgressTitle:(NSString *)title {
6742 performSelectorOnMainThread:@selector(_setProgressTitle:)
6748 - (bool) isCancelling:(size_t)received {
6752 - (void) setProgressPercent:(float)percent {
6754 performSelectorOnMainThread:@selector(_setProgressPercent:)
6755 withObject:[NSNumber numberWithFloat:percent]
6760 - (void) addProgressOutput:(NSString *)output {
6762 performSelectorOnMainThread:@selector(_addProgressOutput:)
6768 - (void) _setProgressTitle:(NSString *)title {
6769 [refreshbar_ setPrompt:title];
6772 - (void) _setProgressPercent:(NSNumber *)percent {
6773 [refreshbar_ setProgress:[percent floatValue]];
6776 - (void) _addProgressOutput:(NSString *)output {
6779 - (void) setUpdateDelegate:(id)delegate {
6780 updatedelegate_ = delegate;
6783 - (CGFloat) statusBarHeight {
6784 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6785 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6787 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6791 - (UIView *) transitionView {
6792 if ([self respondsToSelector:@selector(_transitionView)])
6793 return [self _transitionView];
6795 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6798 - (void) dropBar:(BOOL)animated {
6803 UIView *transition([self transitionView]);
6804 [[self view] addSubview:refreshbar_];
6806 CGRect barframe([refreshbar_ frame]);
6808 if (false) // XXX: _UIApplicationLinkedOnOrAfter(4)
6809 barframe.origin.y = [self statusBarHeight];
6811 barframe.origin.y = 0;
6813 [refreshbar_ setFrame:barframe];
6816 [UIView beginAnimations:nil context:NULL];
6818 CGRect viewframe = [transition frame];
6819 viewframe.origin.y += barframe.size.height;
6820 viewframe.size.height -= barframe.size.height;
6821 [transition setFrame:viewframe];
6824 [UIView commitAnimations];
6826 // Ensure bar has the proper width for our view, it might have changed
6827 barframe.size.width = viewframe.size.width;
6828 [refreshbar_ setFrame:barframe];
6830 // XXX: fix Apple's layout bug
6831 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6834 - (void) raiseBar:(BOOL)animated {
6839 UIView *transition([self transitionView]);
6840 [refreshbar_ removeFromSuperview];
6842 CGRect barframe([refreshbar_ frame]);
6845 [UIView beginAnimations:nil context:NULL];
6847 CGRect viewframe = [transition frame];
6848 viewframe.origin.y -= barframe.size.height;
6849 viewframe.size.height += barframe.size.height;
6850 [transition setFrame:viewframe];
6853 [UIView commitAnimations];
6855 // XXX: fix Apple's layout bug
6856 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6860 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6861 // XXX: fix Apple's layout bug
6862 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6866 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6867 bool dropped(dropped_);
6872 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6877 // XXX: fix Apple's layout bug
6878 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6881 - (void) statusBarFrameChanged:(NSNotification *)notification {
6889 [refreshbar_ release];
6890 [[NSNotificationCenter defaultCenter] removeObserver:self];
6897 /* Cydia Navigation Controller {{{ */
6898 @interface CYNavigationController : UINavigationController {
6899 _transient Database *database_;
6900 _transient id<UINavigationControllerDelegate> delegate_;
6903 - (id) initWithDatabase:(Database *)database;
6904 - (void) reloadData;
6909 @implementation CYNavigationController
6911 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6912 // Inherit autorotation settings for modal parents.
6913 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6914 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6916 return [super shouldAutorotateToInterfaceOrientation:orientation];
6924 - (void) reloadData {
6925 size_t count([[self viewControllers] count]);
6926 for (size_t i(0); i != count; ++i) {
6927 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6932 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6933 delegate_ = delegate;
6936 - (id) initWithDatabase:(Database *)database {
6937 if ((self = [super init]) != nil) {
6938 database_ = database;
6944 /* Cydia:// Protocol {{{ */
6945 @interface CydiaURLProtocol : NSURLProtocol {
6950 @implementation CydiaURLProtocol
6952 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6953 NSURL *url([request URL]);
6956 NSString *scheme([[url scheme] lowercaseString]);
6957 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6962 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6966 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6967 id<NSURLProtocolClient> client([self client]);
6969 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6971 NSData *data(UIImagePNGRepresentation(icon));
6973 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6974 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6975 [client URLProtocol:self didLoadData:data];
6976 [client URLProtocolDidFinishLoading:self];
6980 - (void) startLoading {
6981 id<NSURLProtocolClient> client([self client]);
6982 NSURLRequest *request([self request]);
6984 NSURL *url([request URL]);
6985 NSString *href([url absoluteString]);
6987 NSString *path([href substringFromIndex:8]);
6988 NSRange slash([path rangeOfString:@"/"]);
6991 if (slash.location == NSNotFound) {
6995 command = [path substringToIndex:slash.location];
6996 path = [path substringFromIndex:(slash.location + 1)];
6999 Database *database([Database sharedInstance]);
7001 if ([command isEqualToString:@"package-icon"]) {
7004 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7005 Package *package([database packageWithName:path]);
7008 UIImage *icon([package icon]);
7009 [self _returnPNGWithImage:icon forRequest:request];
7010 } else if ([command isEqualToString:@"source-icon"]) {
7013 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7014 NSString *source(Simplify(path));
7015 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7017 icon = [UIImage applicationImageNamed:@"unknown.png"];
7018 [self _returnPNGWithImage:icon forRequest:request];
7019 } else if ([command isEqualToString:@"uikit-image"]) {
7022 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7023 UIImage *icon(_UIImageWithName(path));
7024 [self _returnPNGWithImage:icon forRequest:request];
7025 } else if ([command isEqualToString:@"section-icon"]) {
7028 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7029 NSString *section(Simplify(path));
7030 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7032 icon = [UIImage applicationImageNamed:@"unknown.png"];
7033 [self _returnPNGWithImage:icon forRequest:request];
7035 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7039 - (void) stopLoading {
7045 /* Sections Controller {{{ */
7046 @interface CYSectionsController : CYViewController <
7047 UITableViewDataSource,
7050 _transient Database *database_;
7051 NSMutableArray *sections_;
7052 NSMutableArray *filtered_;
7058 - (id) initWithDatabase:(Database *)database;
7059 - (void) reloadData;
7062 - (void) editButtonClicked;
7066 @implementation CYSectionsController
7069 [list_ setDataSource:nil];
7070 [list_ setDelegate:nil];
7072 [sections_ release];
7073 [filtered_ release];
7075 [accessory_ release];
7079 - (void) setEditing:(BOOL)editing {
7080 if ((editing_ = editing))
7083 [delegate_ updateData];
7085 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7086 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
7087 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
7090 - (void) viewDidAppear:(BOOL)animated {
7091 [super viewDidAppear:animated];
7092 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7095 - (void) viewWillDisappear:(BOOL)animated {
7096 [super viewWillDisappear:animated];
7097 if (editing_) [self setEditing:NO];
7100 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7101 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7105 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7106 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7109 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7113 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7114 static NSString *reuseIdentifier = @"SectionCell";
7116 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7118 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7120 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7125 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7129 Section *section = [self sectionAtIndexPath:indexPath];
7130 NSString *name = [section name];
7133 if ([indexPath row] == 0) {
7136 title = UCLocalize("ALL_PACKAGES");
7139 name = [NSString stringWithString:name];
7140 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7143 title = UCLocalize("NO_SECTION");
7147 FilteredPackageController *table = [[[FilteredPackageController alloc]
7148 initWithDatabase:database_
7150 filter:@selector(isVisibleInSection:)
7154 [table setDelegate:delegate_];
7156 [[self navigationController] pushViewController:table animated:YES];
7159 - (NSString *) title { return UCLocalize("SECTIONS"); }
7161 - (id) initWithDatabase:(Database *)database {
7162 if ((self = [super init]) != nil) {
7163 database_ = database;
7165 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7167 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7168 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7170 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7171 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7172 [list_ setRowHeight:45.0f];
7173 [[self view] addSubview:list_];
7175 [list_ setDataSource:self];
7176 [list_ setDelegate:self];
7182 - (void) reloadData {
7183 NSArray *packages = [database_ packages];
7185 [sections_ removeAllObjects];
7186 [filtered_ removeAllObjects];
7188 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7191 for (Package *package in packages) {
7192 NSString *name([package section]);
7193 NSString *key(name == nil ? @"" : name);
7197 _profile(SectionsView$reloadData$Section)
7198 section = [sections objectForKey:key];
7199 if (section == nil) {
7200 _profile(SectionsView$reloadData$Section$Allocate)
7201 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
7202 [sections setObject:section forKey:key];
7207 [section addToCount];
7209 _profile(SectionsView$reloadData$Filter)
7210 if (![package valid] || ![package visible])
7218 [sections_ addObjectsFromArray:[sections allValues]];
7220 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7222 for (Section *section in sections_) {
7223 size_t count([section row]);
7227 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7228 [section setCount:count];
7229 [filtered_ addObject:section];
7232 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7233 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
7234 style:UIBarButtonItemStylePlain
7236 action:@selector(editButtonClicked)
7237 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7243 - (void) resetView {
7245 [self editButtonClicked];
7248 - (void)editButtonClicked {
7249 [self setEditing:!editing_];
7252 - (UIView *) accessoryView {
7258 /* Changes Controller {{{ */
7259 @interface ChangesController : CYViewController <
7260 UITableViewDataSource,
7263 _transient Database *database_;
7265 CFMutableArrayRef packages_;
7266 NSMutableArray *sections_;
7269 BOOL hasSentFirstLoad_;
7272 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
7273 - (void) reloadData;
7277 @implementation ChangesController
7280 [list_ setDelegate:nil];
7281 [list_ setDataSource:nil];
7283 CFRelease(packages_);
7285 [sections_ release];
7290 - (void) viewDidAppear:(BOOL)animated {
7291 [super viewDidAppear:animated];
7292 if (!hasSentFirstLoad_) {
7293 hasSentFirstLoad_ = YES;
7294 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7296 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7300 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7301 NSInteger count([sections_ count]);
7302 return count == 0 ? 1 : count;
7305 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7306 if ([sections_ count] == 0)
7308 return [[sections_ objectAtIndex:section] name];
7311 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7312 if ([sections_ count] == 0)
7314 return [[sections_ objectAtIndex:section] count];
7317 - (Package *) packageAtIndex:(NSUInteger)index {
7318 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7321 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7322 @synchronized (database_) {
7323 if ([database_ era] != era_)
7326 Section *section([sections_ objectAtIndex:[path section]]);
7327 NSInteger row([path row]);
7328 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7331 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7332 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7334 cell = [[[PackageCell alloc] init] autorelease];
7335 [cell setPackage:[self packageAtIndexPath:path]];
7339 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7340 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7343 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7344 Package *package([self packageAtIndexPath:path]);
7345 PackageController *view([delegate_ packageController]);
7346 [view setDelegate:delegate_];
7347 [view setPackage:package];
7348 [[self navigationController] pushViewController:view animated:YES];
7352 - (void) refreshButtonClicked {
7353 [delegate_ beginUpdate];
7354 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7357 - (void) upgradeButtonClicked {
7358 [delegate_ distUpgrade];
7361 - (NSString *) title { return UCLocalize("CHANGES"); }
7363 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7364 if ((self = [super init]) != nil) {
7365 database_ = database;
7366 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7368 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7370 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7372 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7373 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7374 [list_ setRowHeight:73.0f];
7375 [[self view] addSubview:list_];
7377 [list_ setDataSource:self];
7378 [list_ setDelegate:self];
7380 delegate_ = delegate;
7384 - (void) _reloadPackages:(NSArray *)packages {
7386 for (Package *package in packages)
7387 if ([package upgradableAndEssential:YES] || [package visible])
7388 CFArrayAppendValue(packages_, package);
7391 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7395 - (void) reloadData {
7396 era_ = [database_ era];
7397 NSArray *packages = [database_ packages];
7399 CFArrayRemoveAllValues(packages_);
7401 [sections_ removeAllObjects];
7404 UIProgressHUD *hud([delegate_ addProgressHUD]);
7405 [hud setText:UCLocalize("LOADING")];
7406 //NSLog(@"HUD:%@::%@", delegate_, hud);
7407 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7408 [delegate_ removeProgressHUD:hud];
7410 [self _reloadPackages:packages];
7413 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7414 Section *ignored = nil;
7415 Section *section = nil;
7419 bool unseens = false;
7421 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7423 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7424 Package *package = [self packageAtIndex:offset];
7426 BOOL uae = [package upgradableAndEssential:YES];
7430 time_t seen([package seen]);
7432 if (section == nil || last != seen) {
7436 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7439 _profile(ChangesController$reloadData$Allocate)
7440 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7441 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7442 [sections_ addObject:section];
7446 [section addToCount];
7447 } else if ([package ignored]) {
7448 if (ignored == nil) {
7449 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7451 [ignored addToCount];
7454 [upgradable addToCount];
7459 CFRelease(formatter);
7462 Section *last = [sections_ lastObject];
7463 size_t count = [last count];
7464 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7465 [sections_ removeLastObject];
7468 if ([ignored count] != 0)
7469 [sections_ insertObject:ignored atIndex:0];
7471 [sections_ insertObject:upgradable atIndex:0];
7476 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7477 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7478 style:UIBarButtonItemStylePlain
7480 action:@selector(upgradeButtonClicked)
7483 if (![delegate_ updating])
7484 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7485 initWithTitle:UCLocalize("REFRESH")
7486 style:UIBarButtonItemStylePlain
7488 action:@selector(refreshButtonClicked)
7494 /* Search Controller {{{ */
7495 @interface SearchController : FilteredPackageController <
7498 UISearchBar *search_;
7501 - (id) initWithDatabase:(Database *)database;
7502 - (void) reloadData;
7506 @implementation SearchController
7513 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7514 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7515 [search_ resignFirstResponder];
7519 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7520 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7524 - (NSString *) title { return nil; }
7526 - (id) initWithDatabase:(Database *)database {
7527 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7530 - (void)viewDidAppear:(BOOL)animated {
7531 [super viewDidAppear:animated];
7533 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7534 [search_ layoutSubviews];
7535 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7537 UITextField *textField;
7538 if ([search_ respondsToSelector:@selector(searchField)])
7539 textField = [search_ searchField];
7541 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7543 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7544 [search_ setDelegate:self];
7545 [textField setEnablesReturnKeyAutomatically:NO];
7546 [[self navigationItem] setTitleView:textField];
7550 - (void) _reloadData {
7553 - (void) reloadData {
7554 _profile(SearchController$reloadData)
7555 [packages_ reloadData];
7558 [packages_ resetCursor];
7561 - (void) didSelectPackage:(Package *)package {
7562 [search_ resignFirstResponder];
7563 [super didSelectPackage:package];
7568 /* Settings Controller {{{ */
7569 @interface CYPackageSettingsController : CYViewController <
7570 UITableViewDataSource,
7573 _transient Database *database_;
7576 UITableView *table_;
7577 UISwitch *subscribedSwitch_;
7578 UISwitch *ignoredSwitch_;
7579 UITableViewCell *subscribedCell_;
7580 UITableViewCell *ignoredCell_;
7583 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7587 @implementation CYPackageSettingsController
7591 if (package_ != nil)
7594 [subscribedSwitch_ release];
7595 [ignoredSwitch_ release];
7596 [subscribedCell_ release];
7597 [ignoredCell_ release];
7602 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7603 if (package_ == nil)
7609 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7610 if (package_ == nil)
7616 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7617 return UCLocalize("SHOW_ALL_CHANGES_EX");
7620 - (void) onSubscribed:(id)control {
7621 bool value([control isOn]);
7622 if (package_ == nil)
7624 if ([package_ setSubscribed:value])
7625 [delegate_ updateData];
7628 - (void) onIgnored:(id)control {
7629 // TODO: set Held state - possibly call out to dpkg, etc.
7632 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7633 if (package_ == nil)
7636 switch ([indexPath row]) {
7637 case 0: return subscribedCell_;
7638 case 1: return ignoredCell_;
7646 - (NSString *) title { return UCLocalize("SETTINGS"); }
7648 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7649 if ((self = [super init])) {
7650 database_ = database;
7651 name_ = [package retain];
7653 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7655 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7656 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7657 [[self view] addSubview:table_];
7659 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7660 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7661 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7663 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7664 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7665 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7667 subscribedCell_ = [[UITableViewCell alloc] init];
7668 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7669 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7670 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7672 ignoredCell_ = [[UITableViewCell alloc] init];
7673 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7674 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7675 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7677 [table_ setDataSource:self];
7678 [table_ setDelegate:self];
7683 - (void) reloadData {
7684 if (package_ != nil)
7685 [package_ autorelease];
7686 package_ = [database_ packageWithName:name_];
7687 if (package_ != nil) {
7689 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7690 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7693 [table_ reloadData];
7698 /* Signature Controller {{{ */
7699 @interface SignatureController : CYBrowserController {
7700 _transient Database *database_;
7704 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7708 @implementation SignatureController
7715 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7717 [super webView:view didClearWindowObject:window forFrame:frame];
7720 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7721 if ((self = [super init]) != nil) {
7722 database_ = database;
7723 package_ = [package retain];
7728 - (void) reloadData {
7729 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7735 /* Role Controller {{{ */
7736 @interface CYSettingsController : CYViewController <
7737 UITableViewDataSource,
7740 _transient Database *database_;
7741 // XXX: ok, "roledelegate_"?...
7742 _transient id roledelegate_;
7743 UITableView *table_;
7744 UISegmentedControl *segment_;
7748 - (void) showDoneButton;
7749 - (void) resizeSegmentedControl;
7753 @implementation CYSettingsController
7757 [container_ release];
7762 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7763 if ((self = [super init])) {
7764 database_ = database;
7765 roledelegate_ = delegate;
7767 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7769 NSArray *items = [NSArray arrayWithObjects:
7771 UCLocalize("HACKER"),
7772 UCLocalize("DEVELOPER"),
7774 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7775 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7776 [container_ addSubview:segment_];
7779 if ([Role_ isEqualToString:@"User"]) index = 0;
7780 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7781 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7783 [segment_ setSelectedSegmentIndex:index];
7784 [self showDoneButton];
7787 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7788 [self resizeSegmentedControl];
7790 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7791 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7792 [table_ setDelegate:self];
7793 [table_ setDataSource:self];
7794 [[self view] addSubview:table_];
7795 [table_ reloadData];
7799 - (void) resizeSegmentedControl {
7800 CGFloat width = [[self view] frame].size.width;
7801 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7804 - (void) viewWillAppear:(BOOL)animated {
7805 [super viewWillAppear:animated];
7807 [self resizeSegmentedControl];
7810 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7811 [self resizeSegmentedControl];
7814 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7815 [self resizeSegmentedControl];
7819 NSString *role(nil);
7821 switch ([segment_ selectedSegmentIndex]) {
7822 case 0: role = @"User"; break;
7823 case 1: role = @"Hacker"; break;
7824 case 2: role = @"Developer"; break;
7829 if (![role isEqualToString:Role_]) {
7830 bool rolling(Role_ == nil);
7833 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7837 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7841 [roledelegate_ loadData];
7843 [roledelegate_ updateData];
7847 - (void) segmentChanged:(UISegmentedControl *)control {
7848 [self showDoneButton];
7851 - (void) saveAndClose {
7854 [[self navigationItem] setRightBarButtonItem:nil];
7855 [[self navigationController] dismissModalViewControllerAnimated:YES];
7858 - (void) doneButtonClicked {
7859 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7860 [spinner startAnimating];
7861 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7862 [[self navigationItem] setRightBarButtonItem:spinItem];
7864 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7867 - (void) showDoneButton {
7868 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7869 initWithTitle:UCLocalize("DONE")
7870 style:UIBarButtonItemStyleDone
7872 action:@selector(doneButtonClicked)
7873 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7876 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7877 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7881 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7885 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7886 return nil; // This method is required by the protocol.
7889 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7891 return UCLocalize("ROLE_EX");
7893 return [NSString stringWithFormat:
7894 @"%@: %@\n%@: %@\n%@: %@",
7895 UCLocalize("USER"), UCLocalize("USER_EX"),
7896 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7897 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7902 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7903 return section == 3 ? 44.0f : 0;
7906 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7907 return section == 3 ? container_ : nil;
7912 /* Stash Controller {{{ */
7913 @interface CYStashController : CYViewController {
7914 // XXX: just delete these things
7915 _transient UIActivityIndicatorView *spinner_;
7916 _transient UILabel *status_;
7917 _transient UILabel *caption_;
7921 @implementation CYStashController
7923 if ((self = [super init])) {
7924 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7926 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7927 CGRect spinrect = [spinner_ frame];
7928 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7929 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7930 [spinner_ setFrame:spinrect];
7931 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7932 [[self view] addSubview:spinner_];
7933 [spinner_ startAnimating];
7936 captrect.size.width = [[self view] frame].size.width;
7937 captrect.size.height = 40.0f;
7938 captrect.origin.x = 0;
7939 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7940 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7941 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
7942 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7943 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7944 [caption_ setTextColor:[UIColor whiteColor]];
7945 [caption_ setBackgroundColor:[UIColor clearColor]];
7946 [caption_ setShadowColor:[UIColor blackColor]];
7947 [caption_ setTextAlignment:UITextAlignmentCenter];
7948 [[self view] addSubview:caption_];
7951 statusrect.size.width = [[self view] frame].size.width;
7952 statusrect.size.height = 30.0f;
7953 statusrect.origin.x = 0;
7954 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7955 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7956 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7957 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
7958 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7959 [status_ setTextColor:[UIColor whiteColor]];
7960 [status_ setBackgroundColor:[UIColor clearColor]];
7961 [status_ setShadowColor:[UIColor blackColor]];
7962 [status_ setTextAlignment:UITextAlignmentCenter];
7963 [[self view] addSubview:status_];
7967 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7968 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7983 @interface Cydia : UIApplication <
7984 ConfirmationControllerDelegate,
7985 ProgressControllerDelegate,
7987 UINavigationControllerDelegate,
7988 UITabBarControllerDelegate
7990 // XXX: evaluate all fields for _transient
7993 CYTabBarController *tabbar_;
7995 NSMutableArray *essential_;
7996 NSMutableArray *broken_;
7998 Database *database_;
8006 CYSectionsController *sections_;
8007 ChangesController *changes_;
8008 ManageController *manage_;
8009 SearchController *search_;
8010 SourceController *sources_;
8011 InstalledController *installed_;
8014 CYStashController *stash_;
8019 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
8020 - (void) setPage:(CYViewController *)page;
8023 // XXX: I hate prototypes
8024 - (id) queueBadgeController;
8028 static _finline void _setHomePage(Cydia *self) {
8029 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
8032 @implementation Cydia
8034 - (void) beginUpdate {
8035 [tabbar_ beginUpdate];
8039 return [tabbar_ updating];
8043 if ([broken_ count] != 0) {
8044 int count = [broken_ count];
8046 UIAlertView *alert = [[[UIAlertView alloc]
8047 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8048 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8050 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8051 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8054 [alert setContext:@"fixhalf"];
8056 } else if (!Ignored_ && [essential_ count] != 0) {
8057 int count = [essential_ count];
8059 UIAlertView *alert = [[[UIAlertView alloc]
8060 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8061 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8063 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8064 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8067 [alert setContext:@"upgrade"];
8072 - (void) _saveConfig {
8078 NSString *error(nil);
8080 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8082 NSError *error(nil);
8083 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8084 NSLog(@"failure to save metadata data: %@", error);
8089 NSLog(@"failure to serialize metadata: %@", error);
8094 - (void) _updateData {
8097 NSMutableSet *tabs([[[NSMutableSet alloc] initWithCapacity:10] autorelease]);
8099 [tabs addObject:[tabbar_ selectedViewController]];
8101 if (sections_ != nil)
8102 [tabs addObject:sections_];
8103 if (changes_ != nil)
8104 [tabs addObject:changes_];
8106 [tabs addObject:manage_];
8108 [tabs addObject:search_];
8109 if (sources_ != nil)
8110 [tabs addObject:sources_];
8111 if (installed_ != nil)
8112 [tabs addObject:installed_];
8114 for (CYNavigationController *tab in tabs)
8117 [queueDelegate_ queueStatusDidChange];
8118 [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8121 - (int)indexOfTabWithTag:(int)tag {
8123 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8124 if ([[controller tabBarItem] tag] == tag)
8132 - (void) _refreshIfPossible {
8133 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8135 bool recently = false;
8136 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8137 if (update != nil) {
8138 NSTimeInterval interval([update timeIntervalSinceNow]);
8139 if (interval <= 0 && interval > -(15*60))
8143 // Don't automatic refresh if:
8144 // - We already refreshed recently.
8145 // - We already auto-refreshed this launch.
8146 // - Auto-refresh is disabled.
8147 if (recently || loaded_ || ManualRefresh) {
8148 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8150 // If we are cancelling due to ManualRefresh or a recent refresh
8151 // we need to make sure it knows it's already loaded.
8155 // We are going to load, so remember that.
8159 SCNetworkReachabilityFlags flags; {
8160 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8161 SCNetworkReachabilityGetFlags(reachability, &flags);
8162 CFRelease(reachability);
8165 // XXX: this elaborate mess is what Apple is using to determine this? :(
8166 // XXX: do we care if the user has to intervene? maybe that's ok?
8168 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8169 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8170 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8171 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8172 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8173 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8177 // If we can reach the server, auto-refresh!
8179 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8184 - (void) refreshIfPossible {
8185 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8188 - (void) _reloadData {
8189 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8190 [hud setText:UCLocalize("RELOADING_DATA")];
8192 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8195 [self removeProgressHUD:hud];
8199 [essential_ removeAllObjects];
8200 [broken_ removeAllObjects];
8202 NSArray *packages([database_ packages]);
8203 for (Package *package in packages) {
8205 [broken_ addObject:package];
8206 if ([package upgradableAndEssential:NO]) {
8207 if ([package essential])
8208 [essential_ addObject:package];
8213 NSLog(@"changes:#%u", changes);
8215 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8218 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8219 [changesItem setBadgeValue:badge];
8220 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8221 [self setApplicationIconBadgeNumber:changes];
8224 [changesItem setBadgeValue:nil];
8225 [changesItem setAnimatedBadge:NO];
8226 [self setApplicationIconBadgeNumber:0];
8231 [self refreshIfPossible];
8234 - (void) updateData {
8243 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8244 _assert(file != NULL);
8246 for (NSString *key in [Sources_ allKeys]) {
8247 NSDictionary *source([Sources_ objectForKey:key]);
8249 fprintf(file, "%s %s %s\n",
8250 [[source objectForKey:@"Type"] UTF8String],
8251 [[source objectForKey:@"URI"] UTF8String],
8252 [[source objectForKey:@"Distribution"] UTF8String]
8260 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8261 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8263 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8264 [tabbar_ presentModalViewController:navigation animated:YES];
8267 detachNewThreadSelector:@selector(update_)
8270 title:UCLocalize("UPDATING_SOURCES")
8274 - (void) reloadData {
8275 @synchronized (self) {
8281 pkgProblemResolver *resolver = [database_ resolver];
8283 resolver->InstallProtect();
8284 if (!resolver->Resolve(true))
8289 if (![database_ prepare])
8292 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8293 [page setDelegate:self];
8294 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8295 [confirm_ setDelegate:self];
8298 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8299 [tabbar_ presentModalViewController:confirm_ animated:YES];
8305 @synchronized (self) {
8310 - (void) clearPackage:(Package *)package {
8311 @synchronized (self) {
8318 - (void) installPackages:(NSArray *)packages {
8319 @synchronized (self) {
8320 for (Package *package in packages)
8327 - (void) installPackage:(Package *)package {
8328 @synchronized (self) {
8335 - (void) removePackage:(Package *)package {
8336 @synchronized (self) {
8343 - (void) distUpgrade {
8344 @synchronized (self) {
8345 if (![database_ upgrade])
8352 @synchronized (self) {
8357 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8360 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8362 if (navigation != nil) {
8363 [navigation pushViewController:progress animated:YES];
8365 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8367 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8368 [tabbar_ presentModalViewController:navigation animated:YES];
8372 detachNewThreadSelector:@selector(perform)
8375 title:UCLocalize("RUNNING")
8381 - (void) progressControllerIsComplete:(ProgressController *)progress {
8386 - (void) setPage:(CYViewController *)page {
8387 [page setDelegate:self];
8389 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8390 [navController setViewControllers:[NSArray arrayWithObject:page]];
8391 for (CYNavigationController *page in [tabbar_ viewControllers])
8392 if (page != navController)
8393 [page setViewControllers:nil];
8396 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8397 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8398 [browser loadURL:url];
8402 - (CYSectionsController *) sectionsController {
8403 if (sections_ == nil)
8404 sections_ = [[CYSectionsController alloc] initWithDatabase:database_];
8408 - (ChangesController *) changesController {
8409 if (changes_ == nil)
8410 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8414 - (ManageController *) manageController {
8415 if (manage_ == nil) {
8416 manage_ = (ManageController *) [[self
8417 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8418 withClass:[ManageController class]
8421 queueDelegate_ = manage_;
8426 - (SearchController *) searchController {
8428 search_ = [[SearchController alloc] initWithDatabase:database_];
8432 - (SourceController *) sourcesController {
8433 if (sources_ == nil)
8434 sources_ = [[SourceController alloc] initWithDatabase:database_];
8438 - (InstalledController *) installedController {
8439 if (installed_ == nil) {
8440 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8442 queueDelegate_ = installed_;
8447 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8448 int tag = [[viewController tabBarItem] tag];
8450 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8452 } else if (tag_ == 1) {
8453 [[self sectionsController] resetView];
8457 case kCydiaTag: _setHomePage(self); break;
8459 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8460 case kChangesTag: [self setPage:[self changesController]]; break;
8461 case kManageTag: [self setPage:[self manageController]]; break;
8462 case kInstalledTag: [self setPage:[self installedController]]; break;
8463 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8464 case kSearchTag: [self setPage:[self searchController]]; break;
8472 - (void) showSettings {
8473 CYSettingsController *role = [[[CYSettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8474 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8476 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8477 [tabbar_ presentModalViewController:nav animated:YES];
8480 - (void) retainNetworkActivityIndicator {
8481 if (activity_++ == 0)
8482 [self setNetworkActivityIndicatorVisible:YES];
8485 - (void) releaseNetworkActivityIndicator {
8486 if (--activity_ == 0)
8487 [self setNetworkActivityIndicatorVisible:NO];
8490 - (void) setPackageController:(PackageController *)view {
8492 [view setPackage:nil];
8496 - (PackageController *) _packageController {
8497 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8500 - (PackageController *) packageController {
8501 return [self _packageController];
8504 // Returns the navigation controller for the queuing badge.
8505 - (id) queueBadgeController {
8506 int index = [self indexOfTabWithTag:kManageTag];
8508 index = [self indexOfTabWithTag:kInstalledTag];
8510 return [[tabbar_ viewControllers] objectAtIndex:index];
8513 - (void) cancelAndClear:(bool)clear {
8514 @synchronized (self) {
8526 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8527 NSString *context([alert context]);
8529 if ([context isEqualToString:@"fixhalf"]) {
8530 if (button == [alert firstOtherButtonIndex]) {
8531 @synchronized (self) {
8532 for (Package *broken in broken_) {
8535 NSString *id = [broken id];
8536 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8537 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8538 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8539 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8545 } else if (button == [alert cancelButtonIndex]) {
8546 [broken_ removeAllObjects];
8550 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8551 } else if ([context isEqualToString:@"upgrade"]) {
8552 if (button == [alert firstOtherButtonIndex]) {
8553 @synchronized (self) {
8554 for (Package *essential in essential_)
8555 [essential install];
8560 } else if (button == [alert firstOtherButtonIndex] + 1) {
8562 } else if (button == [alert cancelButtonIndex]) {
8566 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8570 - (void) system:(NSString *)command { _pooled
8572 system([command UTF8String]);
8576 - (void) applicationWillSuspend {
8578 [super applicationWillSuspend];
8581 - (BOOL) isSafeToSuspend {
8582 // Use external process status API internally.
8583 // This is probably a really bad idea.
8584 // XXX: what is the point of this? does this solve anything at all?
8585 uint64_t status = 0;
8587 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8588 notify_get_state(notify_token, &status);
8589 notify_cancel(notify_token);
8592 return locked_ == 0 && status == 0;
8595 - (void) applicationSuspend:(__GSEvent *)event {
8596 if ([self isSafeToSuspend])
8597 [super applicationSuspend:event];
8600 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8601 if ([self isSafeToSuspend])
8602 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8605 - (void) _setSuspended:(BOOL)value {
8606 if ([self isSafeToSuspend])
8607 [super _setSuspended:value];
8610 - (UIProgressHUD *) addProgressHUD {
8611 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8612 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8614 [window_ setUserInteractionEnabled:NO];
8617 UIViewController *target = tabbar_;
8618 while ([target modalViewController] != nil) target = [target modalViewController];
8619 [[target view] addSubview:hud];
8625 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8627 [hud removeFromSuperview];
8628 [window_ setUserInteractionEnabled:YES];
8632 - (CYViewController *) pageForPackage:(NSString *)name {
8633 if (Package *package = [database_ packageWithName:name]) {
8634 PackageController *view([self packageController]);
8635 [view setPackage:package];
8638 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8639 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8640 return [self _pageForURL:url withClass:[CYBrowserController class]];
8644 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8648 NSString *href([url absoluteString]);
8649 if ([href hasPrefix:@"apptapp://package/"])
8650 return [self pageForPackage:[href substringFromIndex:18]];
8652 NSString *scheme([[url scheme] lowercaseString]);
8653 if (![scheme isEqualToString:@"cydia"])
8655 NSString *path([url absoluteString]);
8656 if ([path length] < 8)
8658 path = [path substringFromIndex:8];
8659 if (![path hasPrefix:@"/"])
8660 path = [@"/" stringByAppendingString:path];
8662 if ([path isEqualToString:@"/storage"])
8663 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8664 /*else if ([path isEqualToString:@"/add-source"])
8665 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];*/
8666 else if ([path isEqualToString:@"/sources"])
8667 return [[[SourceController alloc] initWithDatabase:database_] autorelease];
8668 else if ([path isEqualToString:@"/packages"])
8669 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8670 else if ([path hasPrefix:@"/url/"])
8671 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8672 else if ([path hasPrefix:@"/launch/"])
8673 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8674 else if ([path hasPrefix:@"/package-settings/"])
8675 return [[[CYPackageSettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8676 else if ([path hasPrefix:@"/package-signature/"])
8677 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8678 else if ([path hasPrefix:@"/package/"])
8679 return [self pageForPackage:[path substringFromIndex:9]];
8680 else if ([path hasPrefix:@"/files/"]) {
8681 NSString *name = [path substringFromIndex:7];
8683 if (Package *package = [database_ packageWithName:name]) {
8684 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8685 [files setPackage:package];
8693 - (BOOL) openCydiaURL:(NSURL *)url {
8694 CYViewController *page = nil;
8697 NSLog(@"open url: %@", url);
8699 if ((page = [self pageForURL:url hasTag:&tag])) {
8700 [self setPage:page];
8702 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8708 - (void) applicationOpenURL:(NSURL *)url {
8709 [super applicationOpenURL:url];
8710 NSLog(@"first: %@", url);
8711 if (!loaded_) starturl_ = [url retain];
8712 else [self openCydiaURL:url];
8715 - (void) applicationWillResignActive:(UIApplication *)application {
8716 // Stop refreshing if you get a phone call or lock the device.
8717 if ([tabbar_ updating])
8718 [tabbar_ cancelUpdate];
8720 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8721 [super applicationWillResignActive:application];
8724 - (void) addStashController {
8726 stash_ = [[CYStashController alloc] init];
8727 [window_ addSubview:[stash_ view]];
8730 - (void) removeStashController {
8731 [[stash_ view] removeFromSuperview];
8737 [self setIdleTimerDisabled:YES];
8739 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8740 [self setStatusBarShowsProgress:YES];
8741 UpdateExternalStatus(1);
8743 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8745 UpdateExternalStatus(0);
8746 [self setStatusBarShowsProgress:NO];
8748 [self removeStashController];
8750 if (ExecFork() == 0) {
8751 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8752 perror("launchctl stop");
8756 - (void) setupTabBarController {
8757 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8758 [tabbar_ setDelegate:self];
8760 NSMutableArray *items([NSMutableArray arrayWithObjects:
8761 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8762 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8763 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8764 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8768 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8769 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8771 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8774 NSMutableArray *controllers([NSMutableArray array]);
8776 for (UITabBarItem *item in items) {
8777 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8778 [controller setTabBarItem:item];
8779 [controllers addObject:controller];
8782 [tabbar_ setViewControllers:controllers];
8785 - (void)showFakeTabBarInView:(UIView *)view {
8786 static UITabBar *fake = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
8788 CGRect frame = [fake frame];
8789 frame.origin.y = [view frame].size.height - frame.size.height;
8790 frame.size.width = [view frame].size.width;
8791 [fake setFrame:frame];
8792 [fake setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
8793 [view addSubview:fake];
8795 [fake removeFromSuperview];
8799 - (void) applicationDidFinishLaunching:(id)unused {
8803 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
8804 initWithMemoryCapacity:524288
8805 diskCapacity:10485760
8806 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
8809 [CYBrowserController _initialize];
8811 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8813 Font12_ = [[UIFont systemFontOfSize:12] retain];
8814 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8815 Font14_ = [[UIFont systemFontOfSize:14] retain];
8816 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8817 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8821 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8822 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8824 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
8825 [window_ orderFront:self];
8826 [window_ makeKey:self];
8827 [window_ setHidden:NO];
8830 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8831 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8832 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8833 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8834 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8835 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8836 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8837 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8838 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8841 [self addStashController];
8842 // XXX: this would be much cleaner as a yieldToSelector:
8843 // that way the removeStashController could happen right here inline
8844 // we also could no longer require the useless stash_ field anymore
8845 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8849 database_ = [Database sharedInstance];
8851 [self setupTabBarController];
8852 [tabbar_ setUpdateDelegate:self];
8853 [window_ addSubview:[tabbar_ view]];
8855 // Show pinstripes while loading data.
8856 [[tabbar_ view] setBackgroundColor:[UIColor pinStripeColor]];
8857 [self showFakeTabBarInView:[tabbar_ tabBar]];
8859 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8866 [self showSettings];
8870 [window_ setUserInteractionEnabled:NO];
8872 UIView *container = [[[UIView alloc] init] autorelease];
8873 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8875 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8876 [spinner startAnimating];
8877 [container addSubview:spinner];
8879 UILabel *label = [[[UILabel alloc] init] autorelease];
8880 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8881 [label setBackgroundColor:[UIColor clearColor]];
8882 [label setTextColor:[UIColor blackColor]];
8883 [label setShadowColor:[UIColor whiteColor]];
8884 [label setShadowOffset:CGSizeMake(0, 1)];
8885 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8886 [container addSubview:label];
8888 CGSize viewsize = [[tabbar_ view] frame].size;
8889 CGSize spinnersize = [spinner bounds].size;
8890 CGSize textsize = [[label text] sizeWithFont:[label font]];
8891 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8893 CGRect containrect = {
8894 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8895 CGSizeMake(bothwidth, spinnersize.height)
8898 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8906 [container setFrame:containrect];
8907 [spinner setFrame:spinrect];
8908 [label setFrame:textrect];
8909 [[tabbar_ view] addSubview:container];
8914 // Show the initial page
8915 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
8916 [tabbar_ setSelectedIndex:0];
8920 [self showFakeTabBarInView:nil];
8922 [starturl_ release];
8925 [window_ setUserInteractionEnabled:YES];
8927 // XXX: does this actually slow anything down?
8928 [[tabbar_ view] setBackgroundColor:[UIColor clearColor]];
8929 [container removeFromSuperview];
8932 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8933 if (item != nil && IsWildcat_) {
8934 [sheet showFromBarButtonItem:item animated:YES];
8936 [sheet showInView:window_];
8943 id Alloc_(id self, SEL selector) {
8944 id object = alloc_(self, selector);
8945 lprintf("[%s]A-%p\n", self->isa->name, object);
8950 id Dealloc_(id self, SEL selector) {
8951 id object = dealloc_(self, selector);
8952 lprintf("[%s]D-%p\n", self->isa->name, object);
8956 Class $WebDefaultUIKitDelegate;
8958 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8959 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8960 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8961 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8964 static NSNumber *shouldPlayKeyboardSounds;
8968 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8970 case 1104: // Keyboard Button Clicked
8971 case 1105: // Keyboard Delete Repeated
8972 if (shouldPlayKeyboardSounds == nil) {
8973 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8974 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8977 if (![shouldPlayKeyboardSounds boolValue])
8981 _UIHardware$_playSystemSound$(self, _cmd, sound);
8985 int main(int argc, char *argv[]) { _pooled
8988 if (Class $UIDevice = objc_getClass("UIDevice")) {
8989 UIDevice *device([$UIDevice currentDevice]);
8990 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8994 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8996 /* Library Hacks {{{ */
8997 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8999 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9000 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9001 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9002 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9003 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9006 $UIHardware = objc_getClass("UIHardware");
9007 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9008 if (UIHardware$_playSystemSound$ != NULL) {
9009 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9010 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9013 /* Set Locale {{{ */
9014 Locale_ = CFLocaleCopyCurrent();
9015 Languages_ = [NSLocale preferredLanguages];
9016 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9017 //NSLog(@"%@", [Languages_ description]);
9020 if (Languages_ == nil || [Languages_ count] == 0)
9021 // XXX: consider just setting to C and then falling through?
9024 lang = [[Languages_ objectAtIndex:0] UTF8String];
9025 setenv("LANG", lang, true);
9028 //std::setlocale(LC_ALL, lang);
9029 NSLog(@"Setting Language: %s", lang);
9032 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9034 /* Parse Arguments {{{ */
9035 bool substrate(false);
9041 for (int argi(1); argi != argc; ++argi)
9042 if (strcmp(argv[argi], "--") == 0) {
9044 argv[argi] = argv[0];
9050 for (int argi(1); argi != arge; ++argi)
9051 if (strcmp(args[argi], "--substrate") == 0)
9054 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9058 App_ = [[NSBundle mainBundle] bundlePath];
9059 Home_ = NSHomeDirectory();
9065 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9066 alloc_ = alloc->method_imp;
9067 alloc->method_imp = (IMP) &Alloc_;*/
9069 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9070 dealloc_ = dealloc->method_imp;
9071 dealloc->method_imp = (IMP) &Dealloc_;*/
9073 /* System Information {{{ */
9077 size = sizeof(maxproc);
9078 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9079 perror("sysctlbyname(\"kern.maxproc\", ?)");
9080 else if (maxproc < 64) {
9082 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9083 perror("sysctlbyname(\"kern.maxproc\", #)");
9086 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9087 char *osversion = new char[size];
9088 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9089 perror("sysctlbyname(\"kern.osversion\", ?)");
9091 System_ = [NSString stringWithUTF8String:osversion];
9093 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9094 char *machine = new char[size];
9095 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9096 perror("sysctlbyname(\"hw.machine\", ?)");
9100 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9101 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9102 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9103 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9107 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9108 NSData *data((NSData *) ecid);
9109 size_t length([data length]);
9110 uint8_t bytes[length];
9111 [data getBytes:bytes];
9112 char string[length * 2 + 1];
9113 for (size_t i(0); i != length; ++i)
9114 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9115 ChipID_ = [NSString stringWithUTF8String:string];
9119 IOObjectRelease(service);
9123 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9125 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9126 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9127 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9129 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9130 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9131 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9133 if (mcc != NULL && mnc != NULL)
9134 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9141 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9142 Build_ = [system objectForKey:@"ProductBuildVersion"];
9143 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9144 Product_ = [info objectForKey:@"SafariProductVersion"];
9145 Safari_ = [info objectForKey:@"CFBundleVersion"];
9148 /* Load Database {{{ */
9150 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9152 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9154 if (Metadata_ == NULL)
9155 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9157 Settings_ = [Metadata_ objectForKey:@"Settings"];
9159 Packages_ = [Metadata_ objectForKey:@"Packages"];
9160 Sections_ = [Metadata_ objectForKey:@"Sections"];
9161 Sources_ = [Metadata_ objectForKey:@"Sources"];
9163 Token_ = [Metadata_ objectForKey:@"Token"];
9166 if (Settings_ != nil)
9167 Role_ = [Settings_ objectForKey:@"Role"];
9169 if (Sections_ == nil) {
9170 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9171 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9174 if (Sources_ == nil) {
9175 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9176 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9181 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9184 if (Packages_ != nil) {
9185 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9187 [Metadata_ removeObjectForKey:@"Packages"];
9192 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9194 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9195 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9196 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9197 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9198 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9199 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9201 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9203 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9204 unlink("/tmp/.cydia.fw");
9206 } else if (access("/User", F_OK) != 0 || version < 2) {
9209 system("/usr/libexec/cydia/firmware.sh");
9213 _assert([[NSFileManager defaultManager]
9214 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9215 withIntermediateDirectories:YES
9220 if (access("/tmp/cydia.chk", F_OK) == 0) {
9221 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9222 _assert(errno == ENOENT);
9223 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9224 _assert(errno == ENOENT);
9227 /* APT Initialization {{{ */
9228 _assert(pkgInitConfig(*_config));
9229 _assert(pkgInitSystem(*_config, _system));
9232 _config->Set("APT::Acquire::Translation", lang);
9234 // XXX: this timeout might be important :(
9235 //_config->Set("Acquire::http::Timeout", 15);
9237 _config->Set("Acquire::http::MaxParallel", 3);
9239 /* Color Choices {{{ */
9240 space_ = CGColorSpaceCreateDeviceRGB();
9242 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9243 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9244 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9245 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9246 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9247 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9248 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9249 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9250 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9252 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9253 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9255 /* UIKit Configuration {{{ */
9256 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9257 if ($GSFontSetUseLegacyFontMetrics != NULL)
9258 $GSFontSetUseLegacyFontMetrics(YES);
9260 // XXX: I have a feeling this was important
9261 //UIKeyboardDisableAutomaticAppearance();
9264 Colon_ = UCLocalize("COLON_DELIMITED");
9265 Elision_ = UCLocalize("ELISION");
9266 Error_ = UCLocalize("ERROR");
9267 Warning_ = UCLocalize("WARNING");
9270 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9272 CGColorSpaceRelease(space_);