1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 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"
136 #define _timestamp ({ \
138 gettimeofday(&tv, NULL); \
139 tv.tv_sec * 1000000 + tv.tv_usec; \
142 typedef std::vector<class ProfileTime *> TimeList;
152 ProfileTime(const char *name) :
156 times_.push_back(this);
159 void AddTime(uint64_t time) {
166 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
178 ProfileTimer(ProfileTime &time) :
185 time_.AddTime(_timestamp - start_);
190 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
192 std::cerr << "========" << std::endl;
195 #define _profile(name) { \
196 static ProfileTime name(#name); \
197 ProfileTimer _ ## name(name);
202 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
204 #define CYPoolStart() \
205 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
207 #define CYPoolEnd() \
211 // Hash Functions/Structures {{{
212 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
220 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
222 static _finline NSString *CydiaURL(NSString *path) {
224 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
225 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
226 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
227 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
228 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
230 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
233 static _finline void UpdateExternalStatus(uint64_t newStatus) {
235 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
236 notify_set_state(notify_token, newStatus);
237 notify_cancel(notify_token);
239 notify_post("com.saurik.Cydia.status");
242 /* [NSObject yieldToSelector:(withObject:)] {{{*/
243 @interface NSObject (Cydia)
244 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
245 - (id) yieldToSelector:(SEL)selector;
248 @implementation NSObject (Cydia)
253 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
254 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
255 id object([[context objectAtIndex:1] nonretainedObjectValue]);
256 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
258 /* XXX: deal with exceptions */
259 id value([self performSelector:selector withObject:object]);
261 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
262 [context removeAllObjects];
263 if ([signature methodReturnLength] != 0 && value != nil)
264 [context addObject:value];
269 performSelectorOnMainThread:@selector(doNothing)
275 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
276 volatile bool stopped(false);
278 NSMutableArray *context([NSMutableArray arrayWithObjects:
279 [NSValue valueWithPointer:selector],
280 [NSValue valueWithNonretainedObject:object],
281 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
284 NSThread *thread([[[NSThread alloc]
286 selector:@selector(_yieldToContext:)
292 NSRunLoop *loop([NSRunLoop currentRunLoop]);
293 NSDate *future([NSDate distantFuture]);
294 NSString *mode([loop currentMode] ?: NSDefaultRunLoopMode);
296 while (!stopped && [loop runMode:mode beforeDate:future]);
298 return [context count] == 0 ? nil : [context objectAtIndex:0];
301 - (id) yieldToSelector:(SEL)selector {
302 return [self yieldToSelector:selector withObject:nil];
308 /* Cydia Alert View {{{ */
309 @interface CYAlertView : UIAlertView {
313 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
317 @implementation CYAlertView
319 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
320 if ((self = [super init]) != nil) {
321 [self setTitle:title];
322 [self setDelegate:self];
323 for (NSString *button in buttons) [self addButtonWithTitle:button];
324 [self setCancelButtonIndex:index];
328 - (void) _updateFrameForDisplay {
329 [super _updateFrameForDisplay];
330 if ([self cancelButtonIndex] == -1) {
331 NSArray *buttons = [self buttons];
332 if ([buttons count]) {
333 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
334 for (UIThreePartButton *button in buttons)
335 [button setBackground:background forState:0];
340 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
341 button_ = buttonIndex + 1;
345 [self dismissWithClickedButtonIndex:-1 animated:YES];
348 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
349 [self setRunsModal:YES];
358 /* NSForcedOrderingSearch doesn't work on the iPhone */
359 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
360 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
361 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
363 #define lprintf(args...) fprintf(stderr, args)
366 #define TraceLogging (1 && !ForRelease)
367 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
368 #define ProfileTimes (0 && !ForRelease)
369 #define ForSaurik (0 && !ForRelease)
370 #define LogBrowser (0 && !ForRelease)
371 #define TrackResize (0 && !ForRelease)
372 #define ManualRefresh (1 && !ForRelease)
373 #define ShowInternals (0 && !ForRelease)
374 #define AlwaysReload (0 && !ForRelease)
375 #define TryIndexedCollation (0 && !ForRelease)
379 #define _trace(args...)
384 #define _profile(name) {
387 #define PrintTimes() do {} while (false)
391 typedef uint32_t (*SKRadixFunction)(id, void *);
393 @interface NSMutableArray (Radix)
394 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
402 @implementation NSMutableArray (Radix)
404 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
405 size_t count([self count]);
406 struct RadixItem_ *swap(new RadixItem_[count * 2]);
408 for (size_t i(0); i != count; ++i) {
409 RadixItem_ &item(swap[i]);
412 id object([self objectAtIndex:i]);
413 item.key = function(object, argument);
416 struct RadixItem_ *lhs(swap), *rhs(swap + count);
418 static const size_t width = 32;
419 static const size_t bits = 11;
420 static const size_t slots = 1 << bits;
421 static const size_t passes = (width + (bits - 1)) / bits;
423 size_t *hist(new size_t[slots]);
425 for (size_t pass(0); pass != passes; ++pass) {
426 memset(hist, 0, sizeof(size_t) * slots);
428 for (size_t i(0); i != count; ++i) {
429 uint32_t key(lhs[i].key);
431 key &= _not(uint32_t) >> width - bits;
436 for (size_t i(0); i != slots; ++i) {
437 size_t local(offset);
442 for (size_t i(0); i != count; ++i) {
443 uint32_t key(lhs[i].key);
445 key &= _not(uint32_t) >> width - bits;
446 rhs[hist[key]++] = lhs[i];
449 RadixItem_ *tmp(lhs);
456 const void **values(new const void *[count]);
457 for (size_t i(0); i != count; ++i)
458 values[i] = [self objectAtIndex:lhs[i].index];
459 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
467 /* Insertion Sort {{{ */
469 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
470 const char *ptr = (const char *)list;
472 CFIndex half = count / 2;
473 const char *probe = ptr + elementSize * half;
474 CFComparisonResult cr = comparator(element, probe, context);
475 if (0 == cr) return (probe - (const char *)list) / elementSize;
476 ptr = (cr < 0) ? ptr : probe + elementSize;
477 count = (cr < 0) ? half : (half + (count & 1) - 1);
479 return (ptr - (const char *)list) / elementSize;
482 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
483 const char *ptr = (const char *)list;
485 CFIndex half = count / 2;
486 const char *probe = ptr + elementSize * half;
487 CFComparisonResult cr = comparator(element, probe, context);
488 if (0 == cr) return (probe - (const char *)list) / elementSize;
489 ptr = (cr < 0) ? ptr : probe + elementSize;
490 count = (cr < 0) ? half : (half + (count & 1) - 1);
492 return (ptr - (const char *)list) / elementSize;
495 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
496 if (range.length == 0)
498 const void **values(new const void *[range.length]);
499 CFArrayGetValues(array, range, values);
501 #if HistogramInsertionSort > 0
502 uint32_t total(0), *offsets(new uint32_t[range.length]);
505 for (CFIndex index(1); index != range.length; ++index) {
506 const void *value(values[index]);
507 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
508 CFIndex correct(index);
509 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
510 #if HistogramInsertionSort > 1
511 NSLog(@"%@ < %@", value, values[correct - 1]);
516 if (correct != index) {
517 size_t offset(index - correct);
518 #if HistogramInsertionSort
522 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
524 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
525 values[correct] = value;
529 CFArrayReplaceValues(array, range, values, range.length);
532 #if HistogramInsertionSort > 0
533 for (CFIndex index(0); index != range.length; ++index)
534 if (offsets[index] != 0)
535 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
536 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
543 /* Apple Bug Fixes {{{ */
544 @implementation UIWebDocumentView (Cydia)
546 - (void) _setScrollerOffset:(CGPoint)offset {
547 UIScroller *scroller([self _scroller]);
549 CGSize size([scroller contentSize]);
550 CGSize bounds([scroller bounds].size);
553 max.x = size.width - bounds.width;
554 max.y = size.height - bounds.height;
562 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
563 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
565 [scroller setOffset:offset];
571 @interface NSInvocation (Cydia)
572 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target;
575 @implementation NSInvocation (Cydia)
577 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target {
578 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
579 [invocation setTarget:target];
580 [invocation setSelector:selector];
586 @implementation WebScriptObject (NSFastEnumeration)
588 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
589 size_t length([self count] - state->state);
592 else if (length > count)
594 for (size_t i(0); i != length; ++i)
595 objects[i] = [self objectAtIndex:state->state++];
596 state->itemsPtr = objects;
597 state->mutationsPtr = (unsigned long *) self;
603 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
604 size_t length([self length] - state->state);
607 else if (length > count)
609 for (size_t i(0); i != length; ++i)
610 objects[i] = [self item:state->state++];
611 state->itemsPtr = objects;
612 state->mutationsPtr = (unsigned long *) self;
616 /* Cydia NSString Additions {{{ */
617 @interface NSString (Cydia)
618 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
619 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
620 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
621 - (NSComparisonResult) compareByPath:(NSString *)other;
622 - (NSString *) stringByCachingURLWithCurrentCDN;
623 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
626 @implementation NSString (Cydia)
628 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
629 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
632 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
633 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
634 memcpy(data, bytes, length);
635 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
638 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
639 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
642 - (NSComparisonResult) compareByPath:(NSString *)other {
643 NSString *prefix = [self commonPrefixWithString:other options:0];
644 size_t length = [prefix length];
646 NSRange lrange = NSMakeRange(length, [self length] - length);
647 NSRange rrange = NSMakeRange(length, [other length] - length);
649 lrange = [self rangeOfString:@"/" options:0 range:lrange];
650 rrange = [other rangeOfString:@"/" options:0 range:rrange];
652 NSComparisonResult value;
654 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
655 value = NSOrderedSame;
656 else if (lrange.location == NSNotFound)
657 value = NSOrderedAscending;
658 else if (rrange.location == NSNotFound)
659 value = NSOrderedDescending;
661 value = NSOrderedSame;
663 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
664 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
665 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
666 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
668 NSComparisonResult result = [lpath compare:rpath];
669 return result == NSOrderedSame ? value : result;
672 - (NSString *) stringByCachingURLWithCurrentCDN {
674 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
675 withString:@"://cache.cydia.saurik.com/"
679 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
680 return [(id)CFURLCreateStringByAddingPercentEscapes(
685 kCFStringEncodingUTF8
692 /* C++ NSString Wrapper Cache {{{ */
693 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
694 return size == 0 ? NULL :
695 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
696 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
699 static _finline CFStringRef CYStringCreate(const char *data) {
700 return CYStringCreate(data, strlen(data));
709 _finline void clear_() {
710 if (cache_ != NULL) {
717 _finline bool empty() const {
721 _finline size_t size() const {
725 _finline char *data() const {
729 _finline void clear() {
734 _finline CYString() :
741 _finline ~CYString() {
745 void operator =(const CYString &rhs) {
749 if (rhs.cache_ == nil)
752 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
755 void copy(apr_pool_t *pool) {
756 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
757 memcpy(temp, data_, size_);
762 void set(apr_pool_t *pool, const char *data, size_t size) {
768 data_ = const_cast<char *>(data);
776 _finline void set(apr_pool_t *pool, const char *data) {
777 set(pool, data, data == NULL ? 0 : strlen(data));
780 _finline void set(apr_pool_t *pool, const std::string &rhs) {
781 set(pool, rhs.data(), rhs.size());
784 bool operator ==(const CYString &rhs) const {
785 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
788 _finline operator CFStringRef() {
790 cache_ = CYStringCreate(data_, size_);
794 _finline operator id() {
795 return (NSString *) static_cast<CFStringRef>(*this);
798 _finline operator const char *() {
799 return reinterpret_cast<const char *>(data_);
803 /* C++ NSString Algorithm Adapters {{{ */
805 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
808 struct NSStringMapHash :
809 std::unary_function<NSString *, size_t>
811 _finline size_t operator ()(NSString *value) const {
812 return CFStringHashNSString((CFStringRef) value);
816 struct NSStringMapLess :
817 std::binary_function<NSString *, NSString *, bool>
819 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
820 return [lhs compare:rhs] == NSOrderedAscending;
824 struct NSStringMapEqual :
825 std::binary_function<NSString *, NSString *, bool>
827 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
828 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
829 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
830 //[lhs isEqualToString:rhs];
835 /* Perl-Compatible RegEx {{{ */
845 Pcre(const char *regex) :
850 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
853 lprintf("%d:%s\n", offset, error);
857 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
858 matches_ = new int[(capture_ + 1) * 3];
866 NSString *operator [](size_t match) {
867 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
870 bool operator ()(NSString *data) {
871 // XXX: length is for characters, not for bytes
872 return operator ()([data UTF8String], [data length]);
875 bool operator ()(const char *data, size_t size) {
877 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
881 /* Mime Addresses {{{ */
882 @interface Address : NSObject {
888 - (NSString *) address;
890 - (void) setAddress:(NSString *)address;
892 + (Address *) addressWithString:(NSString *)string;
893 - (Address *) initWithString:(NSString *)string;
897 @implementation Address
906 - (NSString *) name {
910 - (NSString *) address {
914 - (void) setAddress:(NSString *)address {
916 [address_ autorelease];
920 address_ = [address retain];
923 + (Address *) addressWithString:(NSString *)string {
924 return [[[Address alloc] initWithString:string] autorelease];
927 + (NSArray *) _attributeKeys {
928 return [NSArray arrayWithObjects:
934 - (NSArray *) attributeKeys {
935 return [[self class] _attributeKeys];
938 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
939 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
942 - (Address *) initWithString:(NSString *)string {
943 if ((self = [super init]) != nil) {
944 const char *data = [string UTF8String];
945 size_t size = [string length];
947 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
949 if (address_r(data, size)) {
950 name_ = [address_r[1] retain];
951 address_ = [address_r[2] retain];
953 name_ = [string retain];
961 /* CoreGraphics Primitives {{{ */
966 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
967 CGFloat color[] = {red, green, blue, alpha};
968 return CGColorCreate(space, color);
977 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
978 color_(Create_(space, red, green, blue, alpha))
980 Set(space, red, green, blue, alpha);
985 CGColorRelease(color_);
992 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
994 color_ = Create_(space, red, green, blue, alpha);
997 operator CGColorRef() {
1003 /* Random Global Variables {{{ */
1004 static const int PulseInterval_ = 50000;
1006 static const NSString *UI_;
1009 static bool RestartSubstrate_;
1010 static NSArray *Finishes_;
1012 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1013 #define NotifyConfig_ "/etc/notify.conf"
1015 static bool Queuing_;
1017 static CYColor Blue_;
1018 static CYColor Blueish_;
1019 static CYColor Black_;
1020 static CYColor Off_;
1021 static CYColor White_;
1022 static CYColor Gray_;
1023 static CYColor Green_;
1024 static CYColor Purple_;
1025 static CYColor Purplish_;
1027 static UIColor *InstallingColor_;
1028 static UIColor *RemovingColor_;
1030 static NSString *App_;
1031 static NSString *Home_;
1033 static BOOL Advanced_;
1034 static BOOL Ignored_;
1036 static UIFont *Font12_;
1037 static UIFont *Font12Bold_;
1038 static UIFont *Font14_;
1039 static UIFont *Font18Bold_;
1040 static UIFont *Font22Bold_;
1042 static const char *Machine_ = NULL;
1043 static NSString *System_ = nil;
1044 static NSString *SerialNumber_ = nil;
1045 static NSString *ChipID_ = nil;
1046 static _H<NSString> Token_;
1047 static NSString *UniqueID_ = nil;
1048 static NSString *PLMN_ = nil;
1049 static NSString *Build_ = nil;
1050 static NSString *Product_ = nil;
1051 static NSString *Safari_ = nil;
1053 static CFLocaleRef Locale_;
1054 static NSArray *Languages_;
1055 static CGColorSpaceRef space_;
1057 static NSDictionary *SectionMap_;
1058 static NSMutableDictionary *Metadata_;
1059 static _transient NSMutableDictionary *Settings_;
1060 static _transient NSString *Role_;
1061 static _transient NSMutableDictionary *Packages_;
1062 static _transient NSMutableDictionary *Sections_;
1063 static _transient NSMutableDictionary *Sources_;
1064 static bool Changed_;
1068 static CGFloat ScreenScale_;
1071 /* Display Helpers {{{ */
1072 inline float Interpolate(float begin, float end, float fraction) {
1073 return (end - begin) * fraction + begin;
1076 static _finline const char *StripVersion_(const char *version) {
1077 const char *colon(strchr(version, ':'));
1078 return colon == NULL ? version : colon + 1;
1081 NSString *LocalizeSection(NSString *section) {
1082 static Pcre title_r("^(.*?) \\((.*)\\)$");
1083 if (title_r(section)) {
1084 NSString *parent(title_r[1]);
1085 NSString *child(title_r[2]);
1087 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1088 LocalizeSection(parent),
1089 LocalizeSection(child)
1093 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1096 NSString *Simplify(NSString *title) {
1097 const char *data = [title UTF8String];
1098 size_t size = [title length];
1100 static Pcre square_r("^\\[(.*)\\]$");
1101 if (square_r(data, size))
1102 return Simplify(square_r[1]);
1104 static Pcre paren_r("^\\((.*)\\)$");
1105 if (paren_r(data, size))
1106 return Simplify(paren_r[1]);
1108 static Pcre title_r("^(.*?) \\((.*)\\)$");
1109 if (title_r(data, size))
1110 return Simplify(title_r[1]);
1116 NSString *GetLastUpdate() {
1117 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1120 return UCLocalize("NEVER_OR_UNKNOWN");
1122 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1123 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1125 CFRelease(formatter);
1127 return [(NSString *) formatted autorelease];
1130 bool isSectionVisible(NSString *section) {
1131 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1132 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1133 return hidden == nil || ![hidden boolValue];
1138 /* Delegate Prototypes {{{ */
1141 @class CydiaProgressEvent;
1143 @protocol DatabaseDelegate
1144 - (void) repairWithSelector:(SEL)selector;
1145 - (void) setConfigurationData:(NSString *)data;
1146 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1149 @class CYPackageController;
1151 @protocol CydiaDelegate
1152 - (void) retainNetworkActivityIndicator;
1153 - (void) releaseNetworkActivityIndicator;
1154 - (void) clearPackage:(Package *)package;
1155 - (void) installPackage:(Package *)package;
1156 - (void) installPackages:(NSArray *)packages;
1157 - (void) removePackage:(Package *)package;
1158 - (void) beginUpdate;
1160 - (void) distUpgrade;
1162 - (void) updateData;
1164 - (void) addTrivialSource:(NSString *)href;
1165 - (void) showSettings;
1166 - (UIProgressHUD *) addProgressHUD;
1167 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1168 - (CYViewController *) pageForPackage:(NSString *)name;
1169 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1170 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1174 /* ProgressEvent Interface/Delegate {{{ */
1175 @interface CydiaProgressEvent : NSObject {
1176 _H<NSString> message_;
1180 _H<NSString> package_;
1182 _H<NSString> version_;
1185 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1186 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1187 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1189 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1191 - (NSString *) message;
1192 - (NSString *) type;
1195 - (NSString *) package;
1197 - (NSString *) version;
1199 - (void) setItem:(NSArray *)item;
1200 - (void) setPackage:(NSString *)package;
1201 - (void) setURL:(NSString *)url;
1202 - (void) setVersion:(NSString *)version;
1204 - (NSString *) compound:(NSString *)value;
1205 - (NSString *) compoundMessage;
1206 - (NSString *) compoundTitle;
1210 @protocol ProgressDelegate
1211 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1212 - (void) setProgressPercent:(NSNumber *)percent;
1213 - (void) setProgressCancellable:(NSNumber *)cancellable;
1214 - (bool) isProgressCancelled;
1215 - (void) setTitle:(NSString *)title;
1218 /* Status Delegation {{{ */
1220 public pkgAcquireStatus
1223 _transient NSObject<ProgressDelegate> *delegate_;
1233 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1234 delegate_ = delegate;
1237 NSObject<ProgressDelegate> *getDelegate() const {
1241 virtual bool MediaChange(std::string media, std::string drive) {
1245 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1248 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1249 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1250 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:@"STATUS" forItem:item]);
1251 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1254 virtual void Done(pkgAcquire::ItemDesc &item) {
1257 virtual void Fail(pkgAcquire::ItemDesc &item) {
1259 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1260 item.Owner->Status == pkgAcquire::Item::StatDone
1264 std::string &error(item.Owner->ErrorText);
1268 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:@"ERROR" forItem:item]);
1269 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1272 virtual bool Pulse(pkgAcquire *Owner) {
1273 bool value = pkgAcquireStatus::Pulse(Owner);
1276 double(CurrentBytes + CurrentItems) /
1277 double(TotalBytes + TotalItems)
1280 [delegate_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:percent] waitUntilDone:YES];
1281 if (value && ![delegate_ isProgressCancelled])
1289 _finline bool WasCancelled() const {
1293 virtual void Start() {
1294 pkgAcquireStatus::Start();
1295 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1298 virtual void Stop() {
1299 pkgAcquireStatus::Stop();
1300 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1304 /* Database Interface {{{ */
1305 typedef std::map< unsigned long, _H<Source> > SourceMap;
1307 @interface Database : NSObject {
1313 pkgCacheFile cache_;
1314 pkgDepCache::Policy *policy_;
1315 pkgRecords *records_;
1316 pkgProblemResolver *resolver_;
1317 pkgAcquire *fetcher_;
1319 SPtr<pkgPackageManager> manager_;
1320 pkgSourceList *list_;
1322 SourceMap sourceMap_;
1323 NSMutableArray *sourceList_;
1325 CFMutableArrayRef packages_;
1327 _transient NSObject<DatabaseDelegate> *delegate_;
1328 _transient NSObject<ProgressDelegate> *progress_;
1336 std::map<const char *, _H<NSString> > sections_;
1339 + (Database *) sharedInstance;
1342 - (void) _readCydia:(NSNumber *)fd;
1343 - (void) _readStatus:(NSNumber *)fd;
1344 - (void) _readOutput:(NSNumber *)fd;
1348 - (Package *) packageWithName:(NSString *)name;
1350 - (pkgCacheFile &) cache;
1351 - (pkgDepCache::Policy *) policy;
1352 - (pkgRecords *) records;
1353 - (pkgProblemResolver *) resolver;
1354 - (pkgAcquire &) fetcher;
1355 - (pkgSourceList &) list;
1356 - (NSArray *) packages;
1357 - (NSArray *) sources;
1358 - (Source *) sourceWithKey:(NSString *)key;
1359 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1367 - (void) updateWithStatus:(Status &)status;
1369 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1371 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1372 - (NSObject<ProgressDelegate> *) progressDelegate;
1374 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1376 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1380 /* ProgressEvent Implementation {{{ */
1381 @implementation CydiaProgressEvent
1383 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1384 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1387 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1388 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1389 [event setPackage:package];
1393 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1394 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1396 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1397 NSArray *fields([description componentsSeparatedByString:@" "]);
1398 [event setItem:fields];
1400 if ([fields count] > 3) {
1401 [event setPackage:[fields objectAtIndex:2]];
1402 [event setVersion:[fields objectAtIndex:3]];
1405 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1410 + (NSArray *) _attributeKeys {
1411 return [NSArray arrayWithObjects:
1421 - (NSArray *) attributeKeys {
1422 return [[self class] _attributeKeys];
1425 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1426 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1429 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1430 if ((self = [super init]) != nil) {
1436 - (NSString *) message {
1440 - (NSString *) type {
1444 - (NSArray *) item {
1445 return (id) item_ ?: [NSNull null];
1448 - (void) setItem:(NSArray *)item {
1452 - (NSString *) package {
1453 return (id) package_ ?: [NSNull null];
1456 - (void) setPackage:(NSString *)package {
1460 - (NSString *) url {
1461 return (id) url_ ?: [NSNull null];
1464 - (void) setURL:(NSString *)url {
1468 - (void) setVersion:(NSString *)version {
1472 - (NSString *) version {
1473 return (id) version_ ?: [NSNull null];
1476 - (NSString *) compound:(NSString *)value {
1478 NSString *mode(nil); {
1479 NSString *type([self type]);
1480 if ([type isEqualToString:@"ERROR"])
1481 mode = UCLocalize("ERROR");
1482 else if ([type isEqualToString:@"WARNING"])
1483 mode = UCLocalize("WARNING");
1487 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1493 - (NSString *) compoundMessage {
1494 return [self compound:[self message]];
1497 - (NSString *) compoundTitle {
1500 if (package_ == nil)
1502 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1503 title = [package name];
1507 return [self compound:title];
1513 // Cytore Definitions {{{
1514 struct PackageValue :
1517 Cytore::Offset<PackageValue> next_;
1519 uint32_t index_ : 23;
1520 uint32_t subscribed_ : 1;
1537 Cytore::Offset<PackageValue> packages_[1 << 16];
1540 static Cytore::File<MetaValue> MetaFile_;
1542 // Cytore Helper Functions {{{
1543 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1544 SplitHash nhash = { hashlittle(name, length) };
1546 PackageValue *metadata;
1548 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1549 offset: if (offset->IsNull()) {
1550 *offset = MetaFile_.New<PackageValue>(length + 1);
1551 metadata = &MetaFile_.Get(*offset);
1553 if (metadata == NULL) {
1557 metadata = new PackageValue();
1558 memset(metadata, 0, sizeof(*metadata));
1561 memcpy(metadata->name_, name, length + 1);
1562 metadata->nhash_ = nhash.u16[1];
1564 metadata = &MetaFile_.Get(*offset);
1566 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1567 offset = &metadata->next_;
1575 static void PackageImport(const void *key, const void *value, void *context) {
1576 bool &fail(*reinterpret_cast<bool *>(context));
1579 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1580 NSLog(@"failed to import package %@", key);
1584 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1585 NSDictionary *package((NSDictionary *) value);
1587 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1588 if ([subscribed boolValue] && !metadata->subscribed_)
1589 metadata->subscribed_ = true;
1591 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1592 time_t time([date timeIntervalSince1970]);
1593 if (metadata->first_ > time || metadata->first_ == 0)
1594 metadata->first_ = time;
1597 NSDate *date([package objectForKey:@"LastSeen"]);
1598 NSString *version([package objectForKey:@"LastVersion"]);
1600 if (date != nil && version != nil) {
1601 time_t time([date timeIntervalSince1970]);
1602 if (metadata->last_ < time || metadata->last_ == 0)
1603 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1604 size_t length(strlen(buffer));
1605 uint16_t vhash(hashlittle(buffer, length));
1607 size_t capped(std::min<size_t>(8, length));
1608 char *latest(buffer + length - capped);
1610 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1611 metadata->vhash_ = vhash;
1613 metadata->last_ = time;
1619 /* Source Class {{{ */
1620 @interface Source : NSObject {
1621 CYString depiction_;
1622 CYString description_;
1628 CYString distribution_;
1633 NSString *authority_;
1635 CYString defaultIcon_;
1637 NSDictionary *record_;
1641 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1643 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1645 - (NSString *) depictionForPackage:(NSString *)package;
1646 - (NSString *) supportForPackage:(NSString *)package;
1648 - (NSDictionary *) record;
1652 - (NSString *) distribution;
1653 - (NSString *) type;
1655 - (NSString *) host;
1657 - (NSString *) name;
1658 - (NSString *) description;
1659 - (NSString *) label;
1660 - (NSString *) origin;
1661 - (NSString *) version;
1663 - (NSString *) defaultIcon;
1667 @implementation Source
1671 distribution_.clear();
1674 description_.clear();
1680 defaultIcon_.clear();
1682 if (record_ != nil) {
1692 if (authority_ != nil) {
1693 [authority_ release];
1699 // XXX: this is a very inefficient way to call these deconstructors
1704 + (NSArray *) _attributeKeys {
1705 return [NSArray arrayWithObjects:
1720 - (NSArray *) attributeKeys {
1721 return [[self class] _attributeKeys];
1724 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1725 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1728 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1731 trusted_ = index->IsTrusted();
1733 uri_.set(pool, index->GetURI());
1734 distribution_.set(pool, index->GetDist());
1735 type_.set(pool, index->GetType());
1737 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1738 if (dindex != NULL) {
1740 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1743 pkgTagFile tags(&fd);
1745 pkgTagSection section;
1752 {"default-icon", &defaultIcon_},
1753 {"depiction", &depiction_},
1754 {"description", &description_},
1756 {"origin", &origin_},
1757 {"support", &support_},
1758 {"version", &version_},
1761 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1762 const char *start, *end;
1764 if (section.Find(names[i].name_, start, end)) {
1765 CYString &value(*names[i].value_);
1766 value.set(pool, start, end - start);
1772 record_ = [Sources_ objectForKey:[self key]];
1774 record_ = [record_ retain];
1776 NSURL *url([NSURL URLWithString:uri_]);
1780 host_ = [[host_ lowercaseString] retain];
1785 authority_ = [url path];
1787 if (authority_ != nil)
1788 authority_ = [authority_ retain];
1791 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1792 if ((self = [super init]) != nil) {
1793 [self setMetaIndex:index inPool:pool];
1797 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1798 NSDictionary *lhr = [self record];
1799 NSDictionary *rhr = [source record];
1802 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1804 NSString *lhs = [self name];
1805 NSString *rhs = [source name];
1807 if ([lhs length] != 0 && [rhs length] != 0) {
1808 unichar lhc = [lhs characterAtIndex:0];
1809 unichar rhc = [rhs characterAtIndex:0];
1811 if (isalpha(lhc) && !isalpha(rhc))
1812 return NSOrderedAscending;
1813 else if (!isalpha(lhc) && isalpha(rhc))
1814 return NSOrderedDescending;
1817 return [lhs compare:rhs options:LaxCompareOptions_];
1820 - (NSString *) depictionForPackage:(NSString *)package {
1821 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1824 - (NSString *) supportForPackage:(NSString *)package {
1825 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1828 - (NSDictionary *) record {
1836 - (NSString *) uri {
1840 - (NSString *) distribution {
1841 return distribution_;
1844 - (NSString *) type {
1848 - (NSString *) key {
1849 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1852 - (NSString *) host {
1856 - (NSString *) name {
1857 return origin_.empty() ? authority_ : origin_;
1860 - (NSString *) description {
1861 return description_;
1864 - (NSString *) label {
1865 return label_.empty() ? authority_ : label_;
1868 - (NSString *) origin {
1872 - (NSString *) version {
1876 - (NSString *) defaultIcon {
1877 return defaultIcon_;
1882 /* CydiaOperation Class {{{ */
1883 @interface CydiaOperation : NSObject {
1884 NSString *operator_;
1888 - (NSString *) operator;
1889 - (NSString *) value;
1893 @implementation CydiaOperation
1896 [operator_ release];
1901 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1902 if ((self = [super init]) != nil) {
1903 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1904 value_ = [[NSString alloc] initWithUTF8String:value];
1908 + (NSArray *) _attributeKeys {
1909 return [NSArray arrayWithObjects:
1915 - (NSArray *) attributeKeys {
1916 return [[self class] _attributeKeys];
1919 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1920 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1923 - (NSString *) operator {
1927 - (NSString *) value {
1933 /* CydiaClause Class {{{ */
1934 @interface CydiaClause : NSObject {
1936 CydiaOperation *version_;
1939 - (NSString *) package;
1940 - (CydiaOperation *) version;
1944 @implementation CydiaClause
1952 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1953 if ((self = [super init]) != nil) {
1954 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1956 if (const char *version = dep.TargetVer())
1957 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1959 version_ = [[NSNull null] retain];
1963 + (NSArray *) _attributeKeys {
1964 return [NSArray arrayWithObjects:
1970 - (NSArray *) attributeKeys {
1971 return [[self class] _attributeKeys];
1974 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1975 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1978 - (NSString *) package {
1982 - (CydiaOperation *) version {
1988 /* CydiaRelation Class {{{ */
1989 @interface CydiaRelation : NSObject {
1990 NSString *relationship_;
1991 NSMutableArray *clauses_;
1994 - (NSString *) relationship;
1995 - (NSArray *) clauses;
1999 @implementation CydiaRelation
2002 [relationship_ release];
2007 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2008 if ((self = [super init]) != nil) {
2009 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
2010 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
2012 pkgCache::DepIterator start;
2013 pkgCache::DepIterator end;
2014 dep.GlobOr(start, end); // ++dep
2017 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2019 // yes, seriously. (wtf?)
2027 + (NSArray *) _attributeKeys {
2028 return [NSArray arrayWithObjects:
2034 - (NSArray *) attributeKeys {
2035 return [[self class] _attributeKeys];
2038 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2039 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2042 - (NSString *) relationship {
2043 return relationship_;
2046 - (NSArray *) clauses {
2050 - (void) addClause:(CydiaClause *)clause {
2051 [clauses_ addObject:clause];
2056 /* Package Class {{{ */
2057 struct ParsedPackage {
2062 CYString depiction_;
2072 @interface Package : NSObject {
2075 uint32_t essential_ : 1;
2076 uint32_t obsolete_ : 1;
2077 uint32_t ignored_ : 1;
2081 _transient Database *database_;
2083 pkgCache::VerIterator version_;
2084 pkgCache::PkgIterator iterator_;
2085 pkgCache::VerFileIterator file_;
2091 CYString installed_;
2093 const char *section_;
2094 _transient NSString *section$_;
2098 PackageValue *metadata_;
2099 ParsedPackage *parsed_;
2101 NSMutableArray *tags_;
2104 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2105 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2107 - (pkgCache::PkgIterator) iterator;
2110 - (NSString *) section;
2111 - (NSString *) simpleSection;
2113 - (NSString *) longSection;
2114 - (NSString *) shortSection;
2118 - (Address *) maintainer;
2120 - (NSString *) longDescription;
2121 - (NSString *) shortDescription;
2124 - (PackageValue *) metadata;
2127 - (bool) subscribed;
2128 - (bool) setSubscribed:(bool)subscribed;
2132 - (NSString *) latest;
2133 - (NSString *) installed;
2134 - (BOOL) uninstalled;
2137 - (BOOL) upgradableAndEssential:(BOOL)essential;
2140 - (BOOL) unfiltered;
2144 - (BOOL) halfConfigured;
2145 - (BOOL) halfInstalled;
2147 - (NSString *) mode;
2150 - (NSString *) name;
2152 - (NSString *) homepage;
2153 - (NSString *) depiction;
2154 - (Address *) author;
2156 - (NSString *) support;
2158 - (NSArray *) files;
2159 - (NSArray *) warnings;
2160 - (NSArray *) applications;
2162 - (Source *) source;
2164 - (BOOL) matches:(NSString *)text;
2166 - (bool) hasSupportingRole;
2167 - (BOOL) hasTag:(NSString *)tag;
2168 - (NSString *) primaryPurpose;
2169 - (NSArray *) purposes;
2170 - (bool) isCommercial;
2172 - (void) setIndex:(size_t)index;
2174 - (CYString &) cyname;
2176 - (uint32_t) compareBySection:(NSArray *)sections;
2181 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2182 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2183 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2184 - (bool) isVisibleInSection:(NSString *)section;
2185 - (bool) isVisibleInSource:(Source *)source;
2189 uint32_t PackageChangesRadix(Package *self, void *) {
2194 uint32_t timestamp : 30;
2195 uint32_t ignored : 1;
2196 uint32_t upgradable : 1;
2200 bool upgradable([self upgradableAndEssential:YES]);
2201 value.bits.upgradable = upgradable ? 1 : 0;
2204 value.bits.timestamp = 0;
2205 value.bits.ignored = [self ignored] ? 0 : 1;
2206 value.bits.upgradable = 1;
2208 value.bits.timestamp = [self seen] >> 2;
2209 value.bits.ignored = 0;
2210 value.bits.upgradable = 0;
2213 return _not(uint32_t) - value.key;
2216 uint32_t PackagePrefixRadix(Package *self, void *context) {
2217 size_t offset(reinterpret_cast<size_t>(context));
2218 CYString &name([self cyname]);
2220 size_t size(name.size());
2223 char *text(name.data());
2226 if (!isdigit(text[0]))
2230 while (size != digits && isdigit(text[digits]))
2238 if (offset == 0 && zeros != 0) {
2239 memset(data, '0', zeros);
2240 memcpy(data + zeros, text, 4 - zeros);
2242 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2243 if (size <= offset - zeros)
2246 text += offset - zeros;
2247 size -= offset - zeros;
2250 memcpy(data, text, 4);
2252 memcpy(data, text, size);
2253 memset(data + size, 0, 4 - size);
2256 for (size_t i(0); i != 4; ++i)
2257 if (isalpha(data[i]))
2265 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2267 /* XXX: ntohl may be more honest */
2268 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2271 CYString &(*PackageName)(Package *self, SEL sel);
2273 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2274 _profile(PackageNameCompare)
2275 CYString &lhi(PackageName(lhs, @selector(cyname)));
2276 CYString &rhi(PackageName(rhs, @selector(cyname)));
2277 CFStringRef lhn(lhi), rhn(rhi);
2280 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2281 else if (rhn == NULL)
2282 return NSOrderedDescending;
2284 _profile(PackageNameCompare$NumbersLast)
2285 if (!lhi.empty() && !rhi.empty()) {
2286 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2287 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2288 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2289 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2290 return lha ? NSOrderedAscending : NSOrderedDescending;
2294 CFIndex length = CFStringGetLength(lhn);
2296 _profile(PackageNameCompare$Compare)
2297 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2302 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2303 return PackageNameCompare(*lhs, *rhs, context);
2306 struct PackageNameOrdering :
2307 std::binary_function<Package *, Package *, bool>
2309 _finline bool operator ()(Package *lhs, Package *rhs) const {
2310 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2314 @implementation Package
2316 - (NSString *) description {
2317 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2321 if (parsed_ != NULL)
2330 + (NSString *) webScriptNameForSelector:(SEL)selector {
2332 else if (selector == @selector(clear))
2334 else if (selector == @selector(getField:))
2336 else if (selector == @selector(hasTag:))
2338 else if (selector == @selector(install))
2340 else if (selector == @selector(remove))
2346 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2347 return [self webScriptNameForSelector:selector] == nil;
2350 + (NSArray *) _attributeKeys {
2351 return [NSArray arrayWithObjects:
2369 @"shortDescription",
2380 - (NSArray *) attributeKeys {
2381 return [[self class] _attributeKeys];
2384 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2385 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2388 - (NSArray *) relations {
2389 @synchronized (database_) {
2390 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2391 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2392 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2396 - (NSString *) getField:(NSString *)name {
2397 @synchronized (database_) {
2398 if ([database_ era] != era_ || file_.end())
2401 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2403 const char *start, *end;
2404 if (!parser.Find([name UTF8String], start, end))
2405 return (NSString *) [NSNull null];
2407 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2411 if (parsed_ != NULL)
2413 @synchronized (database_) {
2414 if ([database_ era] != era_ || file_.end())
2417 ParsedPackage *parsed(new ParsedPackage);
2420 _profile(Package$parse)
2421 pkgRecords::Parser *parser;
2423 _profile(Package$parse$Lookup)
2424 parser = &[database_ records]->Lookup(file_);
2429 _profile(Package$parse$Find)
2434 {"icon", &parsed->icon_},
2435 {"depiction", &parsed->depiction_},
2436 {"homepage", &parsed->homepage_},
2437 {"website", &website},
2438 {"bugs", &parsed->bugs_},
2439 {"support", &parsed->support_},
2440 {"sponsor", &parsed->sponsor_},
2441 {"author", &parsed->author_},
2444 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2445 const char *start, *end;
2447 if (parser->Find(names[i].name_, start, end)) {
2448 CYString &value(*names[i].value_);
2449 _profile(Package$parse$Value)
2450 value.set(pool_, start, end - start);
2456 _profile(Package$parse$Tagline)
2457 const char *start, *end;
2458 if (parser->ShortDesc(start, end)) {
2459 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2462 while (stop != start && stop[-1] == '\r')
2464 parsed->tagline_.set(pool_, start, stop - start);
2468 _profile(Package$parse$Retain)
2469 if (parsed->homepage_.empty())
2470 parsed->homepage_ = website;
2471 if (parsed->homepage_ == parsed->depiction_)
2472 parsed->homepage_.clear();
2477 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2478 if ((self = [super init]) != nil) {
2479 _profile(Package$initWithVersion)
2482 database_ = database;
2483 era_ = [database era];
2487 pkgCache::PkgIterator iterator(version.ParentPkg());
2488 iterator_ = iterator;
2490 _profile(Package$initWithVersion$Version)
2491 if (!version_.end())
2492 file_ = version_.FileList();
2494 pkgCache &cache([database_ cache]);
2495 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2499 _profile(Package$initWithVersion$Cache)
2500 name_.set(NULL, iterator.Display());
2502 latest_.set(NULL, StripVersion_(version_.VerStr()));
2504 pkgCache::VerIterator current(iterator.CurrentVer());
2506 installed_.set(NULL, StripVersion_(current.VerStr()));
2509 _profile(Package$initWithVersion$Tags)
2510 pkgCache::TagIterator tag(iterator.TagList());
2512 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2514 const char *name(tag.Name());
2515 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2517 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2518 if (strcmp(name + 6, "enduser") == 0)
2520 else if (strcmp(name + 6, "hacker") == 0)
2522 else if (strcmp(name + 6, "developer") == 0)
2524 else if (strcmp(name + 6, "cydia") == 0)
2530 if (strncmp(name, "cydia::", 7) == 0) {
2531 if (strcmp(name + 7, "essential") == 0)
2533 else if (strcmp(name + 7, "obsolete") == 0)
2538 } while (!tag.end());
2542 _profile(Package$initWithVersion$Metadata)
2543 const char *mixed(iterator.Name());
2544 size_t size(strlen(mixed));
2545 char lower[size + 1];
2547 for (size_t i(0); i != size; ++i)
2548 lower[i] = mixed[i] | 0x20;
2551 PackageValue *metadata(PackageFind(lower, size));
2552 metadata_ = metadata;
2554 id_.set(NULL, metadata->name_, size);
2556 const char *latest(version_.VerStr());
2557 size_t length(strlen(latest));
2559 uint16_t vhash(hashlittle(latest, length));
2561 size_t capped(std::min<size_t>(8, length));
2562 latest = latest + length - capped;
2564 if (metadata->first_ == 0)
2565 metadata->first_ = now_;
2567 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2568 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2569 metadata->vhash_ = vhash;
2570 metadata->last_ = now_;
2571 } else if (metadata->last_ == 0)
2572 metadata->last_ = metadata->first_;
2575 _profile(Package$initWithVersion$Section)
2576 section_ = iterator.Section();
2579 _profile(Package$initWithVersion$Flags)
2580 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2581 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2586 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2587 pkgCache::VerIterator version;
2589 _profile(Package$packageWithIterator$GetCandidateVer)
2590 version = [database policy]->GetCandidateVer(iterator);
2598 _profile(Package$packageWithIterator$Allocate)
2599 package = [Package allocWithZone:zone];
2602 _profile(Package$packageWithIterator$Initialize)
2604 initWithVersion:version
2611 _profile(Package$packageWithIterator$Autorelease)
2612 package = [package autorelease];
2618 - (pkgCache::PkgIterator) iterator {
2622 - (NSString *) section {
2623 if (section$_ == nil) {
2624 if (section_ == NULL)
2627 _profile(Package$section$mappedSectionForPointer)
2628 section$_ = [database_ mappedSectionForPointer:section_];
2633 - (NSString *) simpleSection {
2634 if (NSString *section = [self section])
2635 return Simplify(section);
2640 - (NSString *) longSection {
2641 return LocalizeSection([self section]);
2644 - (NSString *) shortSection {
2645 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2648 - (NSString *) uri {
2651 pkgIndexFile *index;
2652 pkgCache::PkgFileIterator file(file_.File());
2653 if (![database_ list].FindIndex(file, index))
2655 return [NSString stringWithUTF8String:iterator_->Path];
2656 //return [NSString stringWithUTF8String:file.Site()];
2657 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2661 - (Address *) maintainer {
2662 @synchronized (database_) {
2663 if ([database_ era] != era_ || file_.end())
2666 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2667 const std::string &maintainer(parser->Maintainer());
2668 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2672 @synchronized (database_) {
2673 if ([database_ era] != era_ || version_.end())
2676 return version_->InstalledSize;
2679 - (NSString *) longDescription {
2680 @synchronized (database_) {
2681 if ([database_ era] != era_ || file_.end())
2684 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2685 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2687 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2688 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2689 if ([lines count] < 2)
2692 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2693 for (size_t i(1), e([lines count]); i != e; ++i) {
2694 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2695 [trimmed addObject:trim];
2698 return [trimmed componentsJoinedByString:@"\n"];
2701 - (NSString *) shortDescription {
2702 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2706 _profile(Package$index)
2707 CFStringRef name((CFStringRef) [self name]);
2708 if (CFStringGetLength(name) == 0)
2710 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2711 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2713 return toupper(character);
2717 - (PackageValue *) metadata {
2722 PackageValue *metadata([self metadata]);
2723 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2726 - (bool) subscribed {
2727 return [self metadata]->subscribed_;
2730 - (bool) setSubscribed:(bool)subscribed {
2731 PackageValue *metadata([self metadata]);
2732 if (metadata->subscribed_ == subscribed)
2734 metadata->subscribed_ = subscribed;
2742 - (NSString *) latest {
2746 - (NSString *) installed {
2750 - (BOOL) uninstalled {
2751 return installed_.empty();
2755 return !version_.end();
2758 - (BOOL) upgradableAndEssential:(BOOL)essential {
2759 _profile(Package$upgradableAndEssential)
2760 pkgCache::VerIterator current(iterator_.CurrentVer());
2762 return essential && essential_;
2764 return !version_.end() && version_ != current;
2768 - (BOOL) essential {
2773 return [database_ cache][iterator_].InstBroken();
2776 - (BOOL) unfiltered {
2777 _profile(Package$unfiltered$obsolete)
2778 if (_unlikely(obsolete_))
2782 _profile(Package$unfiltered$hasSupportingRole)
2783 if (_unlikely(![self hasSupportingRole]))
2791 if (![self unfiltered])
2796 _profile(Package$visible$section)
2797 section = [self section];
2800 _profile(Package$visible$isSectionVisible)
2801 if (!isSectionVisible(section))
2809 unsigned char current(iterator_->CurrentState);
2810 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2813 - (BOOL) halfConfigured {
2814 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2817 - (BOOL) halfInstalled {
2818 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2822 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2823 return state.Mode != pkgDepCache::ModeKeep;
2826 - (NSString *) mode {
2827 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2829 switch (state.Mode) {
2830 case pkgDepCache::ModeDelete:
2831 if ((state.iFlags & pkgDepCache::Purge) != 0)
2835 case pkgDepCache::ModeKeep:
2836 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2837 return @"REINSTALL";
2838 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2842 case pkgDepCache::ModeInstall:
2843 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2844 return @"REINSTALL";
2845 else*/ switch (state.Status) {
2847 return @"DOWNGRADE";
2853 return @"NEW_INSTALL";
2864 - (NSString *) name {
2865 return name_.empty() ? id_ : name_;
2868 - (UIImage *) icon {
2869 NSString *section = [self simpleSection];
2872 if (parsed_ != NULL)
2873 if (NSString *href = parsed_->icon_)
2874 if ([href hasPrefix:@"file:///"])
2875 // XXX: correct escaping
2876 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2877 if (icon == nil) if (section != nil)
2878 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2879 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2880 if ([dicon hasPrefix:@"file:///"])
2881 // XXX: correct escaping
2882 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2884 icon = [UIImage applicationImageNamed:@"unknown.png"];
2888 - (NSString *) homepage {
2889 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2892 - (NSString *) depiction {
2893 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2896 - (Address *) sponsor {
2897 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2900 - (Address *) author {
2901 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2904 - (NSString *) support {
2905 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2908 - (NSArray *) files {
2909 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2910 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2913 fin.open([path UTF8String]);
2918 while (std::getline(fin, line))
2919 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2924 - (NSArray *) warnings {
2925 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2926 const char *name(iterator_.Name());
2928 size_t length(strlen(name));
2929 if (length < 2) invalid:
2930 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2931 else for (size_t i(0); i != length; ++i)
2933 /* XXX: technically this is not allowed */
2934 (name[i] < 'A' || name[i] > 'Z') &&
2935 (name[i] < 'a' || name[i] > 'z') &&
2936 (name[i] < '0' || name[i] > '9') &&
2937 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2940 if (strcmp(name, "cydia") != 0) {
2943 bool _private = false;
2946 bool repository = [[self section] isEqualToString:@"Repositories"];
2948 if (NSArray *files = [self files])
2949 for (NSString *file in files)
2950 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2952 else if (!user && [file isEqualToString:@"/User"])
2954 else if (!_private && [file isEqualToString:@"/private"])
2956 else if (!stash && [file isEqualToString:@"/var/stash"])
2959 /* XXX: this is not sensitive enough. only some folders are valid. */
2960 if (cydia && !repository)
2961 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2963 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2965 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2967 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2970 return [warnings count] == 0 ? nil : warnings;
2973 - (NSArray *) applications {
2974 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2976 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2978 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2979 if (NSArray *files = [self files])
2980 for (NSString *file in files)
2981 if (application_r(file)) {
2982 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2983 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2984 if ([id isEqualToString:me])
2987 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2989 display = application_r[1];
2991 NSString *bundle([file stringByDeletingLastPathComponent]);
2992 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2993 if (icon == nil || [icon length] == 0)
2995 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2997 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2998 [applications addObject:application];
3000 [application addObject:id];
3001 [application addObject:display];
3002 [application addObject:url];
3005 return [applications count] == 0 ? nil : applications;
3008 - (Source *) source {
3009 if (source_ == nil) {
3010 @synchronized (database_) {
3011 if ([database_ era] != era_ || file_.end())
3012 source_ = (Source *) [NSNull null];
3014 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
3018 return source_ == (Source *) [NSNull null] ? nil : source_;
3021 - (BOOL) matches:(NSString *)text {
3027 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3028 if (range.location != NSNotFound)
3031 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3032 if (range.location != NSNotFound)
3037 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
3038 if (range.location != NSNotFound)
3044 - (bool) hasSupportingRole {
3049 if ([Role_ isEqualToString:@"User"])
3053 if ([Role_ isEqualToString:@"Hacker"])
3057 if ([Role_ isEqualToString:@"Developer"])
3062 - (BOOL) hasTag:(NSString *)tag {
3063 return tags_ == nil ? NO : [tags_ containsObject:tag];
3066 - (NSString *) primaryPurpose {
3067 for (NSString *tag in tags_)
3068 if ([tag hasPrefix:@"purpose::"])
3069 return [tag substringFromIndex:9];
3073 - (NSArray *) purposes {
3074 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3075 for (NSString *tag in tags_)
3076 if ([tag hasPrefix:@"purpose::"])
3077 [purposes addObject:[tag substringFromIndex:9]];
3078 return [purposes count] == 0 ? nil : purposes;
3081 - (bool) isCommercial {
3082 return [self hasTag:@"cydia::commercial"];
3085 - (void) setIndex:(size_t)index {
3086 if (metadata_->index_ != index)
3087 metadata_->index_ = index;
3090 - (CYString &) cyname {
3091 return name_.empty() ? id_ : name_;
3094 - (uint32_t) compareBySection:(NSArray *)sections {
3095 NSString *section([self section]);
3096 for (size_t i(0), e([sections count]); i != e; ++i) {
3097 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3101 return _not(uint32_t);
3105 @synchronized (database_) {
3106 pkgProblemResolver *resolver = [database_ resolver];
3107 resolver->Clear(iterator_);
3109 pkgCacheFile &cache([database_ cache]);
3110 cache->SetReInstall(iterator_, false);
3111 cache->MarkKeep(iterator_, false);
3115 @synchronized (database_) {
3116 pkgProblemResolver *resolver = [database_ resolver];
3117 resolver->Clear(iterator_);
3118 resolver->Protect(iterator_);
3120 pkgCacheFile &cache([database_ cache]);
3121 cache->SetReInstall(iterator_, false);
3122 cache->MarkInstall(iterator_, false);
3124 pkgDepCache::StateCache &state((*cache)[iterator_]);
3125 if (!state.Install())
3126 cache->SetReInstall(iterator_, true);
3130 @synchronized (database_) {
3131 pkgProblemResolver *resolver = [database_ resolver];
3132 resolver->Clear(iterator_);
3133 resolver->Remove(iterator_);
3134 resolver->Protect(iterator_);
3136 pkgCacheFile &cache([database_ cache]);
3137 cache->SetReInstall(iterator_, false);
3138 cache->MarkDelete(iterator_, true);
3141 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3142 _profile(Package$isUnfilteredAndSearchedForBy)
3145 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3146 value &= [self unfiltered];
3149 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3150 value &= [self matches:search];
3157 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3158 if ([search length] == 0)
3161 _profile(Package$isUnfilteredAndSelectedForBy)
3164 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3165 value &= [self unfiltered];
3168 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3169 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3176 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3177 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3180 - (bool) isVisibleInSection:(NSString *)name {
3181 NSString *section([self section]);
3185 section == nil && [name length] == 0 ||
3186 [name isEqualToString:section]
3187 ) && [self visible];
3190 - (bool) isVisibleInSource:(Source *)source {
3191 return [self source] == source && [self visible];
3196 /* Section Class {{{ */
3197 @interface Section : NSObject {
3202 NSString *localized_;
3205 - (NSComparisonResult) compareByLocalized:(Section *)section;
3206 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3207 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3208 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3209 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3210 - (NSString *) name;
3217 - (void) addToCount;
3219 - (void) setCount:(size_t)count;
3220 - (NSString *) localized;
3224 @implementation Section
3228 if (localized_ != nil)
3229 [localized_ release];
3233 - (NSComparisonResult) compareByLocalized:(Section *)section {
3234 NSString *lhs(localized_);
3235 NSString *rhs([section localized]);
3237 /*if ([lhs length] != 0 && [rhs length] != 0) {
3238 unichar lhc = [lhs characterAtIndex:0];
3239 unichar rhc = [rhs characterAtIndex:0];
3241 if (isalpha(lhc) && !isalpha(rhc))
3242 return NSOrderedAscending;
3243 else if (!isalpha(lhc) && isalpha(rhc))
3244 return NSOrderedDescending;
3247 return [lhs compare:rhs options:LaxCompareOptions_];
3250 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3251 if ((self = [self initWithName:name localize:NO]) != nil) {
3252 if (localized != nil)
3253 localized_ = [localized retain];
3257 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3258 return [self initWithName:name row:0 localize:localize];
3261 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3262 if ((self = [super init]) != nil) {
3263 name_ = [name retain];
3267 localized_ = [LocalizeSection(name_) retain];
3271 /* XXX: localize the index thingees */
3272 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3273 if ((self = [super init]) != nil) {
3274 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3280 - (NSString *) name {
3300 - (void) addToCount {
3304 - (void) setCount:(size_t)count {
3308 - (NSString *) localized {
3315 static NSString *Colon_;
3316 static NSString *Elision_;
3317 static NSString *Error_;
3318 static NSString *Warning_;
3320 /* Database Implementation {{{ */
3321 @implementation Database
3323 + (Database *) sharedInstance {
3324 static Database *instance;
3325 if (instance == nil)
3326 instance = [[Database alloc] init];
3334 - (void) releasePackages {
3335 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3336 CFArrayRemoveAllValues(packages_);
3340 // XXX: actually implement this thing
3342 [sourceList_ release];
3343 [self releasePackages];
3344 apr_pool_destroy(pool_);
3345 NSRecycleZone(zone_);
3349 - (void) _readCydia:(NSNumber *)fd { _pooled
3350 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3351 std::istream is(&ib);
3354 static Pcre finish_r("^finish:([^:]*)$");
3356 while (std::getline(is, line)) {
3357 const char *data(line.c_str());
3358 size_t size = line.size();
3359 lprintf("C:%s\n", data);
3361 if (finish_r(data, size)) {
3362 NSString *finish = finish_r[1];
3363 int index = [Finishes_ indexOfObject:finish];
3364 if (index != INT_MAX && index > Finish_)
3372 - (void) _readStatus:(NSNumber *)fd { _pooled
3373 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3374 std::istream is(&ib);
3377 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3378 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3380 while (std::getline(is, line)) {
3381 const char *data(line.c_str());
3382 size_t size(line.size());
3383 lprintf("S:%s\n", data);
3385 if (conffile_r(data, size))
3386 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3387 else if (strncmp(data, "status: ", 8) == 0) {
3388 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:@"STATUS"]);
3389 [progress_ performSelectorOnMainThread:@selector(addProgressEvent) withObject:event waitUntilDone:YES];
3390 } else if (pmstatus_r(data, size)) {
3391 std::string type([pmstatus_r[1] UTF8String]);
3393 NSString *package = pmstatus_r[2];
3394 if ([package isEqualToString:@"dpkg-exec"])
3397 float percent([pmstatus_r[3] floatValue]);
3398 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3400 NSString *string = pmstatus_r[4];
3402 if (type == "pmerror") {
3403 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"ERROR" forPackage:package]);
3404 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3405 } else if (type == "pmstatus") {
3406 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"STATUS" forPackage:package]);
3407 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3408 } else if (type == "pmconffile")
3409 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3411 lprintf("E:unknown pmstatus\n");
3413 lprintf("E:unknown status\n");
3419 - (void) _readOutput:(NSNumber *)fd { _pooled
3420 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3421 std::istream is(&ib);
3424 while (std::getline(is, line)) {
3425 lprintf("O:%s\n", line.c_str());
3427 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:@"INFORMATION"]);
3428 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3438 - (Package *) packageWithName:(NSString *)name {
3439 @synchronized (self) {
3440 if (static_cast<pkgDepCache *>(cache_) == NULL)
3442 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3443 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3447 if ((self = [super init]) != nil) {
3454 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3455 apr_pool_create(&pool_, NULL);
3457 size_t capacity(MetaFile_->active_);
3463 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3464 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3468 _assert(pipe(fds) != -1);
3471 _config->Set("APT::Keep-Fds::", cydiafd_);
3472 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3475 detachNewThreadSelector:@selector(_readCydia:)
3477 withObject:[NSNumber numberWithInt:fds[0]]
3480 _assert(pipe(fds) != -1);
3484 detachNewThreadSelector:@selector(_readStatus:)
3486 withObject:[NSNumber numberWithInt:fds[0]]
3489 _assert(pipe(fds) != -1);
3490 _assert(dup2(fds[0], 0) != -1);
3491 _assert(close(fds[0]) != -1);
3493 input_ = fdopen(fds[1], "a");
3495 _assert(pipe(fds) != -1);
3496 _assert(dup2(fds[1], 1) != -1);
3497 _assert(close(fds[1]) != -1);
3500 detachNewThreadSelector:@selector(_readOutput:)
3502 withObject:[NSNumber numberWithInt:fds[0]]
3507 - (pkgCacheFile &) cache {
3511 - (pkgDepCache::Policy *) policy {
3515 - (pkgRecords *) records {
3519 - (pkgProblemResolver *) resolver {
3523 - (pkgAcquire &) fetcher {
3527 - (pkgSourceList &) list {
3531 - (NSArray *) packages {
3532 return (NSArray *) packages_;
3535 - (NSArray *) sources {
3539 - (Source *) sourceWithKey:(NSString *)key {
3540 for (Source *source in [self sources]) {
3541 if ([[source key] isEqualToString:key])
3546 - (bool) popErrorWithTitle:(NSString *)title {
3549 while (!_error->empty()) {
3551 bool warning(!_error->PopMessage(error));
3556 size_t size(error.size());
3557 if (size == 0 || error[size - 1] != '\n')
3559 error.resize(size - 1);
3562 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3564 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3570 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3571 return [self popErrorWithTitle:title] || !success;
3574 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3575 @synchronized (self) {
3578 [self releasePackages];
3581 [sourceList_ removeAllObjects];
3601 apr_pool_clear(pool_);
3603 NSRecycleZone(zone_);
3604 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3606 int chk(creat("/tmp/cydia.chk", 0644));
3610 if (invocation != nil)
3611 [invocation invoke];
3613 NSString *title(UCLocalize("DATABASE"));
3616 OpProgress progress;
3617 while (!cache_.Open(progress, true)) { pop:
3619 bool warning(!_error->PopMessage(error));
3620 lprintf("cache_.Open():[%s]\n", error.c_str());
3622 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3623 [delegate_ repairWithSelector:@selector(configure)];
3624 else if (error == "The package lists or status file could not be parsed or opened.")
3625 [delegate_ repairWithSelector:@selector(update)];
3626 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3627 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3628 // else if (error == "Malformed Status line")
3629 // else if (error == "The list of sources could not be read.")
3631 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3641 unlink("/tmp/cydia.chk");
3643 now_ = [[NSDate date] timeIntervalSince1970];
3645 policy_ = new pkgDepCache::Policy();
3646 records_ = new pkgRecords(cache_);
3647 resolver_ = new pkgProblemResolver(cache_);
3648 fetcher_ = new pkgAcquire(&status_);
3651 list_ = new pkgSourceList();
3652 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3655 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3656 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:@"ERROR"] forTask:title];
3660 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3663 if (cache_->BrokenCount() != 0) {
3664 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3667 if (cache_->BrokenCount() != 0) {
3668 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:@"ERROR"] forTask:title];
3672 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3676 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3677 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3678 [sourceList_ addObject:object];
3680 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3681 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3682 // XXX: this could be more intelligent
3683 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3684 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3686 sourceMap_[cached->ID] = object;
3691 /*std::vector<Package *> packages;
3692 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3693 [packages_ release];
3698 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3699 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3700 //packages.push_back(package);
3701 CFArrayAppendValue(packages_, [package retain]);
3705 /*if (packages.empty())
3706 packages_ = [[NSArray alloc] init];
3708 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3711 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3712 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3713 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3721 /*if (!packages.empty())
3722 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3723 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3725 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3727 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3729 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3733 size_t count(CFArrayGetCount(packages_));
3734 MetaFile_->active_ = count;
3736 for (size_t index(0); index != count; ++index)
3737 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3741 } } CYPoolEnd() _trace(); }
3744 @synchronized (self) {
3746 resolver_ = new pkgProblemResolver(cache_);
3748 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3749 if (!cache_[iterator].Keep())
3750 cache_->MarkKeep(iterator, false);
3751 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3752 cache_->SetReInstall(iterator, false);
3755 - (void) configure {
3756 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3758 system([dpkg UTF8String]);
3763 // XXX: I don't remember this condition
3768 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3770 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3772 if ([self popErrorWithTitle:title])
3776 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3779 public pkgArchiveCleaner
3782 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3787 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3794 fetcher_->Shutdown();
3796 pkgRecords records(cache_);
3798 lock_ = new FileFd();
3799 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3801 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3803 if ([self popErrorWithTitle:title])
3807 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3810 manager_ = (_system->CreatePM(cache_));
3811 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3818 bool substrate(RestartSubstrate_);
3819 RestartSubstrate_ = false;
3821 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3823 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3825 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3827 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3828 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3831 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3833 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3835 [self popErrorWithTitle:title];
3839 bool failed = false;
3840 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3841 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3843 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3849 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3857 RestartSubstrate_ = true;
3860 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3862 if (_error->PendingError()) {
3867 if (result == pkgPackageManager::Failed) {
3872 if (result != pkgPackageManager::Completed) {
3877 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3879 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3881 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3882 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3885 if (![before isEqualToArray:after])
3890 NSString *title(UCLocalize("UPGRADE"));
3891 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3897 [self updateWithStatus:status_];
3900 - (void) updateWithStatus:(Status &)status {
3901 NSString *title(UCLocalize("REFRESHING_DATA"));
3904 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3908 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3909 if ([self popErrorWithTitle:title])
3912 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3914 bool success(ListUpdate(status, list, PulseInterval_));
3915 if (status.WasCancelled())
3918 [self popErrorWithTitle:title forOperation:success];
3920 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3922 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3926 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3927 delegate_ = delegate;
3930 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3931 progress_ = delegate;
3932 status_.setDelegate(delegate);
3935 - (NSObject<ProgressDelegate> *) progressDelegate {
3939 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3940 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3941 return i == sourceMap_.end() ? nil : i->second;
3944 - (NSString *) mappedSectionForPointer:(const char *)section {
3945 _H<NSString> *mapped;
3947 _profile(Database$mappedSectionForPointer$Cache)
3948 mapped = §ions_[section];
3951 if (*mapped == NULL) {
3952 size_t length(strlen(section));
3953 char spaced[length + 1];
3955 _profile(Database$mappedSectionForPointer$Replace)
3956 for (size_t index(0); index != length; ++index)
3957 spaced[index] = section[index] == '_' ? ' ' : section[index];
3958 spaced[length] = '\0';
3963 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3964 string = [NSString stringWithUTF8String:spaced];
3967 _profile(Database$mappedSectionForPointer$Map)
3968 string = [SectionMap_ objectForKey:string] ?: string;
3978 /* Web Scripting {{{ */
3979 @interface CydiaObject : NSObject {
3981 _transient id delegate_;
3984 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3988 @implementation CydiaObject
3991 [indirect_ release];
3995 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3996 if ((self = [super init]) != nil) {
3997 indirect_ = [indirect retain];
4001 - (void) setDelegate:(id)delegate {
4002 delegate_ = delegate;
4005 + (NSArray *) _attributeKeys {
4006 return [NSArray arrayWithObjects:
4021 - (NSArray *) attributeKeys {
4022 return [[self class] _attributeKeys];
4025 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4026 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4029 - (NSString *) version {
4033 - (NSString *) device {
4034 return [[UIDevice currentDevice] uniqueIdentifier];
4037 - (NSString *) firmware {
4038 return [[UIDevice currentDevice] systemVersion];
4041 - (NSString *) hostname {
4042 return [[UIDevice currentDevice] name];
4045 - (NSString *) idiom {
4046 UIDevice *device([UIDevice currentDevice]);
4047 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
4050 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
4051 if (idiom == UIUserInterfaceIdiomPhone)
4053 else if (idiom == UIUserInterfaceIdiomPad)
4059 - (NSString *) plmn {
4060 return (id) PLMN_ ?: [NSNull null];
4063 - (NSString *) ecid {
4064 return (id) ChipID_ ?: [NSNull null];
4067 - (NSString *) serial {
4068 return SerialNumber_;
4071 - (NSString *) role {
4072 return (id) Role_ ?: [NSNull null];
4075 - (NSString *) model {
4076 return [NSString stringWithUTF8String:Machine_];
4079 - (NSString *) token {
4080 return (id) Token_ ?: [NSNull null];
4083 + (NSString *) webScriptNameForSelector:(SEL)selector {
4085 else if (selector == @selector(addTrivialSource:))
4086 return @"addTrivialSource";
4087 else if (selector == @selector(close))
4089 else if (selector == @selector(du:))
4091 else if (selector == @selector(stringWithFormat:arguments:))
4093 else if (selector == @selector(getAllSources))
4094 return @"getAllSourcs";
4095 else if (selector == @selector(getKernelNumber:))
4096 return @"getKernelNumber";
4097 else if (selector == @selector(getKernelString:))
4098 return @"getKernelString";
4099 else if (selector == @selector(getInstalledPackages))
4100 return @"getInstalledPackages";
4101 else if (selector == @selector(getPackageById:))
4102 return @"getPackageById";
4103 else if (selector == @selector(installPackages:))
4104 return @"installPackages";
4105 else if (selector == @selector(localizedStringForKey:value:table:))
4107 else if (selector == @selector(refreshSources))
4108 return @"refreshSources";
4109 else if (selector == @selector(removeButton))
4110 return @"removeButton";
4111 else if (selector == @selector(scrollToBottom:))
4112 return @"scrollToBottom";
4113 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4114 return @"setButtonImage";
4115 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4116 return @"setButtonTitle";
4117 else if (selector == @selector(setHidesBackButton:))
4118 return @"setHidesBackButton";
4119 else if (selector == @selector(setNavigationBarStyle:))
4120 return @"setNavigationBarStyle";
4121 else if (selector == @selector(setPopupHook:))
4122 return @"setPopupHook";
4123 else if (selector == @selector(setToken:))
4125 else if (selector == @selector(setViewportWidth:))
4126 return @"setViewportWidth";
4127 else if (selector == @selector(statfs:))
4129 else if (selector == @selector(supports:))
4135 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4136 return [self webScriptNameForSelector:selector] == nil;
4139 - (BOOL) supports:(NSString *)feature {
4140 return [feature isEqualToString:@"window.open"];
4143 - (NSNumber *) getKernelNumber:(NSString *)name {
4144 const char *string([name UTF8String]);
4147 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4148 return (id) [NSNull null];
4150 if (size != sizeof(int))
4151 return (id) [NSNull null];
4154 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4155 return (id) [NSNull null];
4157 return [NSNumber numberWithInt:value];
4160 - (NSString *) getKernelString:(NSString *)name {
4161 const char *string([name UTF8String]);
4164 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4165 return (id) [NSNull null];
4167 char value[size + 1];
4168 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4169 return (id) [NSNull null];
4171 // XXX: just in case you request something ludicrous
4174 return [NSString stringWithCString:value];
4177 - (void) addTrivialSource:(NSString *)href {
4178 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4181 - (void) refreshSources {
4182 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4185 - (NSArray *) getAllSources {
4186 return [[Database sharedInstance] sources];
4189 - (NSArray *) getInstalledPackages {
4190 Database *database([Database sharedInstance]);
4191 @synchronized (database) {
4192 NSArray *packages([database packages]);
4193 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4194 for (Package *package in packages)
4195 if (![package uninstalled])
4196 [installed addObject:package];
4200 - (Package *) getPackageById:(NSString *)id {
4201 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4205 return (Package *) [NSNull null];
4208 - (NSArray *) statfs:(NSString *)path {
4211 if (path == nil || statfs([path UTF8String], &stat) == -1)
4214 return [NSArray arrayWithObjects:
4215 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4216 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4217 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4221 - (NSNumber *) du:(NSString *)path {
4222 NSNumber *value(nil);
4225 _assert(pipe(fds) != -1);
4227 pid_t pid(ExecFork());
4229 _assert(dup2(fds[1], 1) != -1);
4230 _assert(close(fds[0]) != -1);
4231 _assert(close(fds[1]) != -1);
4232 /* XXX: this should probably not use du */
4233 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4238 _assert(close(fds[1]) != -1);
4240 if (FILE *du = fdopen(fds[0], "r")) {
4242 while (fgets(line, sizeof(line), du) != NULL) {
4243 size_t length(strlen(line));
4244 while (length != 0 && line[length - 1] == '\n')
4245 line[--length] = '\0';
4246 if (char *tab = strchr(line, '\t')) {
4248 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4253 } else _assert(close(fds[0]));
4257 if (waitpid(pid, &status, 0) == -1)
4260 else _assert(false);
4266 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4269 - (void) installPackages:(NSArray *)packages {
4270 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4273 - (void) removeButton {
4274 [indirect_ removeButton];
4277 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4278 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4281 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4282 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4285 - (void) setHidesBackButton:(NSString *)value {
4286 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4289 - (void) setNavigationBarStyle:(NSString *)value {
4290 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4293 - (void) _setToken:(NSString *)token {
4297 [Metadata_ removeObjectForKey:@"Token"];
4299 [Metadata_ setObject:Token_ forKey:@"Token"];
4304 - (void) setToken:(NSString *)token {
4305 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4308 - (void) setPopupHook:(id)function {
4309 [indirect_ setPopupHook:function];
4312 - (void) scrollToBottom:(NSNumber *)animated {
4313 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4316 - (void) setViewportWidth:(float)width {
4317 [indirect_ setViewportWidthOnMainThread:width];
4320 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4321 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4322 unsigned count([arguments count]);
4324 for (unsigned i(0); i != count; ++i)
4325 values[i] = [arguments objectAtIndex:i];
4326 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4329 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4330 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4332 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4334 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4340 /* @ Loading... Indicator {{{ */
4341 @interface CYLoadingIndicator : UIView {
4342 _H<UIActivityIndicatorView> spinner_;
4344 _H<UIView> container_;
4347 @property (readonly, nonatomic) UILabel *label;
4348 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4352 @implementation CYLoadingIndicator
4354 - (id) initWithFrame:(CGRect)frame {
4355 if ((self = [super initWithFrame:frame]) != nil) {
4356 container_ = [[[UIView alloc] init] autorelease];
4357 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4359 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4360 [spinner_ startAnimating];
4361 [container_ addSubview:spinner_];
4363 label_ = [[[UILabel alloc] init] autorelease];
4364 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4365 [label_ setBackgroundColor:[UIColor clearColor]];
4366 [label_ setTextColor:[UIColor blackColor]];
4367 [label_ setShadowColor:[UIColor whiteColor]];
4368 [label_ setShadowOffset:CGSizeMake(0, 1)];
4369 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4370 [container_ addSubview:label_];
4372 CGSize viewsize = frame.size;
4373 CGSize spinnersize = [spinner_ bounds].size;
4374 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4375 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4377 CGRect containrect = {
4378 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4379 CGSizeMake(bothwidth, spinnersize.height)
4382 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4390 [container_ setFrame:containrect];
4391 [spinner_ setFrame:spinrect];
4392 [label_ setFrame:textrect];
4393 [self addSubview:container_];
4397 - (UILabel *) label {
4401 - (UIActivityIndicatorView *) activityIndicatorView {
4407 /* Emulated Loading Controller {{{ */
4408 @interface CYEmulatedLoadingController : CYViewController {
4409 _transient Database *database_;
4410 _H<CYLoadingIndicator> indicator_;
4411 _H<UITabBar> tabbar_;
4412 _H<UINavigationBar> navbar_;
4417 @implementation CYEmulatedLoadingController
4419 - (id) initWithDatabase:(Database *)database {
4420 if ((self = [super init]) != nil) {
4421 database_ = database;
4426 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4427 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4429 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4430 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4431 [[self view] addSubview:indicator_];
4433 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4434 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4435 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4436 [[self view] addSubview:tabbar_];
4438 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4439 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4440 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4441 [[self view] addSubview:navbar_];
4444 - (void) releaseSubviews {
4453 /* Cydia Browser Controller {{{ */
4454 @interface CYBrowserController : BrowserController {
4455 CydiaObject *cydia_;
4460 @implementation CYBrowserController
4467 - (NSURL *) navigationURL {
4468 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4471 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4474 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4475 [super webView:view didClearWindowObject:window forFrame:frame];
4477 WebDataSource *source([frame dataSource]);
4478 NSURLResponse *response([source response]);
4480 NSURL *url([response URL]);
4481 NSString *scheme([url scheme]);
4482 NSString *host([url host]);
4484 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4485 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4486 NSDictionary *headers([http allHeaderFields]);
4487 [self setHeaders:headers forHost:host];
4491 [host isEqualToString:@"cydia.saurik.com"] ||
4492 [host hasSuffix:@".cydia.saurik.com"] ||
4493 [scheme isEqualToString:@"file"]
4495 [window setValue:cydia_ forKey:@"cydia"];
4498 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4499 if (System_ != NULL)
4500 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4501 if (Machine_ != NULL)
4502 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4504 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4506 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4509 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4510 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4511 [self _setMoreHeaders:copy];
4515 - (void) setDelegate:(id)delegate {
4516 [super setDelegate:delegate];
4517 [cydia_ setDelegate:delegate];
4521 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4522 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4524 WebView *webview([[webview_ _documentView] webView]);
4526 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4529 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4531 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4532 if (Product_ != nil)
4533 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4535 [webview setApplicationNameForUserAgent:application];
4543 @interface NSObject (CydiaScript)
4544 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4547 @implementation NSObject (CydiaScript)
4549 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4555 @implementation NSArray (CydiaScript)
4557 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4558 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4559 for (size_t i(0), e([self count]); i != e; ++i)
4560 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4566 @implementation NSDictionary (CydiaScript)
4568 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4569 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4571 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4578 /* Confirmation Controller {{{ */
4579 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4580 if (!iterator.end())
4581 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4582 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4584 pkgCache::PkgIterator package(dep.TargetPkg());
4587 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4594 @protocol ConfirmationControllerDelegate
4595 - (void) cancelAndClear:(bool)clear;
4596 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4600 @interface ConfirmationController : CYBrowserController {
4601 _transient Database *database_;
4603 UIAlertView *essential_;
4605 NSDictionary *changes_;
4606 NSMutableArray *issues_;
4607 NSDictionary *sizes_;
4612 - (id) initWithDatabase:(Database *)database;
4616 @implementation ConfirmationController
4623 if (essential_ != nil)
4624 [essential_ release];
4631 RestartSubstrate_ = true;
4632 [delegate_ confirmWithNavigationController:[self navigationController]];
4635 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4636 NSString *context([alert context]);
4638 if ([context isEqualToString:@"remove"]) {
4639 if (button == [alert cancelButtonIndex])
4640 [self dismissModalViewControllerAnimated:YES];
4641 else if (button == [alert firstOtherButtonIndex]) {
4645 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4646 } else if ([context isEqualToString:@"unable"]) {
4647 [self dismissModalViewControllerAnimated:YES];
4648 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4650 [super alertView:alert clickedButtonAtIndex:button];
4654 - (void) _doContinue {
4655 [self dismissModalViewControllerAnimated:YES];
4656 [delegate_ cancelAndClear:NO];
4659 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4660 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4664 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4665 [super webView:view didClearWindowObject:window forFrame:frame];
4667 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4668 changes_, @"changes",
4672 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4675 - (id) initWithDatabase:(Database *)database {
4676 if ((self = [super init]) != nil) {
4677 database_ = database;
4679 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4680 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4681 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4682 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4683 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4687 pkgCacheFile &cache([database_ cache]);
4688 NSArray *packages([database_ packages]);
4689 pkgDepCache::Policy *policy([database_ policy]);
4691 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4693 for (Package *package in packages) {
4694 pkgCache::PkgIterator iterator([package iterator]);
4695 NSString *name([package id]);
4697 if ([package broken]) {
4698 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4700 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4702 reasons, @"reasons",
4705 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4709 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4710 pkgCache::DepIterator start;
4711 pkgCache::DepIterator end;
4712 dep.GlobOr(start, end); // ++dep
4714 if (!cache->IsImportantDep(end))
4716 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4719 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4721 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4722 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4723 clauses, @"clauses",
4727 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4729 pkgCache::PkgIterator target(start.TargetPkg());
4730 if (target->ProvidesList != 0)
4731 reason = @"missing";
4733 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4735 reason = @"installed";
4736 installed = [NSString stringWithUTF8String:ver.VerStr()];
4737 } else if (!cache[target].CandidateVerIter(cache).end())
4738 reason = @"uninstalled";
4739 else if (target->ProvidesList == 0)
4740 reason = @"uninstallable";
4742 reason = @"virtual";
4745 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4746 [NSString stringWithUTF8String:start.CompType()], @"operator",
4747 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4750 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4751 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4752 version, @"version",
4754 installed, @"installed",
4757 // yes, seriously. (wtf?)
4765 pkgDepCache::StateCache &state(cache[iterator]);
4767 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4769 if (state.NewInstall())
4770 [installs addObject:name];
4771 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4772 [reinstalls addObject:name];
4773 else if (state.Upgrade())
4774 [upgrades addObject:name];
4775 else if (state.Downgrade())
4776 [downgrades addObject:name];
4777 else if (!state.Delete())
4779 else if (special_r(name))
4780 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4781 [NSNull null], @"package",
4782 [NSArray arrayWithObjects:
4783 [NSDictionary dictionaryWithObjectsAndKeys:
4784 @"Conflicts", @"relationship",
4785 [NSArray arrayWithObjects:
4786 [NSDictionary dictionaryWithObjectsAndKeys:
4788 [NSNull null], @"version",
4789 @"installed", @"reason",
4796 if ([package essential])
4798 [removes addObject:name];
4801 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4802 substrate_ |= DepSubstrate(iterator.CurrentVer());
4807 else if (Advanced_) {
4808 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4810 essential_ = [[UIAlertView alloc]
4811 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4812 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4814 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4816 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4820 [essential_ setContext:@"remove"];
4822 essential_ = [[UIAlertView alloc]
4823 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4824 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4826 cancelButtonTitle:UCLocalize("OKAY")
4827 otherButtonTitles:nil
4830 [essential_ setContext:@"unable"];
4833 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4834 installs, @"installs",
4835 reinstalls, @"reinstalls",
4836 upgrades, @"upgrades",
4837 downgrades, @"downgrades",
4838 removes, @"removes",
4841 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4842 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4843 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4846 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4848 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4849 initWithTitle:UCLocalize("CANCEL")
4850 style:UIBarButtonItemStylePlain
4852 action:@selector(cancelButtonClicked)
4858 - (void) applyRightButton {
4859 if ([issues_ count] == 0 && ![self isLoading])
4860 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4861 initWithTitle:UCLocalize("CONFIRM")
4862 style:UIBarButtonItemStyleDone
4864 action:@selector(confirmButtonClicked)
4867 [[self navigationItem] setRightBarButtonItem:nil];
4871 - (void) cancelButtonClicked {
4872 [self dismissModalViewControllerAnimated:YES];
4873 [delegate_ cancelAndClear:YES];
4877 - (void) confirmButtonClicked {
4878 if (essential_ != nil)
4888 /* Progress Data {{{ */
4889 @interface CydiaProgressData : NSObject {
4890 _transient id delegate_;
4895 _H<NSMutableArray> events_;
4896 _H<NSString> title_;
4898 _H<NSString> status_;
4899 _H<NSString> finish_;
4904 @implementation CydiaProgressData
4906 + (NSArray *) _attributeKeys {
4907 return [NSArray arrayWithObjects:
4916 - (NSArray *) attributeKeys {
4917 return [[self class] _attributeKeys];
4920 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4921 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4925 if ((self = [super init]) != nil) {
4926 events_ = [NSMutableArray arrayWithCapacity:32];
4930 - (void) setDelegate:(id)delegate {
4931 delegate_ = delegate;
4934 - (void) setPercent:(float)value {
4938 - (NSNumber *) percent {
4939 return [NSNumber numberWithFloat:percent_];
4942 - (NSArray *) events {
4946 - (void) removeAllEvents {
4947 [events_ removeAllObjects];
4950 - (void) addEvent:(CydiaProgressEvent *)event {
4951 [events_ addObject:event];
4954 - (void) setTitle:(NSString *)text {
4958 - (NSString *) title {
4962 - (void) setFinish:(NSString *)text {
4966 - (NSString *) finish {
4967 return (id) finish_ ?: [NSNull null];
4970 - (void) setRunning:(bool)running {
4974 - (NSNumber *) running {
4975 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4980 /* Progress Controller {{{ */
4981 @interface ProgressController : CYBrowserController <
4984 _transient Database *database_;
4985 _H<CydiaProgressData> progress_;
4989 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4991 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4993 - (void) setTitle:(NSString *)title;
4994 - (void) setCancellable:(bool)cancellable;
4998 @implementation ProgressController
5001 [database_ setProgressDelegate:nil];
5002 [progress_ setDelegate:nil];
5006 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5007 if ((self = [super init]) != nil) {
5008 database_ = database;
5009 delegate_ = delegate;
5011 [database_ setProgressDelegate:self];
5013 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5014 [progress_ setDelegate:self];
5018 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5019 [super webView:view didClearWindowObject:window forFrame:frame];
5020 [window setValue:progress_ forKey:@"cydiaProgress"];
5023 - (void) updateProgress {
5024 [self dispatchEvent:@"CydiaProgressUpdate"];
5027 - (void) updateCancel {
5028 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5029 initWithTitle:UCLocalize("CANCEL")
5030 style:UIBarButtonItemStylePlain
5032 action:@selector(cancel)
5033 ] autorelease] : nil)];
5036 - (void) viewWillAppear:(BOOL)animated {
5037 if (![self hasLoaded]) {
5038 [scroller_ setBackgroundColor:[UIColor blackColor]];
5039 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/progress/", UI_]]];
5042 [super viewDidAppear:animated];
5044 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5046 [[self navigationItem] setHidesBackButton:YES];
5048 [self updateCancel];
5052 UpdateExternalStatus(0);
5059 [delegate_ terminateWithSuccess];
5060 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5061 [delegate_ suspendWithAnimation:YES];
5063 [delegate_ suspend];*/
5075 system("/usr/bin/sbreload");
5081 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5082 SBReboot(SBSSpringBoardServerPort());
5084 reboot2(RB_AUTOBOOT);
5091 - (void) setTitle:(NSString *)title {
5092 [progress_ setTitle:title];
5093 [self updateProgress];
5096 - (UIBarButtonItem *) rightButton {
5097 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5098 initWithTitle:UCLocalize("CLOSE")
5099 style:UIBarButtonItemStylePlain
5101 action:@selector(close)
5105 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5106 UpdateExternalStatus(1);
5108 [progress_ setRunning:true];
5109 [self setTitle:title];
5110 // implicit updateProgress
5112 SHA1SumValue notifyconf; {
5114 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5117 MMap mmap(file, MMap::ReadOnly);
5119 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5120 notifyconf = sha1.Result();
5124 SHA1SumValue springlist; {
5126 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5129 MMap mmap(file, MMap::ReadOnly);
5131 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5132 springlist = sha1.Result();
5136 if (invocation != nil) {
5137 [invocation yieldToSelector:@selector(invoke)];
5138 [self setTitle:@"COMPLETE"];
5143 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5146 MMap mmap(file, MMap::ReadOnly);
5148 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5149 if (!(notifyconf == sha1.Result()))
5156 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5159 MMap mmap(file, MMap::ReadOnly);
5161 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5162 if (!(springlist == sha1.Result()))
5168 if (RestartSubstrate_)
5172 RestartSubstrate_ = false;
5175 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5176 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5177 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5178 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5179 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5183 system("su -c /usr/bin/uicache mobile");
5186 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5188 [progress_ setRunning:false];
5189 [self updateProgress];
5191 [self applyRightButton];
5194 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5195 [progress_ addEvent:event];
5196 [self updateProgress];
5199 - (bool) isProgressCancelled {
5200 return cancel_ == 2;
5205 [self updateCancel];
5208 - (void) setCancellable:(bool)cancellable {
5209 unsigned cancel(cancel_);
5213 else if (cancel_ == 0)
5216 if (cancel != cancel_)
5217 [self updateCancel];
5220 - (void) setProgressCancellable:(NSNumber *)cancellable {
5221 [self setCancellable:[cancellable boolValue]];
5224 - (void) setProgressPercent:(NSNumber *)percent {
5225 [progress_ setPercent:[percent floatValue]];
5226 [self updateProgress];
5232 /* Cell Content View {{{ */
5233 @protocol ContentDelegate
5234 - (void) drawContentRect:(CGRect)rect;
5237 @interface ContentView : UIView {
5238 _transient id<ContentDelegate> delegate_;
5243 @implementation ContentView
5245 - (id) initWithFrame:(CGRect)frame {
5246 if ((self = [super initWithFrame:frame]) != nil) {
5247 [self setNeedsDisplayOnBoundsChange:YES];
5251 - (void) setDelegate:(id<ContentDelegate>)delegate {
5252 delegate_ = delegate;
5255 - (void) drawRect:(CGRect)rect {
5256 [super drawRect:rect];
5257 [delegate_ drawContentRect:rect];
5262 /* Cydia TableView Cell {{{ */
5263 @interface CYTableViewCell : UITableViewCell {
5264 ContentView *content_;
5270 @implementation CYTableViewCell
5277 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5278 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5280 if (view == content_) {
5281 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5282 highlighted_ = highlighted;
5285 [super _updateHighlightColorsForView:view highlighted:highlighted];
5288 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5289 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5290 highlighted_ = selected;
5292 [super setSelected:selected animated:animated];
5293 [content_ setNeedsDisplay];
5299 /* Package Cell {{{ */
5300 @interface PackageCell : CYTableViewCell <
5305 NSString *description_;
5313 - (PackageCell *) init;
5314 - (void) setPackage:(Package *)package;
5316 - (void) drawContentRect:(CGRect)rect;
5320 @implementation PackageCell
5322 - (void) clearPackage {
5333 if (description_ != nil) {
5334 [description_ release];
5338 if (source_ != nil) {
5343 if (badge_ != nil) {
5348 if (placard_ != nil) {
5358 [self clearPackage];
5362 - (PackageCell *) init {
5363 CGRect frame(CGRectMake(0, 0, 320, 74));
5364 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5365 UIView *content([self contentView]);
5366 CGRect bounds([content bounds]);
5368 content_ = [[ContentView alloc] initWithFrame:bounds];
5369 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5370 [content addSubview:content_];
5372 [content_ setDelegate:self];
5373 [content_ setOpaque:YES];
5377 - (NSString *) accessibilityLabel {
5378 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5381 - (void) setPackage:(Package *)package {
5382 [self clearPackage];
5385 Source *source = [package source];
5387 icon_ = [[package icon] retain];
5388 name_ = [[package name] retain];
5391 description_ = [package longDescription];
5392 if (description_ == nil)
5393 description_ = [package shortDescription];
5394 if (description_ != nil)
5395 description_ = [description_ retain];
5397 commercial_ = [package isCommercial];
5399 package_ = [package retain];
5401 NSString *label = nil;
5402 bool trusted = false;
5404 if (source != nil) {
5405 label = [source label];
5406 trusted = [source trusted];
5407 } else if ([[package id] isEqualToString:@"firmware"])
5408 label = UCLocalize("APPLE");
5410 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5412 NSString *from(label);
5414 NSString *section = [package simpleSection];
5415 if (section != nil && ![section isEqualToString:label]) {
5416 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5417 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5420 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5421 source_ = [from retain];
5423 if (NSString *purpose = [package primaryPurpose])
5424 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5425 badge_ = [badge_ retain];
5430 if (NSString *mode = [package_ mode]) {
5431 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5432 color = RemovingColor_;
5433 //placard = @"removing";
5435 color = InstallingColor_;
5436 //placard = @"installing";
5439 // XXX: the removing/installing placards are not @2x
5442 color = [UIColor whiteColor];
5444 if ([package installed] != nil)
5445 placard = @"installed";
5450 [content_ setBackgroundColor:color];
5453 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5454 placard_ = [placard_ retain];
5456 [self setNeedsDisplay];
5457 [content_ setNeedsDisplay];
5460 - (void) drawContentRect:(CGRect)rect {
5461 bool highlighted(highlighted_);
5462 float width([self bounds].size.width);
5465 CGContextRef context(UIGraphicsGetCurrentContext());
5466 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5467 CGContextFillRect(context, rect);
5472 rect.size = [icon_ size];
5474 rect.size.width /= 2;
5475 rect.size.height /= 2;
5477 rect.origin.x = 25 - rect.size.width / 2;
5478 rect.origin.y = 25 - rect.size.height / 2;
5480 [icon_ drawInRect:rect];
5483 if (badge_ != nil) {
5485 rect.size = [badge_ size];
5487 rect.size.width /= 2;
5488 rect.size.height /= 2;
5490 rect.origin.x = 36 - rect.size.width / 2;
5491 rect.origin.y = 36 - rect.size.height / 2;
5493 [badge_ drawInRect:rect];
5500 UISetColor(commercial_ ? Purple_ : Black_);
5501 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5502 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5505 UISetColor(commercial_ ? Purplish_ : Gray_);
5506 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5508 if (placard_ != nil)
5509 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5514 /* Section Cell {{{ */
5515 @interface SectionCell : CYTableViewCell <
5527 - (void) setSection:(Section *)section editing:(BOOL)editing;
5531 @implementation SectionCell
5533 - (void) clearSection {
5534 if (basic_ != nil) {
5539 if (section_ != nil) {
5549 if (count_ != nil) {
5556 [self clearSection];
5562 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5563 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5564 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5565 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5566 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5568 UIView *content([self contentView]);
5569 CGRect bounds([content bounds]);
5571 content_ = [[ContentView alloc] initWithFrame:bounds];
5572 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5573 [content addSubview:content_];
5574 [content_ setBackgroundColor:[UIColor whiteColor]];
5576 [content_ setDelegate:self];
5580 - (void) onSwitch:(id)sender {
5581 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5582 if (metadata == nil) {
5583 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5584 [Sections_ setObject:metadata forKey:basic_];
5587 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5591 - (void) setSection:(Section *)section editing:(BOOL)editing {
5592 if (editing != editing_) {
5594 [switch_ removeFromSuperview];
5596 [self addSubview:switch_];
5600 [self clearSection];
5602 if (section == nil) {
5603 name_ = [UCLocalize("ALL_PACKAGES") retain];
5606 basic_ = [section name];
5608 basic_ = [basic_ retain];
5610 section_ = [section localized];
5611 if (section_ != nil)
5612 section_ = [section_ retain];
5614 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5615 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5618 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5621 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5622 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5624 [content_ setNeedsDisplay];
5627 - (void) setFrame:(CGRect)frame {
5628 [super setFrame:frame];
5630 CGRect rect([switch_ frame]);
5631 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5634 - (NSString *) accessibilityLabel {
5638 - (void) drawContentRect:(CGRect)rect {
5639 bool highlighted(highlighted_ && !editing_);
5641 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5646 float width(rect.size.width);
5652 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5654 CGSize size = [count_ sizeWithFont:Font14_];
5658 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5664 /* File Table {{{ */
5665 @interface FileTable : CYViewController <
5666 UITableViewDataSource,
5669 _transient Database *database_;
5672 NSMutableArray *files_;
5676 - (id) initWithDatabase:(Database *)database;
5677 - (void) setPackage:(Package *)package;
5681 @implementation FileTable
5684 [self releaseSubviews];
5693 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5694 return files_ == nil ? 0 : [files_ count];
5697 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5701 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5702 static NSString *reuseIdentifier = @"Cell";
5704 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5706 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5707 [cell setFont:[UIFont systemFontOfSize:16]];
5709 [cell setText:[files_ objectAtIndex:indexPath.row]];
5710 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5715 - (NSURL *) navigationURL {
5716 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5720 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5722 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5723 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5724 [list_ setRowHeight:24.0f];
5725 [list_ setDataSource:self];
5726 [list_ setDelegate:self];
5727 [[self view] addSubview:list_];
5730 - (void) viewDidLoad {
5731 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5734 - (void) releaseSubviews {
5739 - (id) initWithDatabase:(Database *)database {
5740 if ((self = [super init]) != nil) {
5741 database_ = database;
5743 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5747 - (void) setPackage:(Package *)package {
5748 if (package_ != nil) {
5749 [package_ autorelease];
5758 [files_ removeAllObjects];
5760 if (package != nil) {
5761 package_ = [package retain];
5762 name_ = [[package id] retain];
5764 if (NSArray *files = [package files])
5765 [files_ addObjectsFromArray:files];
5767 if ([files_ count] != 0) {
5768 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5769 [files_ removeObjectAtIndex:0];
5770 [files_ sortUsingSelector:@selector(compareByPath:)];
5772 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5773 [stack addObject:@"/"];
5775 for (int i(0), e([files_ count]); i != e; ++i) {
5776 NSString *file = [files_ objectAtIndex:i];
5777 while (![file hasPrefix:[stack lastObject]])
5778 [stack removeLastObject];
5779 NSString *directory = [stack lastObject];
5780 [stack addObject:[file stringByAppendingString:@"/"]];
5781 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5782 ([stack count] - 2) * 3, "",
5783 [file substringFromIndex:[directory length]]
5792 - (void) reloadData {
5795 [self setPackage:[database_ packageWithName:name_]];
5800 /* Package Controller {{{ */
5801 @interface CYPackageController : CYBrowserController <
5802 UIActionSheetDelegate
5804 _transient Database *database_;
5808 NSMutableArray *buttons_;
5809 UIBarButtonItem *button_;
5812 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5816 @implementation CYPackageController
5819 if (package_ != nil)
5832 - (NSURL *) navigationURL {
5833 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5836 /* XXX: this is not safe at all... localization of /fail/ */
5837 - (void) _clickButtonWithName:(NSString *)name {
5838 if ([name isEqualToString:UCLocalize("CLEAR")])
5839 [delegate_ clearPackage:package_];
5840 else if ([name isEqualToString:UCLocalize("INSTALL")])
5841 [delegate_ installPackage:package_];
5842 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5843 [delegate_ installPackage:package_];
5844 else if ([name isEqualToString:UCLocalize("REMOVE")])
5845 [delegate_ removePackage:package_];
5846 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5847 [delegate_ installPackage:package_];
5848 else _assert(false);
5851 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5852 NSString *context([sheet context]);
5854 if ([context isEqualToString:@"modify"]) {
5855 if (button != [sheet cancelButtonIndex]) {
5856 NSString *buttonName = [buttons_ objectAtIndex:button];
5857 [self _clickButtonWithName:buttonName];
5860 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5864 - (bool) _allowJavaScriptPanel {
5869 - (void) _customButtonClicked {
5870 int count([buttons_ count]);
5875 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5877 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5878 [buttons addObjectsFromArray:buttons_];
5880 UIActionSheet *sheet = [[[UIActionSheet alloc]
5883 cancelButtonTitle:nil
5884 destructiveButtonTitle:nil
5885 otherButtonTitles:nil
5888 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5890 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5891 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5893 [sheet setContext:@"modify"];
5895 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5899 // We don't want to allow non-commercial packages to do custom things to the install button,
5900 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5901 - (void) customButtonClicked {
5903 [super customButtonClicked];
5905 [self _customButtonClicked];
5908 - (void) reloadButtonClicked {
5909 // Don't reload a commerical package by tapping the loading button,
5910 // but if it's not an Install button, we should forward it on.
5911 if (![package_ uninstalled])
5912 [self _customButtonClicked];
5915 - (void) applyLoadingTitle {
5916 // Don't show "Loading" as the title. Ever.
5919 - (UIBarButtonItem *) rightButton {
5924 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5925 if ((self = [super init]) != nil) {
5926 database_ = database;
5927 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5928 name_ = [[NSString alloc] initWithString:name];
5929 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5933 - (void) reloadData {
5934 if (package_ != nil)
5935 [package_ autorelease];
5936 package_ = [database_ packageWithName:name_];
5938 [buttons_ removeAllObjects];
5940 if (package_ != nil) {
5943 package_ = [package_ retain];
5944 commercial_ = [package_ isCommercial];
5946 if ([package_ mode] != nil)
5947 [buttons_ addObject:UCLocalize("CLEAR")];
5948 if ([package_ source] == nil);
5949 else if ([package_ upgradableAndEssential:NO])
5950 [buttons_ addObject:UCLocalize("UPGRADE")];
5951 else if ([package_ uninstalled])
5952 [buttons_ addObject:UCLocalize("INSTALL")];
5954 [buttons_ addObject:UCLocalize("REINSTALL")];
5955 if (![package_ uninstalled])
5956 [buttons_ addObject:UCLocalize("REMOVE")];
5963 switch ([buttons_ count]) {
5964 case 0: title = nil; break;
5965 case 1: title = [buttons_ objectAtIndex:0]; break;
5966 default: title = UCLocalize("MODIFY"); break;
5969 button_ = [[UIBarButtonItem alloc]
5971 style:UIBarButtonItemStylePlain
5973 action:@selector(customButtonClicked)
5979 - (bool) isLoading {
5980 return commercial_ ? [super isLoading] : false;
5986 /* Package List Controller {{{ */
5987 @interface PackageListController : CYViewController <
5988 UITableViewDataSource,
5991 _transient Database *database_;
5993 NSMutableArray *packages_;
5994 NSMutableArray *sections_;
5996 NSMutableArray *index_;
5997 NSMutableDictionary *indices_;
6001 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6002 - (void) setDelegate:(id)delegate;
6003 - (void) resetCursor;
6007 @implementation PackageListController
6010 [packages_ release];
6011 [sections_ release];
6020 - (void) deselectWithAnimation:(BOOL)animated {
6021 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6024 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6025 CGRect base = [[self view] bounds];
6026 base.size.height -= bounds.size.height;
6027 base.origin = [list_ frame].origin;
6029 [UIView beginAnimations:nil context:NULL];
6030 [UIView setAnimationBeginsFromCurrentState:YES];
6031 [UIView setAnimationCurve:curve];
6032 [UIView setAnimationDuration:duration];
6033 [list_ setFrame:base];
6034 [UIView commitAnimations];
6037 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6038 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6041 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6042 [self resizeForKeyboardBounds:bounds duration:0];
6045 - (void) keyboardWillShow:(NSNotification *)notification {
6048 NSTimeInterval duration;
6049 UIViewAnimationCurve curve;
6050 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6051 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6052 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6053 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6055 CGRect kbframe = CGRectMake(round(center.x - bounds.size.width / 2.0), round(center.y - bounds.size.height / 2.0), bounds.size.width, bounds.size.height);
6056 UIViewController *base = self;
6057 while ([base parentViewController] != nil)
6058 base = [base parentViewController];
6059 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6060 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6062 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6065 - (void) keyboardWillHide:(NSNotification *)notification {
6066 NSTimeInterval duration;
6067 UIViewAnimationCurve curve;
6068 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6069 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6071 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6074 - (void) viewWillAppear:(BOOL)animated {
6075 [super viewWillAppear:animated];
6077 [self resizeForKeyboardBounds:CGRectZero];
6078 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6079 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6082 - (void) viewWillDisappear:(BOOL)animated {
6083 [super viewWillDisappear:animated];
6085 [self resizeForKeyboardBounds:CGRectZero];
6086 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6087 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6090 - (void) viewDidAppear:(BOOL)animated {
6091 [super viewDidAppear:animated];
6092 [self deselectWithAnimation:animated];
6095 - (void) didSelectPackage:(Package *)package {
6096 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6097 [view setDelegate:delegate_];
6098 [[self navigationController] pushViewController:view animated:YES];
6101 #if TryIndexedCollation
6102 + (BOOL) hasIndexedCollation {
6103 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6107 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6108 NSInteger count([sections_ count]);
6109 return count == 0 ? 1 : count;
6112 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6113 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6115 return [[sections_ objectAtIndex:section] name];
6118 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6119 if ([sections_ count] == 0)
6121 return [[sections_ objectAtIndex:section] count];
6124 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6125 @synchronized (database_) {
6126 if ([database_ era] != era_)
6129 Section *section([sections_ objectAtIndex:[path section]]);
6130 NSInteger row([path row]);
6131 Package *package([packages_ objectAtIndex:([section row] + row)]);
6132 return [[package retain] autorelease];
6135 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6136 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6138 cell = [[[PackageCell alloc] init] autorelease];
6139 [cell setPackage:[self packageAtIndexPath:path]];
6143 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6144 Package *package([self packageAtIndexPath:path]);
6145 package = [database_ packageWithName:[package id]];
6146 [self didSelectPackage:package];
6149 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6150 // XXX: is 20 the most optimal number here?
6151 return [packages_ count] > 20 ? index_ : nil;
6154 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6155 #if TryIndexedCollation
6156 if ([[self class] hasIndexedCollation]) {
6157 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6164 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6165 if ((self = [super init]) != nil) {
6166 database_ = database;
6167 title_ = [title copy];
6168 [[self navigationItem] setTitle:title_];
6170 #if TryIndexedCollation
6171 if ([[self class] hasIndexedCollation])
6172 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6175 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6177 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6179 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6180 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6182 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6183 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6184 [list_ setRowHeight:73];
6185 [[self view] addSubview:list_];
6187 [list_ setDataSource:self];
6188 [list_ setDelegate:self];
6192 - (void) setDelegate:(id)delegate {
6193 delegate_ = delegate;
6196 - (bool) hasPackage:(Package *)package {
6200 - (void) reloadData {
6203 era_ = [database_ era];
6204 NSArray *packages = [database_ packages];
6206 [packages_ removeAllObjects];
6207 [sections_ removeAllObjects];
6209 _profile(PackageTable$reloadData$Filter)
6210 for (Package *package in packages)
6211 if ([self hasPackage:package])
6212 [packages_ addObject:package];
6215 [indices_ removeAllObjects];
6217 Section *section = nil;
6219 #if TryIndexedCollation
6220 if ([[self class] hasIndexedCollation]) {
6221 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6222 NSArray *titles = [collation sectionIndexTitles];
6225 _profile(PackageTable$reloadData$Section)
6226 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6230 _profile(PackageTable$reloadData$Section$Package)
6231 package = [packages_ objectAtIndex:offset];
6232 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6235 while (secidx < index) {
6238 _profile(PackageTable$reloadData$Section$Allocate)
6239 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6242 _profile(PackageTable$reloadData$Section$Add)
6243 [sections_ addObject:section];
6247 [section addToCount];
6253 [index_ removeAllObjects];
6255 _profile(PackageTable$reloadData$Section)
6256 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6260 _profile(PackageTable$reloadData$Section$Package)
6261 package = [packages_ objectAtIndex:offset];
6262 index = [package index];
6265 if (section == nil || [section index] != index) {
6266 _profile(PackageTable$reloadData$Section$Allocate)
6267 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6270 [index_ addObject:[section name]];
6271 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6273 _profile(PackageTable$reloadData$Section$Add)
6274 [sections_ addObject:section];
6278 [section addToCount];
6283 _profile(PackageTable$reloadData$List)
6288 - (void) resetCursor {
6289 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6294 /* Filtered Package List Controller {{{ */
6295 @interface FilteredPackageListController : PackageListController {
6301 - (void) setObject:(id)object;
6302 - (void) setObject:(id)object forFilter:(SEL)filter;
6304 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6308 @implementation FilteredPackageListController
6316 - (void) setFilter:(SEL)filter {
6319 /* XXX: this is an unsafe optimization of doomy hell */
6320 Method method(class_getInstanceMethod([Package class], filter));
6321 _assert(method != NULL);
6322 imp_ = method_getImplementation(method);
6323 _assert(imp_ != NULL);
6326 - (void) setObject:(id)object {
6332 object_ = [object retain];
6335 - (void) setObject:(id)object forFilter:(SEL)filter {
6336 [self setFilter:filter];
6337 [self setObject:object];
6340 - (bool) hasPackage:(Package *)package {
6341 _profile(FilteredPackageTable$hasPackage)
6342 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6346 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6347 if ((self = [super initWithDatabase:database title:title]) != nil) {
6348 [self setFilter:filter];
6349 [self setObject:object];
6356 /* Home Controller {{{ */
6357 @interface HomeController : CYBrowserController {
6362 @implementation HomeController
6364 + (BOOL) shouldHideNavigationBar {
6368 - (NSURL *) navigationURL {
6369 return [NSURL URLWithString:@"cydia://home"];
6372 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6373 [super _setMoreHeaders:request];
6376 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6377 if (UniqueID_ != nil)
6378 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6380 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6383 - (void) aboutButtonClicked {
6384 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6386 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6387 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6388 [alert setCancelButtonIndex:0];
6391 @"Copyright (C) 2008-2011\n"
6392 "Jay Freeman (saurik)\n"
6393 "saurik@saurik.com\n"
6394 "http://www.saurik.com/"
6400 - (void) viewWillDisappear:(BOOL)animated {
6401 [super viewWillDisappear:animated];
6403 if ([[self class] shouldHideNavigationBar])
6404 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6407 - (void) viewWillAppear:(BOOL)animated {
6408 if (![self hasLoaded])
6409 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6411 [super viewWillAppear:animated];
6413 if ([[self class] shouldHideNavigationBar])
6414 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6417 - (void) viewDidLoad {
6418 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6419 initWithTitle:UCLocalize("ABOUT")
6420 style:UIBarButtonItemStylePlain
6422 action:@selector(aboutButtonClicked)
6428 /* Manage Controller {{{ */
6429 @interface ManageController : CYBrowserController {
6432 - (void) queueStatusDidChange;
6436 @implementation ManageController
6438 - (NSURL *) navigationURL {
6439 return [NSURL URLWithString:@"cydia://manage"];
6442 - (void) viewWillAppear:(BOOL)animated {
6443 if (![self hasLoaded])
6444 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6446 [super viewWillAppear:animated];
6449 - (void) viewDidLoad {
6450 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6451 initWithTitle:UCLocalize("SETTINGS")
6452 style:UIBarButtonItemStylePlain
6454 action:@selector(settingsButtonClicked)
6457 [self queueStatusDidChange];
6460 - (void) settingsButtonClicked {
6461 [delegate_ showSettings];
6465 - (void) queueButtonClicked {
6469 - (void) applyLoadingTitle {
6470 // Disable "Loading" title.
6473 - (void) applyRightButton {
6474 // Disable right button.
6478 - (void) queueStatusDidChange {
6480 if (!IsWildcat_ && Queuing_) {
6481 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6482 initWithTitle:UCLocalize("QUEUE")
6483 style:UIBarButtonItemStyleDone
6485 action:@selector(queueButtonClicked)
6488 [[self navigationItem] setRightBarButtonItem:nil];
6493 - (bool) isLoading {
6494 // Never show as loading.
6501 /* Refresh Bar {{{ */
6502 @interface RefreshBar : UINavigationBar {
6503 UIProgressIndicator *indicator_;
6504 UITextLabel *prompt_;
6505 UIProgressBar *progress_;
6506 UINavigationButton *cancel_;
6511 @implementation RefreshBar
6514 [indicator_ release];
6516 [progress_ release];
6521 - (void) positionViews {
6522 CGRect frame = [cancel_ frame];
6523 frame.size = [cancel_ sizeThatFits:frame.size];
6524 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6525 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6526 [cancel_ setFrame:frame];
6528 CGSize prgsize = {75, 100};
6530 [self frame].size.width - prgsize.width - 10,
6531 ([self frame].size.height - prgsize.height) / 2
6533 [progress_ setFrame:prgrect];
6535 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6536 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6537 CGRect indrect = {{indoffset, indoffset}, indsize};
6538 [indicator_ setFrame:indrect];
6540 CGSize prmsize = {215, indsize.height + 4};
6542 indoffset * 2 + indsize.width,
6543 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6545 [prompt_ setFrame:prmrect];
6548 - (void) setFrame:(CGRect)frame {
6549 [super setFrame:frame];
6550 [self positionViews];
6553 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6554 if ((self = [super initWithFrame:frame]) != nil) {
6555 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6557 [self setBarStyle:UIBarStyleBlack];
6559 UIBarStyle barstyle([self _barStyle:NO]);
6560 bool ugly(barstyle == UIBarStyleDefault);
6562 UIProgressIndicatorStyle style = ugly ?
6563 UIProgressIndicatorStyleMediumBrown :
6564 UIProgressIndicatorStyleMediumWhite;
6566 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6567 [indicator_ setStyle:style];
6568 [indicator_ startAnimation];
6569 [self addSubview:indicator_];
6571 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6572 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6573 [prompt_ setBackgroundColor:[UIColor clearColor]];
6574 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6575 [self addSubview:prompt_];
6577 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6578 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6579 [progress_ setStyle:0];
6580 [self addSubview:progress_];
6582 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6583 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6584 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6585 [cancel_ setBarStyle:barstyle];
6587 [self positionViews];
6591 - (void) setCancellable:(bool)cancellable {
6593 [self addSubview:cancel_];
6595 [cancel_ removeFromSuperview];
6599 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6600 [progress_ setProgress:0];
6604 [self setCancellable:NO];
6607 - (void) setPrompt:(NSString *)prompt {
6608 [prompt_ setText:prompt];
6611 - (void) setProgress:(float)progress {
6612 [progress_ setProgress:progress];
6618 @class CYNavigationController;
6620 /* Cydia Tab Bar Controller {{{ */
6621 @interface CYTabBarController : UITabBarController <
6622 UITabBarControllerDelegate,
6625 _transient Database *database_;
6626 RefreshBar *refreshbar_;
6630 // XXX: ok, "updatedelegate_"?...
6631 _transient NSObject<CydiaDelegate> *updatedelegate_;
6634 UIViewController *remembered_;
6635 _transient UIViewController *transient_;
6638 - (NSArray *) navigationURLCollection;
6639 - (void) dropBar:(BOOL)animated;
6640 - (void) beginUpdate;
6641 - (void) raiseBar:(BOOL)animated;
6646 @implementation CYTabBarController
6648 - (void) setUnselectedViewController:(UIViewController *)transient {
6649 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6650 if (transient != nil) {
6651 if (transient_ == nil)
6652 remembered_ = [[controllers objectAtIndex:0] retain];
6653 transient_ = transient;
6654 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6655 [controllers replaceObjectAtIndex:0 withObject:transient_];
6656 [self setSelectedIndex:0];
6657 [self setViewControllers:controllers];
6658 [self concealTabBarSelection];
6659 } else if (remembered_ != nil) {
6660 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6661 transient_ = transient;
6662 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6663 [remembered_ release];
6665 [self setViewControllers:controllers];
6666 [self revealTabBarSelection];
6670 - (UIViewController *) unselectedViewController {
6674 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6675 if ([self unselectedViewController])
6676 [self setUnselectedViewController:nil];
6679 - (NSArray *) navigationURLCollection {
6680 NSMutableArray *items([NSMutableArray array]);
6682 // XXX: Should this deal with transient view controllers?
6683 for (id navigation in [self viewControllers]) {
6684 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6686 [items addObject:stack];
6692 - (void) reloadData {
6693 for (CYViewController *controller in [self viewControllers])
6694 [controller reloadData];
6696 [(CYNavigationController *)[self unselectedViewController] reloadData];
6700 [refreshbar_ release];
6701 [[NSNotificationCenter defaultCenter] removeObserver:self];
6706 - (id) initWithDatabase:(Database *)database {
6707 if ((self = [super init]) != nil) {
6708 database_ = database;
6709 [self setDelegate:self];
6711 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6712 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6714 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6718 - (void) setUpdate:(NSDate *)date {
6722 - (void) beginUpdate {
6723 [refreshbar_ start];
6726 [updatedelegate_ retainNetworkActivityIndicator];
6730 detachNewThreadSelector:@selector(performUpdate)
6736 - (void) performUpdate { _pooled
6738 status.setDelegate(self);
6739 [database_ updateWithStatus:status];
6742 performSelectorOnMainThread:@selector(completeUpdate)
6748 - (void) stopUpdateWithSelector:(SEL)selector {
6750 [updatedelegate_ releaseNetworkActivityIndicator];
6752 [self raiseBar:YES];
6755 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6758 - (void) completeUpdate {
6761 [self stopUpdateWithSelector:@selector(reloadData)];
6764 - (void) cancelUpdate {
6765 [self stopUpdateWithSelector:@selector(updateData)];
6768 - (void) cancelPressed {
6769 [self cancelUpdate];
6776 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6777 [refreshbar_ setPrompt:[event compoundMessage]];
6780 - (bool) isProgressCancelled {
6784 - (void) setProgressCancellable:(NSNumber *)cancellable {
6785 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6788 - (void) setProgressPercent:(NSNumber *)percent {
6789 [refreshbar_ setProgress:[percent floatValue]];
6792 - (void) setUpdateDelegate:(id)delegate {
6793 updatedelegate_ = delegate;
6796 - (CGFloat) statusBarHeight {
6797 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6798 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6800 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6804 - (UIView *) transitionView {
6805 if ([self respondsToSelector:@selector(_transitionView)])
6806 return [self _transitionView];
6808 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6811 - (void) dropBar:(BOOL)animated {
6816 UIView *transition([self transitionView]);
6817 [[self view] addSubview:refreshbar_];
6819 CGRect barframe([refreshbar_ frame]);
6821 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6822 barframe.origin.y = [self statusBarHeight];
6824 barframe.origin.y = 0;
6826 [refreshbar_ setFrame:barframe];
6829 [UIView beginAnimations:nil context:NULL];
6831 CGRect viewframe = [transition frame];
6832 viewframe.origin.y += barframe.size.height;
6833 viewframe.size.height -= barframe.size.height;
6834 [transition setFrame:viewframe];
6837 [UIView commitAnimations];
6839 // Ensure bar has the proper width for our view, it might have changed
6840 barframe.size.width = viewframe.size.width;
6841 [refreshbar_ setFrame:barframe];
6843 // XXX: fix Apple's layout bug
6844 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6847 - (void) raiseBar:(BOOL)animated {
6852 UIView *transition([self transitionView]);
6853 [refreshbar_ removeFromSuperview];
6855 CGRect barframe([refreshbar_ frame]);
6858 [UIView beginAnimations:nil context:NULL];
6860 CGRect viewframe = [transition frame];
6861 viewframe.origin.y -= barframe.size.height;
6862 viewframe.size.height += barframe.size.height;
6863 [transition setFrame:viewframe];
6866 [UIView commitAnimations];
6868 // XXX: fix Apple's layout bug
6869 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6873 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6874 // XXX: fix Apple's layout bug
6875 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6879 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6880 bool dropped(dropped_);
6885 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6890 // XXX: fix Apple's layout bug
6891 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6894 - (void) statusBarFrameChanged:(NSNotification *)notification {
6903 /* Cydia Navigation Controller {{{ */
6904 @interface CYNavigationController : UINavigationController {
6905 _transient Database *database_;
6906 _transient id<UINavigationControllerDelegate> delegate_;
6909 - (NSArray *) navigationURLCollection;
6910 - (id) initWithDatabase:(Database *)database;
6911 - (void) reloadData;
6916 @implementation CYNavigationController
6918 - (NSArray *) navigationURLCollection {
6919 NSMutableArray *stack([NSMutableArray array]);
6921 for (CYViewController *controller in [self viewControllers]) {
6922 NSString *url = [[controller navigationURL] absoluteString];
6924 [stack addObject:url];
6930 - (void) reloadData {
6931 for (CYViewController *page in [self viewControllers]) {
6932 // Only reload controllers that have already loaded.
6933 // This prevents a page from accidentally loading too
6934 // early if it hasn't been shown on the screen yet.
6935 if ([page hasLoaded])
6940 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6941 delegate_ = delegate;
6944 - (id) initWithDatabase:(Database *)database {
6945 if ((self = [super init]) != nil) {
6946 database_ = database;
6953 /* Cydia:// Protocol {{{ */
6954 @interface CydiaURLProtocol : NSURLProtocol {
6959 @implementation CydiaURLProtocol
6961 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6962 NSURL *url([request URL]);
6966 NSString *scheme([[url scheme] lowercaseString]);
6967 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6969 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6975 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6979 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6980 id<NSURLProtocolClient> client([self client]);
6982 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6984 NSData *data(UIImagePNGRepresentation(icon));
6986 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6987 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6988 [client URLProtocol:self didLoadData:data];
6989 [client URLProtocolDidFinishLoading:self];
6993 - (void) startLoading {
6994 id<NSURLProtocolClient> client([self client]);
6995 NSURLRequest *request([self request]);
6997 NSURL *url([request URL]);
6998 NSString *href([url absoluteString]);
6999 NSString *scheme([[url scheme] lowercaseString]);
7003 if ([scheme isEqualToString:@"cydia"])
7004 path = [href substringFromIndex:8];
7005 else if ([scheme isEqualToString:@"about"])
7006 path = [href substringFromIndex:12];
7007 else _assert(false);
7009 NSRange slash([path rangeOfString:@"/"]);
7012 if (slash.location == NSNotFound) {
7016 command = [path substringToIndex:slash.location];
7017 path = [path substringFromIndex:(slash.location + 1)];
7020 Database *database([Database sharedInstance]);
7022 if ([command isEqualToString:@"package-icon"]) {
7025 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7026 Package *package([database packageWithName:path]);
7029 UIImage *icon([package icon]);
7030 [self _returnPNGWithImage:icon forRequest:request];
7031 } else if ([command isEqualToString:@"source-icon"]) {
7034 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7035 NSString *source(Simplify(path));
7036 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7038 icon = [UIImage applicationImageNamed:@"unknown.png"];
7039 [self _returnPNGWithImage:icon forRequest:request];
7040 } else if ([command isEqualToString:@"uikit-image"]) {
7043 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7044 UIImage *icon(_UIImageWithName(path));
7045 [self _returnPNGWithImage:icon forRequest:request];
7046 } else if ([command isEqualToString:@"section-icon"]) {
7049 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7050 NSString *section(Simplify(path));
7051 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7053 icon = [UIImage applicationImageNamed:@"unknown.png"];
7054 [self _returnPNGWithImage:icon forRequest:request];
7056 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7060 - (void) stopLoading {
7066 /* Section Controller {{{ */
7067 @interface SectionController : FilteredPackageListController {
7071 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7075 @implementation SectionController
7077 - (NSURL *) navigationURL {
7078 NSString *name = section_;
7082 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7085 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7088 title = UCLocalize("ALL_PACKAGES");
7089 else if (![name isEqual:@""])
7090 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7092 title = UCLocalize("NO_SECTION");
7094 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7101 /* Sections Controller {{{ */
7102 @interface SectionsController : CYViewController <
7103 UITableViewDataSource,
7106 _transient Database *database_;
7107 NSMutableArray *sections_;
7108 NSMutableArray *filtered_;
7113 - (id) initWithDatabase:(Database *)database;
7114 - (void) editButtonClicked;
7118 @implementation SectionsController
7121 [self releaseSubviews];
7122 [sections_ release];
7123 [filtered_ release];
7128 - (NSURL *) navigationURL {
7129 return [NSURL URLWithString:@"cydia://sections"];
7132 - (void) updateNavigationItem {
7133 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7134 if ([sections_ count] == 0) {
7135 [[self navigationItem] setRightBarButtonItem:nil];
7137 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7138 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7140 action:@selector(editButtonClicked)
7141 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7145 - (BOOL) isEditing {
7149 - (void) setEditing:(BOOL)editing {
7150 if ((editing_ = editing))
7153 [delegate_ updateData];
7155 [self updateNavigationItem];
7158 - (void) viewDidAppear:(BOOL)animated {
7159 [super viewDidAppear:animated];
7160 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7163 - (void) viewWillDisappear:(BOOL)animated {
7164 [super viewWillDisappear:animated];
7165 if (editing_) [self setEditing:NO];
7168 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7169 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7173 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7174 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7177 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7181 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7182 static NSString *reuseIdentifier = @"SectionCell";
7184 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7186 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7188 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7193 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7197 Section *section = [self sectionAtIndexPath:indexPath];
7199 SectionController *controller = [[[SectionController alloc]
7200 initWithDatabase:database_
7201 section:[section name]
7203 [controller setDelegate:delegate_];
7205 [[self navigationController] pushViewController:controller animated:YES];
7209 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7211 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7212 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7213 [list_ setRowHeight:45.0f];
7214 [list_ setDataSource:self];
7215 [list_ setDelegate:self];
7216 [[self view] addSubview:list_];
7219 - (void) viewDidLoad {
7220 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7223 - (void) releaseSubviews {
7228 - (id) initWithDatabase:(Database *)database {
7229 if ((self = [super init]) != nil) {
7230 database_ = database;
7232 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7233 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7237 - (void) reloadData {
7240 NSArray *packages = [database_ packages];
7242 [sections_ removeAllObjects];
7243 [filtered_ removeAllObjects];
7245 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7248 for (Package *package in packages) {
7249 NSString *name([package section]);
7250 NSString *key(name == nil ? @"" : name);
7254 _profile(SectionsView$reloadData$Section)
7255 section = [sections objectForKey:key];
7256 if (section == nil) {
7257 _profile(SectionsView$reloadData$Section$Allocate)
7258 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7259 [sections setObject:section forKey:key];
7264 [section addToCount];
7266 _profile(SectionsView$reloadData$Filter)
7267 if (![package valid] || ![package visible])
7275 [sections_ addObjectsFromArray:[sections allValues]];
7277 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7279 for (Section *section in sections_) {
7280 size_t count([section row]);
7284 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7285 [section setCount:count];
7286 [filtered_ addObject:section];
7289 [self updateNavigationItem];
7294 - (void) editButtonClicked {
7295 [self setEditing:(!editing_)];
7301 /* Changes Controller {{{ */
7302 @interface ChangesController : CYViewController <
7303 UITableViewDataSource,
7306 _transient Database *database_;
7308 CFMutableArrayRef packages_;
7309 NSMutableArray *sections_;
7312 BOOL hasSentFirstLoad_;
7315 - (id) initWithDatabase:(Database *)database;
7319 @implementation ChangesController
7322 [self releaseSubviews];
7323 CFRelease(packages_);
7324 [sections_ release];
7329 - (NSURL *) navigationURL {
7330 return [NSURL URLWithString:@"cydia://changes"];
7333 - (void) viewWillAppear:(BOOL)animated {
7334 // Loads after it appears, so don't load beforehand.
7336 [super viewWillAppear:animated];
7339 - (void) viewDidAppear:(BOOL)animated {
7340 [super viewDidAppear:animated];
7342 if (!hasSentFirstLoad_) {
7343 hasSentFirstLoad_ = YES;
7344 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7346 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7350 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7351 NSInteger count([sections_ count]);
7352 return count == 0 ? 1 : count;
7355 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7356 if ([sections_ count] == 0)
7358 return [[sections_ objectAtIndex:section] name];
7361 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7362 if ([sections_ count] == 0)
7364 return [[sections_ objectAtIndex:section] count];
7367 - (Package *) packageAtIndex:(NSUInteger)index {
7368 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7371 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7372 @synchronized (database_) {
7373 if ([database_ era] != era_)
7376 NSUInteger sectionIndex([path section]);
7377 if (sectionIndex >= [sections_ count])
7379 Section *section([sections_ objectAtIndex:sectionIndex]);
7380 NSInteger row([path row]);
7381 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7384 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7385 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7387 cell = [[[PackageCell alloc] init] autorelease];
7388 [cell setPackage:[self packageAtIndexPath:path]];
7392 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7393 Package *package([self packageAtIndexPath:path]);
7394 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7395 [view setDelegate:delegate_];
7396 [[self navigationController] pushViewController:view animated:YES];
7400 - (void) refreshButtonClicked {
7401 [delegate_ beginUpdate];
7402 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7405 - (void) upgradeButtonClicked {
7406 [delegate_ distUpgrade];
7410 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7412 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7413 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7414 [list_ setRowHeight:73];
7415 [list_ setDataSource:self];
7416 [list_ setDelegate:self];
7417 [[self view] addSubview:list_];
7420 - (void) viewDidLoad {
7421 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7424 - (void) releaseSubviews {
7429 - (id) initWithDatabase:(Database *)database {
7430 if ((self = [super init]) != nil) {
7431 database_ = database;
7433 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7434 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7438 // this mostly works because reloadData (below) is @synchronized (database_)
7439 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7440 - (void) _reloadPackages:(NSArray *)packages {
7441 CFRelease(packages_);
7442 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7445 _profile(ChangesController$_reloadPackages$Filter)
7446 for (Package *package in packages)
7447 if ([package upgradableAndEssential:YES] || [package visible])
7448 CFArrayAppendValue(packages_, package);
7451 _profile(ChangesController$_reloadPackages$radixSort)
7452 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7457 - (void) reloadData {
7458 @synchronized (database_) {
7459 era_ = [database_ era];
7460 NSArray *packages = [database_ packages];
7462 [sections_ removeAllObjects];
7465 UIProgressHUD *hud([delegate_ addProgressHUD]);
7466 [hud setText:UCLocalize("LOADING")];
7467 //NSLog(@"HUD:%@::%@", delegate_, hud);
7468 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7469 [delegate_ removeProgressHUD:hud];
7471 [self _reloadPackages:packages];
7474 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7475 Section *ignored = nil;
7476 Section *section = nil;
7480 bool unseens = false;
7482 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7484 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7485 Package *package = [self packageAtIndex:offset];
7487 BOOL uae = [package upgradableAndEssential:YES];
7491 time_t seen([package seen]);
7493 if (section == nil || last != seen) {
7497 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7500 _profile(ChangesController$reloadData$Allocate)
7501 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7502 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7503 [sections_ addObject:section];
7507 [section addToCount];
7508 } else if ([package ignored]) {
7509 if (ignored == nil) {
7510 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7512 [ignored addToCount];
7515 [upgradable addToCount];
7520 CFRelease(formatter);
7523 Section *last = [sections_ lastObject];
7524 size_t count = [last count];
7525 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7526 [sections_ removeLastObject];
7529 if ([ignored count] != 0)
7530 [sections_ insertObject:ignored atIndex:0];
7532 [sections_ insertObject:upgradable atIndex:0];
7537 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7538 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7539 style:UIBarButtonItemStylePlain
7541 action:@selector(upgradeButtonClicked)
7544 if (![delegate_ updating])
7545 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7546 initWithTitle:UCLocalize("REFRESH")
7547 style:UIBarButtonItemStylePlain
7549 action:@selector(refreshButtonClicked)
7557 /* Search Controller {{{ */
7558 @interface SearchController : FilteredPackageListController <
7561 UISearchBar *search_;
7565 - (id) initWithDatabase:(Database *)database;
7566 - (void) setSearchTerm:(NSString *)term;
7567 - (void) reloadData;
7571 @implementation SearchController
7578 - (NSURL *) navigationURL {
7579 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7580 return [NSURL URLWithString:@"cydia://search"];
7582 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7585 - (void) setSearchTerm:(NSString *)searchTerm {
7586 [search_ setText:searchTerm];
7590 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7591 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7592 [search_ resignFirstResponder];
7596 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7597 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7601 - (id) initWithDatabase:(Database *)database {
7602 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7603 search_ = [[UISearchBar alloc] init];
7607 - (void) viewDidAppear:(BOOL)animated {
7608 [super viewDidAppear:animated];
7610 if (!searchloaded_) {
7611 searchloaded_ = YES;
7612 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7613 [search_ layoutSubviews];
7614 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7616 UITextField *textField;
7617 if ([search_ respondsToSelector:@selector(searchField)])
7618 textField = [search_ searchField];
7620 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7622 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7623 [search_ setDelegate:self];
7624 [textField setEnablesReturnKeyAutomatically:NO];
7625 [[self navigationItem] setTitleView:textField];
7629 - (void) reloadData {
7630 [self setObject:[search_ text]];
7635 - (void) didSelectPackage:(Package *)package {
7636 [search_ resignFirstResponder];
7637 [super didSelectPackage:package];
7642 /* Package Settings Controller {{{ */
7643 @interface PackageSettingsController : CYViewController <
7644 UITableViewDataSource,
7647 _transient Database *database_;
7650 UITableView *table_;
7651 UISwitch *subscribedSwitch_;
7652 UISwitch *ignoredSwitch_;
7653 UITableViewCell *subscribedCell_;
7654 UITableViewCell *ignoredCell_;
7657 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7661 @implementation PackageSettingsController
7664 [self releaseSubviews];
7671 - (NSURL *) navigationURL {
7672 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7675 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7676 if (package_ == nil)
7679 if ([package_ installed] == nil)
7685 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7686 if (package_ == nil)
7689 // both sections contain just one item right now.
7693 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7697 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7699 return UCLocalize("SHOW_ALL_CHANGES_EX");
7701 return UCLocalize("IGNORE_UPGRADES_EX");
7704 - (void) onSubscribed:(id)control {
7705 bool value([control isOn]);
7706 if (package_ == nil)
7708 if ([package_ setSubscribed:value])
7709 [delegate_ updateData];
7712 - (void) _updateIgnored {
7713 const char *package([name_ UTF8String]);
7714 bool on([ignoredSwitch_ isOn]);
7716 pid_t pid(ExecFork());
7718 FILE *dpkg(popen("dpkg --set-selections", "w"));
7719 fwrite(package, strlen(package), 1, dpkg);
7722 fwrite(" hold\n", 6, 1, dpkg);
7724 fwrite(" install\n", 9, 1, dpkg);
7734 int result(waitpid(pid, &status, 0));
7737 _assert(result == pid);
7743 - (void) onIgnored:(id)control {
7744 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7745 [invocation setTarget:self];
7746 [invocation setSelector:@selector(_updateIgnored)];
7748 [delegate_ reloadDataWithInvocation:invocation];
7751 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7752 if (package_ == nil)
7755 switch ([indexPath section]) {
7756 case 0: return subscribedCell_;
7757 case 1: return ignoredCell_;
7766 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7768 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7769 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7770 [table_ setDataSource:self];
7771 [table_ setDelegate:self];
7772 [[self view] addSubview:table_];
7774 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7775 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7776 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7778 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7779 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7780 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7782 subscribedCell_ = [[UITableViewCell alloc] init];
7783 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7784 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7785 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7787 ignoredCell_ = [[UITableViewCell alloc] init];
7788 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7789 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7790 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7793 - (void) viewDidLoad {
7794 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7797 - (void) releaseSubviews {
7798 [ignoredCell_ release];
7801 [subscribedCell_ release];
7802 subscribedCell_ = nil;
7807 [ignoredSwitch_ release];
7808 ignoredSwitch_ = nil;
7810 [subscribedSwitch_ release];
7811 subscribedSwitch_ = nil;
7814 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7815 if ((self = [super init]) != nil) {
7816 database_ = database;
7817 name_ = [package retain];
7821 - (void) reloadData {
7824 if (package_ != nil)
7825 [package_ autorelease];
7826 package_ = [database_ packageWithName:name_];
7828 if (package_ != nil) {
7829 package_ = [package_ retain];
7830 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7831 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7832 } // XXX: what now, G?
7834 [table_ reloadData];
7840 /* Installed Controller {{{ */
7841 @interface InstalledController : FilteredPackageListController {
7845 - (id) initWithDatabase:(Database *)database;
7847 - (void) updateRoleButton;
7848 - (void) queueStatusDidChange;
7852 @implementation InstalledController
7858 - (NSURL *) navigationURL {
7859 return [NSURL URLWithString:@"cydia://installed"];
7862 - (id) initWithDatabase:(Database *)database {
7863 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7864 [self updateRoleButton];
7865 [self queueStatusDidChange];
7870 - (void) queueButtonClicked {
7875 - (void) queueStatusDidChange {
7879 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7880 initWithTitle:UCLocalize("QUEUE")
7881 style:UIBarButtonItemStyleDone
7883 action:@selector(queueButtonClicked)
7886 [[self navigationItem] setLeftBarButtonItem:nil];
7892 - (void) updateRoleButton {
7893 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7894 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7895 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7896 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7898 action:@selector(roleButtonClicked)
7902 - (void) roleButtonClicked {
7903 [self setObject:[NSNumber numberWithBool:expert_]];
7907 [self updateRoleButton];
7913 /* Source Cell {{{ */
7914 @interface SourceCell : CYTableViewCell <
7922 - (void) setSource:(Source *)source;
7926 @implementation SourceCell
7928 - (void) clearSource {
7938 - (void) setSource:(Source *)source {
7942 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7944 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7945 icon_ = [icon_ retain];
7947 origin_ = [[source name] retain];
7948 label_ = [[source uri] retain];
7950 [content_ setNeedsDisplay];
7958 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7959 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7960 UIView *content([self contentView]);
7961 CGRect bounds([content bounds]);
7963 content_ = [[ContentView alloc] initWithFrame:bounds];
7964 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7965 [content_ setBackgroundColor:[UIColor whiteColor]];
7966 [content addSubview:content_];
7968 [content_ setDelegate:self];
7969 [content_ setOpaque:YES];
7973 - (NSString *) accessibilityLabel {
7977 - (void) drawContentRect:(CGRect)rect {
7978 bool highlighted(highlighted_);
7979 float width(rect.size.width);
7982 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7989 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7993 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7998 /* Source Controller {{{ */
7999 @interface SourceController : FilteredPackageListController {
8000 _transient Source *source_;
8004 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8008 @implementation SourceController
8010 - (NSURL *) navigationURL {
8011 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8014 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8015 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8017 key_ = [[source key] retain];
8021 - (void) reloadData {
8022 source_ = [database_ sourceWithKey:key_];
8024 key_ = [[source_ key] retain];
8025 [self setObject:source_];
8026 [[self navigationItem] setTitle:[source_ label]];
8033 /* Sources Controller {{{ */
8034 @interface SourcesController : CYViewController <
8035 UITableViewDataSource,
8038 _transient Database *database_;
8040 NSMutableArray *sources_;
8044 UIProgressHUD *hud_;
8047 //NSURLConnection *installer_;
8048 NSURLConnection *trivial_;
8049 NSURLConnection *trivial_bz2_;
8050 NSURLConnection *trivial_gz_;
8051 //NSURLConnection *automatic_;
8056 - (id) initWithDatabase:(Database *)database;
8057 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8061 @implementation SourcesController
8063 - (void) _releaseConnection:(NSURLConnection *)connection {
8064 if (connection != nil) {
8065 [connection cancel];
8066 //[connection setDelegate:nil];
8067 [connection release];
8072 [self releaseSubviews];
8078 //[self _releaseConnection:installer_];
8079 [self _releaseConnection:trivial_];
8080 [self _releaseConnection:trivial_gz_];
8081 [self _releaseConnection:trivial_bz2_];
8082 //[self _releaseConnection:automatic_];
8088 - (NSURL *) navigationURL {
8089 return [NSURL URLWithString:@"cydia://sources"];
8092 - (void) viewDidAppear:(BOOL)animated {
8093 [super viewDidAppear:animated];
8094 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8097 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8098 return offset_ == 0 ? 1 : 2;
8101 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8102 switch (section + (offset_ == 0 ? 1 : 0)) {
8103 case 0: return UCLocalize("ENTERED_BY_USER");
8104 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8110 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8111 int count = [sources_ count];
8113 case 0: return (offset_ == 0 ? count : offset_);
8114 case 1: return count - offset_;
8120 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8122 switch (indexPath.section) {
8123 case 0: idx = indexPath.row; break;
8124 case 1: idx = indexPath.row + offset_; break;
8128 return [sources_ objectAtIndex:idx];
8131 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8132 static NSString *cellIdentifier = @"SourceCell";
8134 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8135 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8136 [cell setSource:[self sourceAtIndexPath:indexPath]];
8137 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8142 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8143 Source *source = [self sourceAtIndexPath:indexPath];
8145 SourceController *controller = [[[SourceController alloc]
8146 initWithDatabase:database_
8150 [controller setDelegate:delegate_];
8152 [[self navigationController] pushViewController:controller animated:YES];
8155 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8156 Source *source = [self sourceAtIndexPath:indexPath];
8157 return [source record] != nil;
8160 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8161 Source *source = [self sourceAtIndexPath:indexPath];
8162 [Sources_ removeObjectForKey:[source key]];
8163 [delegate_ syncData];
8167 [delegate_ addTrivialSource:href_];
8168 [delegate_ syncData];
8171 - (NSString *) getWarning {
8172 NSString *href(href_);
8173 NSRange colon([href rangeOfString:@"://"]);
8174 if (colon.location != NSNotFound)
8175 href = [href substringFromIndex:(colon.location + 3)];
8176 href = [href stringByAddingPercentEscapes];
8177 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8178 href = [href stringByCachingURLWithCurrentCDN];
8180 NSURL *url([NSURL URLWithString:href]);
8182 NSStringEncoding encoding;
8183 NSError *error(nil);
8185 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8186 return [warning length] == 0 ? nil : warning;
8190 - (void) _endConnection:(NSURLConnection *)connection {
8191 // XXX: the memory management in this method is horribly awkward
8193 NSURLConnection **field = NULL;
8194 if (connection == trivial_)
8196 else if (connection == trivial_bz2_)
8197 field = &trivial_bz2_;
8198 else if (connection == trivial_gz_)
8199 field = &trivial_gz_;
8200 _assert(field != NULL);
8201 [connection release];
8206 trivial_bz2_ == nil &&
8212 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8215 UIAlertView *alert = [[[UIAlertView alloc]
8216 initWithTitle:UCLocalize("SOURCE_WARNING")
8219 cancelButtonTitle:UCLocalize("CANCEL")
8221 UCLocalize("ADD_ANYWAY"),
8225 [alert setContext:@"warning"];
8226 [alert setNumberOfRows:1];
8230 } else if (error_ != nil) {
8231 UIAlertView *alert = [[[UIAlertView alloc]
8232 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8233 message:[error_ localizedDescription]
8235 cancelButtonTitle:UCLocalize("OK")
8236 otherButtonTitles:nil
8239 [alert setContext:@"urlerror"];
8242 UIAlertView *alert = [[[UIAlertView alloc]
8243 initWithTitle:UCLocalize("NOT_REPOSITORY")
8244 message:UCLocalize("NOT_REPOSITORY_EX")
8246 cancelButtonTitle:UCLocalize("OK")
8247 otherButtonTitles:nil
8250 [alert setContext:@"trivial"];
8254 [delegate_ releaseNetworkActivityIndicator];
8256 [delegate_ removeProgressHUD:hud_];
8265 if (error_ != nil) {
8272 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8273 switch ([response statusCode]) {
8279 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8280 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8282 error_ = [error retain];
8283 [self _endConnection:connection];
8286 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8287 [self _endConnection:connection];
8290 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8291 NSMutableURLRequest *request = [NSMutableURLRequest
8292 requestWithURL:[NSURL URLWithString:href]
8293 cachePolicy:NSURLRequestUseProtocolCachePolicy
8294 timeoutInterval:120.0
8297 [request setHTTPMethod:method];
8299 if (Machine_ != NULL)
8300 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8301 if (UniqueID_ != nil)
8302 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8304 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8306 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8309 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8310 NSString *context([alert context]);
8312 if ([context isEqualToString:@"source"]) {
8315 NSString *href = [[alert textField] text];
8317 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8319 if (![href hasSuffix:@"/"])
8320 href_ = [href stringByAppendingString:@"/"];
8323 href_ = [href_ retain];
8325 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8326 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8327 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8328 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8332 // XXX: this is stupid
8333 hud_ = [[delegate_ addProgressHUD] retain];
8334 [hud_ setText:UCLocalize("VERIFYING_URL")];
8335 [delegate_ retainNetworkActivityIndicator];
8344 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8345 } else if ([context isEqualToString:@"trivial"])
8346 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8347 else if ([context isEqualToString:@"urlerror"])
8348 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8349 else if ([context isEqualToString:@"warning"]) {
8364 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8369 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8371 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8372 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8373 [list_ setRowHeight:56];
8374 [list_ setDataSource:self];
8375 [list_ setDelegate:self];
8376 [[self view] addSubview:list_];
8379 - (void) viewDidLoad {
8380 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8381 [self updateButtonsForEditingStatus:NO animated:NO];
8384 - (void) releaseSubviews {
8389 - (id) initWithDatabase:(Database *)database {
8390 if ((self = [super init]) != nil) {
8391 database_ = database;
8392 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8396 - (void) reloadData {
8400 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8403 [sources_ removeAllObjects];
8404 [sources_ addObjectsFromArray:[database_ sources]];
8406 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8409 int count([sources_ count]);
8411 for (int i = 0; i != count; i++) {
8412 if ([[sources_ objectAtIndex:i] record] == nil)
8417 [list_ setEditing:NO];
8418 [self updateButtonsForEditingStatus:NO animated:NO];
8422 - (void) showAddSourcePrompt {
8423 UIAlertView *alert = [[[UIAlertView alloc]
8424 initWithTitle:UCLocalize("ENTER_APT_URL")
8427 cancelButtonTitle:UCLocalize("CANCEL")
8429 UCLocalize("ADD_SOURCE"),
8433 [alert setContext:@"source"];
8434 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8436 [alert setNumberOfRows:1];
8437 [alert addTextFieldWithValue:@"http://" label:@""];
8439 UITextInputTraits *traits = [[alert textField] textInputTraits];
8440 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8441 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8442 [traits setKeyboardType:UIKeyboardTypeURL];
8443 // XXX: UIReturnKeyDone
8444 [traits setReturnKeyType:UIReturnKeyNext];
8449 - (void) addButtonClicked {
8450 [self showAddSourcePrompt];
8453 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8454 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8455 initWithTitle:UCLocalize("ADD")
8456 style:UIBarButtonItemStylePlain
8458 action:@selector(addButtonClicked)
8459 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8461 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8462 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8463 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8465 action:@selector(editButtonClicked)
8466 ] autorelease] animated:animated];
8468 if (IsWildcat_ && !editing)
8469 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8470 initWithTitle:UCLocalize("SETTINGS")
8471 style:UIBarButtonItemStylePlain
8473 action:@selector(settingsButtonClicked)
8477 - (void) settingsButtonClicked {
8478 [delegate_ showSettings];
8481 - (void) editButtonClicked {
8482 [list_ setEditing:![list_ isEditing] animated:YES];
8484 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8490 /* Settings Controller {{{ */
8491 @interface SettingsController : CYViewController <
8492 UITableViewDataSource,
8495 _transient Database *database_;
8496 // XXX: ok, "roledelegate_"?...
8497 _transient id roledelegate_;
8498 UITableView *table_;
8499 UISegmentedControl *segment_;
8503 - (void) showDoneButton;
8504 - (void) resizeSegmentedControl;
8508 @implementation SettingsController
8511 [self releaseSubviews];
8517 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8519 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8520 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8521 [table_ setDelegate:self];
8522 [table_ setDataSource:self];
8523 [[self view] addSubview:table_];
8525 NSArray *items = [NSArray arrayWithObjects:
8527 UCLocalize("HACKER"),
8528 UCLocalize("DEVELOPER"),
8530 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8531 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8532 [container_ addSubview:segment_];
8535 - (void) viewDidLoad {
8536 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8539 if ([Role_ isEqualToString:@"User"]) index = 0;
8540 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8541 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8543 [segment_ setSelectedSegmentIndex:index];
8544 [self showDoneButton];
8547 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8548 [self resizeSegmentedControl];
8551 - (void) releaseSubviews {
8558 [container_ release];
8562 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8563 if ((self = [super init]) != nil) {
8564 database_ = database;
8565 roledelegate_ = delegate;
8569 - (void) resizeSegmentedControl {
8570 CGFloat width = [[self view] frame].size.width;
8571 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8574 - (void) viewWillAppear:(BOOL)animated {
8575 [super viewWillAppear:animated];
8577 [self resizeSegmentedControl];
8580 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8581 [self resizeSegmentedControl];
8584 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8585 [self resizeSegmentedControl];
8589 NSString *role(nil);
8591 switch ([segment_ selectedSegmentIndex]) {
8592 case 0: role = @"User"; break;
8593 case 1: role = @"Hacker"; break;
8594 case 2: role = @"Developer"; break;
8599 if (![role isEqualToString:Role_]) {
8600 bool rolling(Role_ == nil);
8603 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8607 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8611 [roledelegate_ loadData];
8613 [roledelegate_ updateData];
8617 - (void) segmentChanged:(UISegmentedControl *)control {
8618 [self showDoneButton];
8621 - (void) saveAndClose {
8624 [[self navigationItem] setRightBarButtonItem:nil];
8625 [[self navigationController] dismissModalViewControllerAnimated:YES];
8628 - (void) doneButtonClicked {
8629 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8630 [spinner startAnimating];
8631 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8632 [[self navigationItem] setRightBarButtonItem:spinItem];
8634 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8637 - (void) showDoneButton {
8638 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8639 initWithTitle:UCLocalize("DONE")
8640 style:UIBarButtonItemStyleDone
8642 action:@selector(doneButtonClicked)
8643 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8646 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8647 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8651 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8655 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8656 return nil; // This method is required by the protocol.
8659 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8661 return UCLocalize("ROLE_EX");
8663 return [NSString stringWithFormat:
8664 @"%@: %@\n%@: %@\n%@: %@",
8665 UCLocalize("USER"), UCLocalize("USER_EX"),
8666 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8667 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8672 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8673 return section == 3 ? 44.0f : 0;
8676 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8677 return section == 3 ? container_ : nil;
8680 - (void) reloadData {
8682 [table_ reloadData];
8687 /* Stash Controller {{{ */
8688 @interface StashController : CYViewController {
8689 UIActivityIndicatorView *spinner_;
8696 @implementation StashController
8699 [self releaseSubviews];
8705 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8706 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8708 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8709 CGRect spinrect = [spinner_ frame];
8710 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8711 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8712 [spinner_ setFrame:spinrect];
8713 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8714 [[self view] addSubview:spinner_];
8715 [spinner_ startAnimating];
8718 captrect.size.width = [[self view] frame].size.width;
8719 captrect.size.height = 40.0f;
8720 captrect.origin.x = 0;
8721 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8722 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8723 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8724 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8725 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8726 [caption_ setTextColor:[UIColor whiteColor]];
8727 [caption_ setBackgroundColor:[UIColor clearColor]];
8728 [caption_ setShadowColor:[UIColor blackColor]];
8729 [caption_ setTextAlignment:UITextAlignmentCenter];
8730 [[self view] addSubview:caption_];
8733 statusrect.size.width = [[self view] frame].size.width;
8734 statusrect.size.height = 30.0f;
8735 statusrect.origin.x = 0;
8736 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8737 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8738 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8739 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8740 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8741 [status_ setTextColor:[UIColor whiteColor]];
8742 [status_ setBackgroundColor:[UIColor clearColor]];
8743 [status_ setShadowColor:[UIColor blackColor]];
8744 [status_ setTextAlignment:UITextAlignmentCenter];
8745 [[self view] addSubview:status_];
8748 - (void) releaseSubviews {
8762 @interface Cydia : UIApplication <
8763 ConfirmationControllerDelegate,
8766 UINavigationControllerDelegate,
8767 UITabBarControllerDelegate
8769 // XXX: evaluate all fields for _transient
8772 CYTabBarController *tabbar_;
8773 CYEmulatedLoadingController *emulated_;
8775 NSMutableArray *essential_;
8776 NSMutableArray *broken_;
8778 Database *database_;
8785 StashController *stash_;
8794 @implementation Cydia
8796 - (void) beginUpdate {
8797 [tabbar_ beginUpdate];
8801 return [tabbar_ updating];
8805 if ([broken_ count] != 0) {
8806 int count = [broken_ count];
8808 UIAlertView *alert = [[[UIAlertView alloc]
8809 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8810 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8812 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8814 UCLocalize("TEMPORARY_IGNORE"),
8818 [alert setContext:@"fixhalf"];
8819 [alert setNumberOfRows:2];
8821 } else if (!Ignored_ && [essential_ count] != 0) {
8822 int count = [essential_ count];
8824 UIAlertView *alert = [[[UIAlertView alloc]
8825 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8826 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8828 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8830 UCLocalize("UPGRADE_ESSENTIAL"),
8831 UCLocalize("COMPLETE_UPGRADE"),
8835 [alert setContext:@"upgrade"];
8840 - (void) _saveConfig {
8846 NSString *error(nil);
8848 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8850 NSError *error(nil);
8851 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8852 NSLog(@"failure to save metadata data: %@", error);
8857 NSLog(@"failure to serialize metadata: %@", error);
8862 // Navigation controller for the queuing badge.
8863 - (CYNavigationController *) queueNavigationController {
8864 NSArray *controllers = [tabbar_ viewControllers];
8865 return [controllers objectAtIndex:3];
8868 - (void) _updateData {
8871 [tabbar_ reloadData];
8873 CYNavigationController *navigation = [self queueNavigationController];
8875 id queuedelegate = nil;
8876 if ([[navigation viewControllers] count] > 0)
8877 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8879 [queuedelegate queueStatusDidChange];
8880 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8883 - (void) _refreshIfPossible:(NSDate *)update {
8884 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8886 bool recently = false;
8887 if (update != nil) {
8888 NSTimeInterval interval([update timeIntervalSinceNow]);
8889 if (interval <= 0 && interval > -(15*60))
8893 // Don't automatic refresh if:
8894 // - We already refreshed recently.
8895 // - We already auto-refreshed this launch.
8896 // - Auto-refresh is disabled.
8897 if (recently || loaded_ || ManualRefresh) {
8898 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8900 // If we are cancelling, we need to make sure it knows it's already loaded.
8904 // We are going to load, so remember that.
8908 SCNetworkReachabilityFlags flags; {
8909 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8910 SCNetworkReachabilityGetFlags(reachability, &flags);
8911 CFRelease(reachability);
8914 // XXX: this elaborate mess is what Apple is using to determine this? :(
8915 // XXX: do we care if the user has to intervene? maybe that's ok?
8917 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8918 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8919 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8920 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8921 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8922 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8926 // If we can reach the server, auto-refresh!
8928 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8933 - (void) refreshIfPossible {
8934 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8937 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8938 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8939 [hud setText:UCLocalize("RELOADING_DATA")];
8941 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8944 [self removeProgressHUD:hud];
8948 [essential_ removeAllObjects];
8949 [broken_ removeAllObjects];
8951 NSArray *packages([database_ packages]);
8952 for (Package *package in packages) {
8954 [broken_ addObject:package];
8955 if ([package upgradableAndEssential:NO]) {
8956 if ([package essential])
8957 [essential_ addObject:package];
8962 NSLog(@"changes:#%u", changes);
8964 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8967 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8968 [changesItem setBadgeValue:badge];
8969 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8970 [self setApplicationIconBadgeNumber:changes];
8973 [changesItem setBadgeValue:nil];
8974 [changesItem setAnimatedBadge:NO];
8975 [self setApplicationIconBadgeNumber:0];
8980 [self refreshIfPossible];
8983 - (void) updateData {
8992 @synchronized (self) {
8993 [self _reloadDataWithInvocation:nil];
8997 - (void) disemulate {
8998 if (emulated_ == nil)
9001 [window_ addSubview:[tabbar_ view]];
9002 [[emulated_ view] removeFromSuperview];
9003 [emulated_ release];
9005 [window_ setUserInteractionEnabled:YES];
9008 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9009 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
9011 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9013 UIViewController *parent;
9014 if (emulated_ == nil)
9023 [parent presentModalViewController:navigation animated:YES];
9026 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9027 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9029 if (navigation != nil)
9030 [navigation pushViewController:progress animated:YES];
9032 [self presentModalViewController:progress force:YES];
9034 [progress invoke:invocation withTitle:title];
9038 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9039 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9042 - (void) repairWithInvocation:(NSInvocation *)invocation {
9044 [self invokeNewProgress:invocation forController:nil withTitle:UCLocalize("REPAIRING")];
9048 - (void) repairWithSelector:(SEL)selector {
9049 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9055 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9056 _assert(file != NULL);
9058 for (NSString *key in [Sources_ allKeys]) {
9059 NSDictionary *source([Sources_ objectForKey:key]);
9061 fprintf(file, "%s %s %s\n",
9062 [[source objectForKey:@"Type"] UTF8String],
9063 [[source objectForKey:@"URI"] UTF8String],
9064 [[source objectForKey:@"Distribution"] UTF8String]
9070 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:UCLocalize("UPDATING_SOURCES")];
9075 - (void) addTrivialSource:(NSString *)href {
9076 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9079 @"./", @"Distribution",
9080 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9085 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9086 @synchronized (self) {
9087 [self _reloadDataWithInvocation:invocation];
9091 - (void) reloadData {
9092 [self reloadDataWithInvocation:nil];
9096 pkgProblemResolver *resolver = [database_ resolver];
9098 resolver->InstallProtect();
9099 if (!resolver->Resolve(true))
9104 // XXX: this is a really crappy way of doing this.
9105 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9106 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9107 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9108 if ([tabbar_ updating])
9109 [tabbar_ cancelUpdate];
9111 if (![database_ prepare])
9114 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9115 [page setDelegate:self];
9116 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9117 [confirm_ setDelegate:self];
9120 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9121 [tabbar_ presentModalViewController:confirm_ animated:YES];
9127 @synchronized (self) {
9132 - (void) clearPackage:(Package *)package {
9133 @synchronized (self) {
9140 - (void) installPackages:(NSArray *)packages {
9141 @synchronized (self) {
9142 for (Package *package in packages)
9149 - (void) installPackage:(Package *)package {
9150 @synchronized (self) {
9157 - (void) removePackage:(Package *)package {
9158 @synchronized (self) {
9165 - (void) distUpgrade {
9166 @synchronized (self) {
9167 if (![database_ upgrade])
9173 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9176 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:UCLocalize("RUNNING")];
9181 - (void) showSettings {
9182 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9183 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9185 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9186 [tabbar_ presentModalViewController:nav animated:YES];
9189 - (void) retainNetworkActivityIndicator {
9190 if (activity_++ == 0)
9191 [self setNetworkActivityIndicatorVisible:YES];
9194 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9198 - (void) releaseNetworkActivityIndicator {
9199 if (--activity_ == 0)
9200 [self setNetworkActivityIndicatorVisible:NO];
9203 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9208 - (void) cancelAndClear:(bool)clear {
9209 @synchronized (self) {
9221 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9222 NSString *context([alert context]);
9224 if ([context isEqualToString:@"conffile"]) {
9225 FILE *input = [database_ input];
9226 if (button == [alert cancelButtonIndex])
9227 fprintf(input, "N\n");
9228 else if (button == [alert firstOtherButtonIndex])
9229 fprintf(input, "Y\n");
9232 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9233 } else if ([context isEqualToString:@"fixhalf"]) {
9234 if (button == [alert cancelButtonIndex]) {
9235 @synchronized (self) {
9236 for (Package *broken in broken_) {
9239 NSString *id = [broken id];
9240 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9241 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9242 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9243 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9249 } else if (button == [alert firstOtherButtonIndex]) {
9250 [broken_ removeAllObjects];
9254 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9255 } else if ([context isEqualToString:@"upgrade"]) {
9256 if (button == [alert firstOtherButtonIndex]) {
9257 @synchronized (self) {
9258 for (Package *essential in essential_)
9259 [essential install];
9264 } else if (button == [alert firstOtherButtonIndex] + 1) {
9266 } else if (button == [alert cancelButtonIndex]) {
9270 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9274 - (void) system:(NSString *)command { _pooled
9276 system([command UTF8String]);
9280 - (void) applicationWillSuspend {
9282 [super applicationWillSuspend];
9285 - (BOOL) isSafeToSuspend {
9286 // Use external process status API internally.
9287 // This is probably a really bad idea.
9288 // XXX: what is the point of this? does this solve anything at all?
9289 uint64_t status = 0;
9291 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9292 notify_get_state(notify_token, &status);
9293 notify_cancel(notify_token);
9296 return locked_ == 0 && status == 0;
9299 - (void) applicationSuspend:(__GSEvent *)event {
9300 if ([self isSafeToSuspend])
9301 [super applicationSuspend:event];
9304 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9305 if ([self isSafeToSuspend])
9306 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9309 - (void) _setSuspended:(BOOL)value {
9310 if ([self isSafeToSuspend])
9311 [super _setSuspended:value];
9314 - (UIProgressHUD *) addProgressHUD {
9315 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9316 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9318 [window_ setUserInteractionEnabled:NO];
9321 UIViewController *target = tabbar_;
9322 while ([target modalViewController] != nil) target = [target modalViewController];
9323 [[target view] addSubview:hud];
9329 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9331 [hud removeFromSuperview];
9332 [window_ setUserInteractionEnabled:YES];
9336 - (CYViewController *) pageForPackage:(NSString *)name {
9337 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9340 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9341 NSString *scheme([[url scheme] lowercaseString]);
9342 if ([[url absoluteString] length] <= [scheme length] + 3)
9344 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9345 NSArray *components([path pathComponents]);
9347 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9348 return [self pageForPackage:[components objectAtIndex:1]];
9350 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9353 NSString *base([components objectAtIndex:0]);
9355 CYViewController *controller = nil;
9357 if ([base isEqualToString:@"url"]) {
9358 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9359 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9360 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9361 } else if (!external && [components count] == 1) {
9362 if ([base isEqualToString:@"manage"]) {
9363 controller = [[[ManageController alloc] init] autorelease];
9366 if ([base isEqualToString:@"sources"]) {
9367 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9370 if ([base isEqualToString:@"home"]) {
9371 controller = [[[HomeController alloc] init] autorelease];
9374 if ([base isEqualToString:@"sections"]) {
9375 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9378 if ([base isEqualToString:@"search"]) {
9379 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9382 if ([base isEqualToString:@"changes"]) {
9383 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9386 if ([base isEqualToString:@"installed"]) {
9387 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9389 } else if ([components count] == 2) {
9390 NSString *argument = [components objectAtIndex:1];
9392 if ([base isEqualToString:@"package"]) {
9393 controller = [self pageForPackage:argument];
9396 if (!external && [base isEqualToString:@"search"]) {
9397 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9398 [(SearchController *)controller setSearchTerm:argument];
9401 if (!external && [base isEqualToString:@"sections"]) {
9402 if ([argument isEqualToString:@"all"])
9404 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9407 if (!external && [base isEqualToString:@"sources"]) {
9408 if ([argument isEqualToString:@"add"]) {
9409 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9410 [(SourcesController *)controller showAddSourcePrompt];
9412 Source *source = [database_ sourceWithKey:argument];
9413 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9417 if (!external && [base isEqualToString:@"launch"]) {
9418 [self launchApplicationWithIdentifier:argument suspended:NO];
9421 } else if (!external && [components count] == 3) {
9422 NSString *arg1 = [components objectAtIndex:1];
9423 NSString *arg2 = [components objectAtIndex:2];
9425 if ([base isEqualToString:@"package"]) {
9426 if ([arg2 isEqualToString:@"settings"]) {
9427 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9428 } else if ([arg2 isEqualToString:@"files"]) {
9429 if (Package *package = [database_ packageWithName:arg1]) {
9430 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9431 [(FileTable *)controller setPackage:package];
9437 [controller setDelegate:self];
9441 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9442 CYViewController *page([self pageForURL:url forExternal:external]);
9445 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9446 [nav setViewControllers:[NSArray arrayWithObject:page]];
9447 [tabbar_ setUnselectedViewController:nav];
9453 - (void) applicationOpenURL:(NSURL *)url {
9454 [super applicationOpenURL:url];
9456 if (!loaded_) starturl_ = [url retain];
9457 else [self openCydiaURL:url forExternal:YES];
9460 - (void) applicationWillResignActive:(UIApplication *)application {
9461 // Stop refreshing if you get a phone call or lock the device.
9462 if ([tabbar_ updating])
9463 [tabbar_ cancelUpdate];
9465 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9466 [super applicationWillResignActive:application];
9469 - (void) applicationWillTerminate:(UIApplication *)application {
9471 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9472 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9473 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9478 - (void) setConfigurationData:(NSString *)data {
9479 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9481 if (!conffile_r(data)) {
9482 lprintf("E:invalid conffile\n");
9486 NSString *ofile = conffile_r[1];
9487 //NSString *nfile = conffile_r[2];
9489 UIAlertView *alert = [[[UIAlertView alloc]
9490 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9491 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9493 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9495 UCLocalize("ACCEPT_NEW_COPY"),
9496 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9500 [alert setContext:@"conffile"];
9504 - (void) addStashController {
9506 stash_ = [[StashController alloc] init];
9507 [window_ addSubview:[stash_ view]];
9510 - (void) removeStashController {
9511 [[stash_ view] removeFromSuperview];
9517 [self setIdleTimerDisabled:YES];
9519 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9520 UpdateExternalStatus(1);
9521 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9522 UpdateExternalStatus(0);
9524 [self removeStashController];
9526 if (ExecFork() == 0) {
9527 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9528 perror("launchctl stop");
9532 - (void) setupViewControllers {
9533 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9535 NSMutableArray *items([NSMutableArray arrayWithObjects:
9536 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9537 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9538 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9539 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9543 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9544 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9546 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9549 NSMutableArray *controllers([NSMutableArray array]);
9550 for (UITabBarItem *item in items) {
9551 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9552 [controller setTabBarItem:item];
9553 [controllers addObject:controller];
9555 [tabbar_ setViewControllers:controllers];
9557 [tabbar_ setUpdateDelegate:self];
9560 - (void) applicationDidFinishLaunching:(id)unused {
9562 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9563 [self setApplicationSupportsShakeToEdit:NO];
9565 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9566 initWithMemoryCapacity:524288
9567 diskCapacity:10485760
9568 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9571 [CYBrowserController _initialize];
9573 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9575 Font12_ = [[UIFont systemFontOfSize:12] retain];
9576 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9577 Font14_ = [[UIFont systemFontOfSize:14] retain];
9578 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9579 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9581 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9582 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9584 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9585 [window_ orderFront:self];
9586 [window_ makeKey:self];
9587 [window_ setHidden:NO];
9590 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9591 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9592 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9593 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9594 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9595 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9596 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9597 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9598 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9601 [self addStashController];
9602 // XXX: this would be much cleaner as a yieldToSelector:
9603 // that way the removeStashController could happen right here inline
9604 // we also could no longer require the useless stash_ field anymore
9605 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9609 database_ = [Database sharedInstance];
9610 [database_ setDelegate:self];
9612 [window_ setUserInteractionEnabled:NO];
9613 [self setupViewControllers];
9615 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9616 [window_ addSubview:[emulated_ view]];
9618 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9625 [window_ setUserInteractionEnabled:YES];
9626 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9629 if ([emulated_ modalViewController] != nil)
9630 [emulated_ dismissModalViewControllerAnimated:YES];
9631 [window_ setUserInteractionEnabled:NO];
9639 int selectedIndex = 0;
9640 NSMutableArray *items = nil;
9642 bool recently = false;
9643 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9644 if (closed != nil) {
9645 NSTimeInterval interval([closed timeIntervalSinceNow]);
9646 // XXX: Is 15 minutes the optimal time here?
9647 if (interval <= 0 && interval > -(15*60))
9651 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9652 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9655 for (NSArray *entry in items)
9656 if ([entry count] <= 0)
9659 if (!recently || !items || !enough) {
9661 items = [NSMutableArray array];
9662 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9663 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9664 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9666 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9668 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9669 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9671 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9674 [tabbar_ setSelectedIndex:selectedIndex];
9675 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9676 NSArray *stack = [items objectAtIndex:tab];
9677 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9678 NSMutableArray *current = [NSMutableArray array];
9680 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9681 NSString *addr = [stack objectAtIndex:nav];
9682 NSURL *url = [NSURL URLWithString:addr];
9683 CYViewController *page = [self pageForURL:url forExternal:NO];
9685 [current addObject:page];
9688 [navigation setViewControllers:current];
9691 // (Try to) show the startup URL.
9692 if (starturl_ != nil) {
9693 [self openCydiaURL:starturl_ forExternal:NO];
9694 [starturl_ release];
9699 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9700 if (item != nil && IsWildcat_) {
9701 [sheet showFromBarButtonItem:item animated:YES];
9703 [sheet showInView:window_];
9707 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9708 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9709 [progress setTitle:task];
9710 [progress addProgressEvent:event];
9713 - (void) addProgressEventForTask:(NSArray *)data {
9714 CydiaProgressEvent *event([data objectAtIndex:0]);
9715 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9716 [self addProgressEvent:event forTask:task];
9719 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9720 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9726 id Alloc_(id self, SEL selector) {
9727 id object = alloc_(self, selector);
9728 lprintf("[%s]A-%p\n", self->isa->name, object);
9733 id Dealloc_(id self, SEL selector) {
9734 id object = dealloc_(self, selector);
9735 lprintf("[%s]D-%p\n", self->isa->name, object);
9739 Class $WebDefaultUIKitDelegate;
9741 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9742 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9743 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9744 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9747 static NSNumber *shouldPlayKeyboardSounds;
9751 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9753 case 1104: // Keyboard Button Clicked
9754 case 1105: // Keyboard Delete Repeated
9755 if (shouldPlayKeyboardSounds == nil) {
9756 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9757 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9760 if (![shouldPlayKeyboardSounds boolValue])
9764 _UIHardware$_playSystemSound$(self, _cmd, sound);
9768 Class $UIApplication;
9770 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9771 static BOOL initialized = NO;
9772 static BOOL started = NO;
9774 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9775 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9777 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9778 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9779 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9780 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9782 if (initialized && !enabled) {
9784 [bundle performSelector:@selector(_accessibilityStopServer)];
9785 } else if (enabled) {
9789 [bundle performSelector:@selector(_accessibilityStartServer)];
9795 int main(int argc, char *argv[]) { _pooled
9798 UpdateExternalStatus(0);
9800 if (Class $UIDevice = objc_getClass("UIDevice")) {
9801 UIDevice *device([$UIDevice currentDevice]);
9802 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9806 UIScreen *screen([UIScreen mainScreen]);
9807 if ([screen respondsToSelector:@selector(scale)])
9808 ScreenScale_ = [screen scale];
9812 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9813 if (ScreenScale_ > 1)
9814 [parts addObject:@"@2x"];
9815 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9816 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9818 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9820 /* Library Hacks {{{ */
9821 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9823 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9824 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9825 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9826 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9827 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9830 $UIHardware = objc_getClass("UIHardware");
9831 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9832 if (UIHardware$_playSystemSound$ != NULL) {
9833 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9834 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9837 $UIApplication = objc_getClass("UIApplication");
9838 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9839 if (UIApplication$_updateApplicationAccessibility != NULL) {
9840 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9841 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9844 /* Set Locale {{{ */
9845 Locale_ = CFLocaleCopyCurrent();
9846 Languages_ = [NSLocale preferredLanguages];
9847 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9848 //NSLog(@"%@", [Languages_ description]);
9851 if (Languages_ == nil || [Languages_ count] == 0)
9852 // XXX: consider just setting to C and then falling through?
9855 lang = [[Languages_ objectAtIndex:0] UTF8String];
9856 setenv("LANG", lang, true);
9859 //std::setlocale(LC_ALL, lang);
9860 NSLog(@"Setting Language: %s", lang);
9863 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9865 /* Parse Arguments {{{ */
9866 bool substrate(false);
9872 for (int argi(1); argi != argc; ++argi)
9873 if (strcmp(argv[argi], "--") == 0) {
9875 argv[argi] = argv[0];
9881 for (int argi(1); argi != arge; ++argi)
9882 if (strcmp(args[argi], "--substrate") == 0)
9885 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9889 App_ = [[NSBundle mainBundle] bundlePath];
9890 Home_ = NSHomeDirectory();
9896 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9897 alloc_ = alloc->method_imp;
9898 alloc->method_imp = (IMP) &Alloc_;*/
9900 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9901 dealloc_ = dealloc->method_imp;
9902 dealloc->method_imp = (IMP) &Dealloc_;*/
9904 /* System Information {{{ */
9908 size = sizeof(maxproc);
9909 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9910 perror("sysctlbyname(\"kern.maxproc\", ?)");
9911 else if (maxproc < 64) {
9913 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9914 perror("sysctlbyname(\"kern.maxproc\", #)");
9917 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9918 char *osversion = new char[size];
9919 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9920 perror("sysctlbyname(\"kern.osversion\", ?)");
9922 System_ = [NSString stringWithUTF8String:osversion];
9924 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9925 char *machine = new char[size];
9926 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9927 perror("sysctlbyname(\"hw.machine\", ?)");
9931 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9932 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9933 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9934 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9938 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9939 NSData *data((NSData *) ecid);
9940 size_t length([data length]);
9941 uint8_t bytes[length];
9942 [data getBytes:bytes];
9943 char string[length * 2 + 1];
9944 for (size_t i(0); i != length; ++i)
9945 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9946 ChipID_ = [NSString stringWithUTF8String:string];
9950 IOObjectRelease(service);
9954 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9956 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9957 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9958 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9960 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9961 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9962 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9964 if (mcc != NULL && mnc != NULL)
9965 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9972 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9973 Build_ = [system objectForKey:@"ProductBuildVersion"];
9974 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9975 Product_ = [info objectForKey:@"SafariProductVersion"];
9976 Safari_ = [info objectForKey:@"CFBundleVersion"];
9979 /* Load Database {{{ */
9981 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9983 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9985 if (Metadata_ == NULL)
9986 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9988 Settings_ = [Metadata_ objectForKey:@"Settings"];
9990 Packages_ = [Metadata_ objectForKey:@"Packages"];
9991 Sections_ = [Metadata_ objectForKey:@"Sections"];
9992 Sources_ = [Metadata_ objectForKey:@"Sources"];
9994 Token_ = [Metadata_ objectForKey:@"Token"];
9997 if (Settings_ != nil)
9998 Role_ = [Settings_ objectForKey:@"Role"];
10000 if (Sections_ == nil) {
10001 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10002 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10005 if (Sources_ == nil) {
10006 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10007 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10012 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10015 if (Packages_ != nil) {
10017 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10021 [Metadata_ removeObjectForKey:@"Packages"];
10027 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10029 #define MobileSubstrate_(name) \
10030 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) \
10031 dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL);
10033 MobileSubstrate_(Activator)
10034 MobileSubstrate_(libstatusbar)
10035 MobileSubstrate_(SimulatedKeyEvents)
10036 MobileSubstrate_(WinterBoard)
10038 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10039 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10041 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10043 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10044 unlink("/tmp/.cydia.fw");
10046 } else if (access("/User", F_OK) != 0 || version < 2) {
10049 system("/usr/libexec/cydia/firmware.sh");
10053 _assert([[NSFileManager defaultManager]
10054 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10055 withIntermediateDirectories:YES
10060 if (access("/tmp/cydia.chk", F_OK) == 0) {
10061 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10062 _assert(errno == ENOENT);
10063 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10064 _assert(errno == ENOENT);
10067 /* APT Initialization {{{ */
10068 _assert(pkgInitConfig(*_config));
10069 _assert(pkgInitSystem(*_config, _system));
10072 _config->Set("APT::Acquire::Translation", lang);
10074 // XXX: this timeout might be important :(
10075 //_config->Set("Acquire::http::Timeout", 15);
10077 _config->Set("Acquire::http::MaxParallel", 3);
10079 /* Color Choices {{{ */
10080 space_ = CGColorSpaceCreateDeviceRGB();
10082 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10083 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10084 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10085 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10086 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10087 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10088 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10089 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10090 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10092 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10093 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10095 /* UIKit Configuration {{{ */
10096 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10097 if ($GSFontSetUseLegacyFontMetrics != NULL)
10098 $GSFontSetUseLegacyFontMetrics(YES);
10100 // XXX: I have a feeling this was important
10101 //UIKeyboardDisableAutomaticAppearance();
10104 Colon_ = UCLocalize("COLON_DELIMITED");
10105 Elision_ = UCLocalize("ELISION");
10106 Error_ = UCLocalize("ERROR");
10107 Warning_ = UCLocalize("WARNING");
10110 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10112 CGColorSpaceRelease(space_);
10113 CFRelease(Locale_);