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"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
202 #define CYPoolStart() \
203 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
205 #define CYPoolEnd() \
209 // Hash Functions/Structures {{{
210 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
218 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
220 static _finline NSString *CydiaURL(NSString *path) {
222 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
223 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
224 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
225 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
226 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
227 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
230 static _finline void UpdateExternalStatus(uint64_t newStatus) {
232 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
233 notify_set_state(notify_token, newStatus);
234 notify_cancel(notify_token);
236 notify_post("com.saurik.Cydia.status");
239 /* [NSObject yieldToSelector:(withObject:)] {{{*/
240 @interface NSObject (Cydia)
241 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
242 - (id) yieldToSelector:(SEL)selector;
245 @implementation NSObject (Cydia)
250 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
251 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
252 id object([[context objectAtIndex:1] nonretainedObjectValue]);
253 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
255 /* XXX: deal with exceptions */
256 id value([self performSelector:selector withObject:object]);
258 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
259 [context removeAllObjects];
260 if ([signature methodReturnLength] != 0 && value != nil)
261 [context addObject:value];
266 performSelectorOnMainThread:@selector(doNothing)
272 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
273 volatile bool stopped(false);
275 NSMutableArray *context([NSMutableArray arrayWithObjects:
276 [NSValue valueWithPointer:selector],
277 [NSValue valueWithNonretainedObject:object],
278 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
281 NSThread *thread([[[NSThread alloc]
283 selector:@selector(_yieldToContext:)
289 NSRunLoop *loop([NSRunLoop currentRunLoop]);
290 NSDate *future([NSDate distantFuture]);
292 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
294 return [context count] == 0 ? nil : [context objectAtIndex:0];
297 - (id) yieldToSelector:(SEL)selector {
298 return [self yieldToSelector:selector withObject:nil];
304 /* Cydia Alert View {{{ */
305 @interface CYAlertView : UIAlertView {
309 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
313 @implementation CYAlertView
315 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
316 if ((self = [super init]) != nil) {
317 [self setTitle:title];
318 [self setDelegate:self];
319 for (NSString *button in buttons) [self addButtonWithTitle:button];
320 [self setCancelButtonIndex:index];
324 - (void) _updateFrameForDisplay {
325 [super _updateFrameForDisplay];
326 if ([self cancelButtonIndex] == -1) {
327 NSArray *buttons = [self buttons];
328 if ([buttons count]) {
329 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
330 for (UIThreePartButton *button in buttons)
331 [button setBackground:background forState:0];
336 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
337 button_ = buttonIndex + 1;
341 [self dismissWithClickedButtonIndex:-1 animated:YES];
344 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
345 [self setRunsModal:YES];
354 /* NSForcedOrderingSearch doesn't work on the iPhone */
355 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
356 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
357 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
359 #define lprintf(args...) fprintf(stderr, args)
362 #define TraceLogging (1 && !ForRelease)
363 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
364 #define ProfileTimes (0 && !ForRelease)
365 #define ForSaurik (0 && !ForRelease)
366 #define LogBrowser (0 && !ForRelease)
367 #define TrackResize (0 && !ForRelease)
368 #define ManualRefresh (1 && !ForRelease)
369 #define ShowInternals (0 && !ForRelease)
370 #define AlwaysReload (0 && !ForRelease)
371 #define TryIndexedCollation (0 && !ForRelease)
375 #define _trace(args...)
380 #define _profile(name) {
383 #define PrintTimes() do {} while (false)
387 typedef uint32_t (*SKRadixFunction)(id, void *);
389 @interface NSMutableArray (Radix)
390 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
398 @implementation NSMutableArray (Radix)
400 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
401 size_t count([self count]);
402 struct RadixItem_ *swap(new RadixItem_[count * 2]);
404 for (size_t i(0); i != count; ++i) {
405 RadixItem_ &item(swap[i]);
408 id object([self objectAtIndex:i]);
409 item.key = function(object, argument);
412 struct RadixItem_ *lhs(swap), *rhs(swap + count);
414 static const size_t width = 32;
415 static const size_t bits = 11;
416 static const size_t slots = 1 << bits;
417 static const size_t passes = (width + (bits - 1)) / bits;
419 size_t *hist(new size_t[slots]);
421 for (size_t pass(0); pass != passes; ++pass) {
422 memset(hist, 0, sizeof(size_t) * slots);
424 for (size_t i(0); i != count; ++i) {
425 uint32_t key(lhs[i].key);
427 key &= _not(uint32_t) >> width - bits;
432 for (size_t i(0); i != slots; ++i) {
433 size_t local(offset);
438 for (size_t i(0); i != count; ++i) {
439 uint32_t key(lhs[i].key);
441 key &= _not(uint32_t) >> width - bits;
442 rhs[hist[key]++] = lhs[i];
445 RadixItem_ *tmp(lhs);
452 const void **values(new const void *[count]);
453 for (size_t i(0); i != count; ++i)
454 values[i] = [self objectAtIndex:lhs[i].index];
455 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
463 /* Insertion Sort {{{ */
465 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
466 const char *ptr = (const char *)list;
468 CFIndex half = count / 2;
469 const char *probe = ptr + elementSize * half;
470 CFComparisonResult cr = comparator(element, probe, context);
471 if (0 == cr) return (probe - (const char *)list) / elementSize;
472 ptr = (cr < 0) ? ptr : probe + elementSize;
473 count = (cr < 0) ? half : (half + (count & 1) - 1);
475 return (ptr - (const char *)list) / elementSize;
478 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
479 const char *ptr = (const char *)list;
481 CFIndex half = count / 2;
482 const char *probe = ptr + elementSize * half;
483 CFComparisonResult cr = comparator(element, probe, context);
484 if (0 == cr) return (probe - (const char *)list) / elementSize;
485 ptr = (cr < 0) ? ptr : probe + elementSize;
486 count = (cr < 0) ? half : (half + (count & 1) - 1);
488 return (ptr - (const char *)list) / elementSize;
491 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
492 if (range.length == 0)
494 const void **values(new const void *[range.length]);
495 CFArrayGetValues(array, range, values);
497 #if HistogramInsertionSort > 0
498 uint32_t total(0), *offsets(new uint32_t[range.length]);
501 for (CFIndex index(1); index != range.length; ++index) {
502 const void *value(values[index]);
503 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
504 CFIndex correct(index);
505 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
506 #if HistogramInsertionSort > 1
507 NSLog(@"%@ < %@", value, values[correct - 1]);
512 if (correct != index) {
513 size_t offset(index - correct);
514 #if HistogramInsertionSort
518 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
520 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
521 values[correct] = value;
525 CFArrayReplaceValues(array, range, values, range.length);
528 #if HistogramInsertionSort > 0
529 for (CFIndex index(0); index != range.length; ++index)
530 if (offsets[index] != 0)
531 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
532 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
539 /* Apple Bug Fixes {{{ */
540 @implementation UIWebDocumentView (Cydia)
542 - (void) _setScrollerOffset:(CGPoint)offset {
543 UIScroller *scroller([self _scroller]);
545 CGSize size([scroller contentSize]);
546 CGSize bounds([scroller bounds].size);
549 max.x = size.width - bounds.width;
550 max.y = size.height - bounds.height;
558 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
559 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
561 [scroller setOffset:offset];
567 @implementation WebScriptObject (NSFastEnumeration)
569 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
570 size_t length([self count] - state->state);
573 else if (length > count)
575 for (size_t i(0); i != length; ++i)
576 objects[i] = [self objectAtIndex:state->state++];
577 state->itemsPtr = objects;
578 state->mutationsPtr = (unsigned long *) self;
584 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
585 size_t length([self length] - state->state);
588 else if (length > count)
590 for (size_t i(0); i != length; ++i)
591 objects[i] = [self item:state->state++];
592 state->itemsPtr = objects;
593 state->mutationsPtr = (unsigned long *) self;
597 /* Cydia NSString Additions {{{ */
598 @interface NSString (Cydia)
599 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
600 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
601 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
602 - (NSComparisonResult) compareByPath:(NSString *)other;
603 - (NSString *) stringByCachingURLWithCurrentCDN;
604 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
607 @implementation NSString (Cydia)
609 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
610 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
613 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
614 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
615 memcpy(data, bytes, length);
616 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
619 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
620 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
623 - (NSComparisonResult) compareByPath:(NSString *)other {
624 NSString *prefix = [self commonPrefixWithString:other options:0];
625 size_t length = [prefix length];
627 NSRange lrange = NSMakeRange(length, [self length] - length);
628 NSRange rrange = NSMakeRange(length, [other length] - length);
630 lrange = [self rangeOfString:@"/" options:0 range:lrange];
631 rrange = [other rangeOfString:@"/" options:0 range:rrange];
633 NSComparisonResult value;
635 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
636 value = NSOrderedSame;
637 else if (lrange.location == NSNotFound)
638 value = NSOrderedAscending;
639 else if (rrange.location == NSNotFound)
640 value = NSOrderedDescending;
642 value = NSOrderedSame;
644 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
645 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
646 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
647 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
649 NSComparisonResult result = [lpath compare:rpath];
650 return result == NSOrderedSame ? value : result;
653 - (NSString *) stringByCachingURLWithCurrentCDN {
655 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
656 withString:@"://cache.cydia.saurik.com/"
660 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
661 return [(id)CFURLCreateStringByAddingPercentEscapes(
666 kCFStringEncodingUTF8
673 /* C++ NSString Wrapper Cache {{{ */
674 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
675 return size == 0 ? NULL :
676 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
677 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
680 static _finline CFStringRef CYStringCreate(const char *data) {
681 return CYStringCreate(data, strlen(data));
690 _finline void clear_() {
691 if (cache_ != NULL) {
698 _finline bool empty() const {
702 _finline size_t size() const {
706 _finline char *data() const {
710 _finline void clear() {
715 _finline CYString() :
722 _finline ~CYString() {
726 void operator =(const CYString &rhs) {
730 if (rhs.cache_ == nil)
733 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
736 void copy(apr_pool_t *pool) {
737 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
738 memcpy(temp, data_, size_);
743 void set(apr_pool_t *pool, const char *data, size_t size) {
749 data_ = const_cast<char *>(data);
757 _finline void set(apr_pool_t *pool, const char *data) {
758 set(pool, data, data == NULL ? 0 : strlen(data));
761 _finline void set(apr_pool_t *pool, const std::string &rhs) {
762 set(pool, rhs.data(), rhs.size());
765 bool operator ==(const CYString &rhs) const {
766 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
769 _finline operator CFStringRef() {
771 cache_ = CYStringCreate(data_, size_);
775 _finline operator id() {
776 return (NSString *) static_cast<CFStringRef>(*this);
779 _finline operator const char *() {
780 return reinterpret_cast<const char *>(data_);
784 /* C++ NSString Algorithm Adapters {{{ */
786 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
789 struct NSStringMapHash :
790 std::unary_function<NSString *, size_t>
792 _finline size_t operator ()(NSString *value) const {
793 return CFStringHashNSString((CFStringRef) value);
797 struct NSStringMapLess :
798 std::binary_function<NSString *, NSString *, bool>
800 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
801 return [lhs compare:rhs] == NSOrderedAscending;
805 struct NSStringMapEqual :
806 std::binary_function<NSString *, NSString *, bool>
808 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
809 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
810 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
811 //[lhs isEqualToString:rhs];
816 /* Perl-Compatible RegEx {{{ */
826 Pcre(const char *regex) :
831 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
834 lprintf("%d:%s\n", offset, error);
838 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
839 matches_ = new int[(capture_ + 1) * 3];
847 NSString *operator [](size_t match) {
848 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
851 bool operator ()(NSString *data) {
852 // XXX: length is for characters, not for bytes
853 return operator ()([data UTF8String], [data length]);
856 bool operator ()(const char *data, size_t size) {
858 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
862 /* Mime Addresses {{{ */
863 @interface Address : NSObject {
869 - (NSString *) address;
871 - (void) setAddress:(NSString *)address;
873 + (Address *) addressWithString:(NSString *)string;
874 - (Address *) initWithString:(NSString *)string;
878 @implementation Address
887 - (NSString *) name {
891 - (NSString *) address {
895 - (void) setAddress:(NSString *)address {
897 [address_ autorelease];
901 address_ = [address retain];
904 + (Address *) addressWithString:(NSString *)string {
905 return [[[Address alloc] initWithString:string] autorelease];
908 + (NSArray *) _attributeKeys {
909 return [NSArray arrayWithObjects:
915 - (NSArray *) attributeKeys {
916 return [[self class] _attributeKeys];
919 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
920 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
923 - (Address *) initWithString:(NSString *)string {
924 if ((self = [super init]) != nil) {
925 const char *data = [string UTF8String];
926 size_t size = [string length];
928 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
930 if (address_r(data, size)) {
931 name_ = [address_r[1] retain];
932 address_ = [address_r[2] retain];
934 name_ = [string retain];
942 /* CoreGraphics Primitives {{{ */
947 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
948 CGFloat color[] = {red, green, blue, alpha};
949 return CGColorCreate(space, color);
958 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
959 color_(Create_(space, red, green, blue, alpha))
961 Set(space, red, green, blue, alpha);
966 CGColorRelease(color_);
973 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
975 color_ = Create_(space, red, green, blue, alpha);
978 operator CGColorRef() {
984 /* Random Global Variables {{{ */
985 static const int PulseInterval_ = 50000;
987 static const NSString *UI_;
990 static bool RestartSubstrate_;
991 static NSArray *Finishes_;
993 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
994 #define NotifyConfig_ "/etc/notify.conf"
996 static bool Queuing_;
998 static CYColor Blue_;
999 static CYColor Blueish_;
1000 static CYColor Black_;
1001 static CYColor Off_;
1002 static CYColor White_;
1003 static CYColor Gray_;
1004 static CYColor Green_;
1005 static CYColor Purple_;
1006 static CYColor Purplish_;
1008 static UIColor *InstallingColor_;
1009 static UIColor *RemovingColor_;
1011 static NSString *App_;
1012 static NSString *Home_;
1014 static BOOL Advanced_;
1015 static BOOL Ignored_;
1017 static UIFont *Font12_;
1018 static UIFont *Font12Bold_;
1019 static UIFont *Font14_;
1020 static UIFont *Font18Bold_;
1021 static UIFont *Font22Bold_;
1023 static const char *Machine_ = NULL;
1024 static NSString *System_ = nil;
1025 static NSString *SerialNumber_ = nil;
1026 static NSString *ChipID_ = nil;
1027 static NSString *Token_ = nil;
1028 static NSString *UniqueID_ = nil;
1029 static NSString *PLMN_ = nil;
1030 static NSString *Build_ = nil;
1031 static NSString *Product_ = nil;
1032 static NSString *Safari_ = nil;
1034 static CFLocaleRef Locale_;
1035 static NSArray *Languages_;
1036 static CGColorSpaceRef space_;
1038 static NSDictionary *SectionMap_;
1039 static NSMutableDictionary *Metadata_;
1040 static _transient NSMutableDictionary *Settings_;
1041 static _transient NSString *Role_;
1042 static _transient NSMutableDictionary *Packages_;
1043 static _transient NSMutableDictionary *Sections_;
1044 static _transient NSMutableDictionary *Sources_;
1045 static bool Changed_;
1049 static CGFloat ScreenScale_;
1052 /* Display Helpers {{{ */
1053 inline float Interpolate(float begin, float end, float fraction) {
1054 return (end - begin) * fraction + begin;
1057 static _finline const char *StripVersion_(const char *version) {
1058 const char *colon(strchr(version, ':'));
1059 return colon == NULL ? version : colon + 1;
1062 NSString *LocalizeSection(NSString *section) {
1063 static Pcre title_r("^(.*?) \\((.*)\\)$");
1064 if (title_r(section)) {
1065 NSString *parent(title_r[1]);
1066 NSString *child(title_r[2]);
1068 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1069 LocalizeSection(parent),
1070 LocalizeSection(child)
1074 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1077 NSString *Simplify(NSString *title) {
1078 const char *data = [title UTF8String];
1079 size_t size = [title length];
1081 static Pcre square_r("^\\[(.*)\\]$");
1082 if (square_r(data, size))
1083 return Simplify(square_r[1]);
1085 static Pcre paren_r("^\\((.*)\\)$");
1086 if (paren_r(data, size))
1087 return Simplify(paren_r[1]);
1089 static Pcre title_r("^(.*?) \\((.*)\\)$");
1090 if (title_r(data, size))
1091 return Simplify(title_r[1]);
1097 NSString *GetLastUpdate() {
1098 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1101 return UCLocalize("NEVER_OR_UNKNOWN");
1103 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1104 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1106 CFRelease(formatter);
1108 return [(NSString *) formatted autorelease];
1111 bool isSectionVisible(NSString *section) {
1112 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1113 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1114 return hidden == nil || ![hidden boolValue];
1119 /* Delegate Prototypes {{{ */
1123 @interface NSObject (ProgressDelegate)
1126 @protocol ProgressDelegate
1127 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1128 - (void) setProgressTitle:(NSString *)title;
1129 - (void) setProgressPercent:(NSNumber *)percent;
1130 - (void) startProgress;
1131 - (void) addProgressOutput:(NSString *)output;
1132 - (bool) isCancelling:(size_t)received;
1135 @protocol ConfigurationDelegate
1136 - (void) repairWithSelector:(SEL)selector;
1137 - (void) setConfigurationData:(NSString *)data;
1140 @class CYPackageController;
1142 @protocol CydiaDelegate
1143 - (void) retainNetworkActivityIndicator;
1144 - (void) releaseNetworkActivityIndicator;
1145 - (void) clearPackage:(Package *)package;
1146 - (void) installPackage:(Package *)package;
1147 - (void) installPackages:(NSArray *)packages;
1148 - (void) removePackage:(Package *)package;
1149 - (void) beginUpdate;
1151 - (void) distUpgrade;
1153 - (void) updateData;
1155 - (void) addTrivialSource:(NSString *)href;
1156 - (void) showSettings;
1157 - (UIProgressHUD *) addProgressHUD;
1158 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1159 - (CYViewController *) pageForPackage:(NSString *)name;
1160 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1161 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1164 static NSObject<CydiaDelegate> *CydiaApp;
1167 /* Status Delegation {{{ */
1169 public pkgAcquireStatus
1172 _transient NSObject<ProgressDelegate> *delegate_;
1180 void setDelegate(id delegate) {
1181 delegate_ = delegate;
1184 NSObject<ProgressDelegate> *getDelegate() const {
1188 virtual bool MediaChange(std::string media, std::string drive) {
1192 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1195 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1196 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1198 performSelectorOnMainThread:@selector(setProgressTitle:)
1199 withObject:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]
1204 virtual void Done(pkgAcquire::ItemDesc &item) {
1207 virtual void Fail(pkgAcquire::ItemDesc &item) {
1209 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1210 item.Owner->Status == pkgAcquire::Item::StatDone
1214 std::string &error(item.Owner->ErrorText);
1218 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1219 NSArray *fields([description componentsSeparatedByString:@" "]);
1220 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1222 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1223 withObject:[NSArray arrayWithObjects:
1224 [NSString stringWithUTF8String:error.c_str()],
1231 virtual bool Pulse(pkgAcquire *Owner) {
1232 bool value = pkgAcquireStatus::Pulse(Owner);
1235 double(CurrentBytes + CurrentItems) /
1236 double(TotalBytes + TotalItems)
1239 [delegate_ setProgressPercent:[NSNumber numberWithFloat:percent]];
1240 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1243 virtual void Start() {
1244 [delegate_ startProgress];
1247 virtual void Stop() {
1252 /* Database Interface {{{ */
1253 typedef std::map< unsigned long, _H<Source> > SourceMap;
1255 @interface Database : NSObject {
1261 pkgCacheFile cache_;
1262 pkgDepCache::Policy *policy_;
1263 pkgRecords *records_;
1264 pkgProblemResolver *resolver_;
1265 pkgAcquire *fetcher_;
1267 SPtr<pkgPackageManager> manager_;
1268 pkgSourceList *list_;
1270 SourceMap sourceMap_;
1271 NSMutableArray *sourceList_;
1273 CFMutableArrayRef packages_;
1275 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1282 std::map<const char *, _H<NSString> > sections_;
1285 + (Database *) sharedInstance;
1288 - (void) _readCydia:(NSNumber *)fd;
1289 - (void) _readStatus:(NSNumber *)fd;
1290 - (void) _readOutput:(NSNumber *)fd;
1294 - (Package *) packageWithName:(NSString *)name;
1296 - (pkgCacheFile &) cache;
1297 - (pkgDepCache::Policy *) policy;
1298 - (pkgRecords *) records;
1299 - (pkgProblemResolver *) resolver;
1300 - (pkgAcquire &) fetcher;
1301 - (pkgSourceList &) list;
1302 - (NSArray *) packages;
1303 - (NSArray *) sources;
1304 - (Source *) sourceWithKey:(NSString *)key;
1305 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1313 - (void) updateWithStatus:(Status &)status;
1315 - (void) setDelegate:(id)delegate;
1316 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1318 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1322 /* Delegate Helpers {{{ */
1323 @implementation NSObject (ProgressDelegate)
1325 - (void) _setProgressErrorPackage:(NSArray *)args {
1326 [self performSelector:@selector(setProgressError:forPackage:)
1327 withObject:[args objectAtIndex:0]
1328 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1332 - (void) _setProgressErrorTitle:(NSArray *)args {
1333 [self performSelector:@selector(setProgressError:withTitle:)
1334 withObject:[args objectAtIndex:0]
1335 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1339 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1340 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1341 withObject:[NSArray arrayWithObjects:error, title, nil]
1346 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1347 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1349 [self performSelector:@selector(setProgressError:withTitle:)
1351 withObject:(package == nil ? id : [package name])
1358 // Cytore Definitions {{{
1359 struct PackageValue :
1362 Cytore::Offset<PackageValue> next_;
1364 uint32_t index_ : 23;
1365 uint32_t subscribed_ : 1;
1382 Cytore::Offset<PackageValue> packages_[1 << 16];
1385 static Cytore::File<MetaValue> MetaFile_;
1387 // Cytore Helper Functions {{{
1388 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1389 SplitHash nhash = { hashlittle(name, length) };
1391 PackageValue *metadata;
1393 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1394 offset: if (offset->IsNull()) {
1395 *offset = MetaFile_.New<PackageValue>(length + 1);
1396 metadata = &MetaFile_.Get(*offset);
1398 if (metadata == NULL) {
1402 metadata = new PackageValue();
1403 memset(metadata, 0, sizeof(*metadata));
1406 memcpy(metadata->name_, name, length + 1);
1407 metadata->nhash_ = nhash.u16[1];
1409 metadata = &MetaFile_.Get(*offset);
1411 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1412 offset = &metadata->next_;
1420 static void PackageImport(const void *key, const void *value, void *context) {
1421 bool &fail(*reinterpret_cast<bool *>(context));
1424 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1425 NSLog(@"failed to import package %@", key);
1429 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1430 NSDictionary *package((NSDictionary *) value);
1432 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1433 if ([subscribed boolValue] && !metadata->subscribed_)
1434 metadata->subscribed_ = true;
1436 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1437 time_t time([date timeIntervalSince1970]);
1438 if (metadata->first_ > time || metadata->first_ == 0)
1439 metadata->first_ = time;
1442 NSDate *date([package objectForKey:@"LastSeen"]);
1443 NSString *version([package objectForKey:@"LastVersion"]);
1445 if (date != nil && version != nil) {
1446 time_t time([date timeIntervalSince1970]);
1447 if (metadata->last_ < time || metadata->last_ == 0)
1448 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1449 size_t length(strlen(buffer));
1450 uint16_t vhash(hashlittle(buffer, length));
1452 size_t capped(std::min<size_t>(8, length));
1453 char *latest(buffer + length - capped);
1455 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1456 metadata->vhash_ = vhash;
1458 metadata->last_ = time;
1464 /* Source Class {{{ */
1465 @interface Source : NSObject {
1466 CYString depiction_;
1467 CYString description_;
1473 CYString distribution_;
1478 NSString *authority_;
1480 CYString defaultIcon_;
1482 NSDictionary *record_;
1486 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1488 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1490 - (NSString *) depictionForPackage:(NSString *)package;
1491 - (NSString *) supportForPackage:(NSString *)package;
1493 - (NSDictionary *) record;
1497 - (NSString *) distribution;
1498 - (NSString *) type;
1500 - (NSString *) host;
1502 - (NSString *) name;
1503 - (NSString *) description;
1504 - (NSString *) label;
1505 - (NSString *) origin;
1506 - (NSString *) version;
1508 - (NSString *) defaultIcon;
1512 @implementation Source
1516 distribution_.clear();
1519 description_.clear();
1525 defaultIcon_.clear();
1527 if (record_ != nil) {
1537 if (authority_ != nil) {
1538 [authority_ release];
1544 // XXX: this is a very inefficient way to call these deconstructors
1549 + (NSArray *) _attributeKeys {
1550 return [NSArray arrayWithObjects:
1565 - (NSArray *) attributeKeys {
1566 return [[self class] _attributeKeys];
1569 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1570 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1573 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1576 trusted_ = index->IsTrusted();
1578 uri_.set(pool, index->GetURI());
1579 distribution_.set(pool, index->GetDist());
1580 type_.set(pool, index->GetType());
1582 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1583 if (dindex != NULL) {
1585 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1588 pkgTagFile tags(&fd);
1590 pkgTagSection section;
1597 {"default-icon", &defaultIcon_},
1598 {"depiction", &depiction_},
1599 {"description", &description_},
1601 {"origin", &origin_},
1602 {"support", &support_},
1603 {"version", &version_},
1606 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1607 const char *start, *end;
1609 if (section.Find(names[i].name_, start, end)) {
1610 CYString &value(*names[i].value_);
1611 value.set(pool, start, end - start);
1617 record_ = [Sources_ objectForKey:[self key]];
1619 record_ = [record_ retain];
1621 NSURL *url([NSURL URLWithString:uri_]);
1625 host_ = [[host_ lowercaseString] retain];
1630 authority_ = [url path];
1632 if (authority_ != nil)
1633 authority_ = [authority_ retain];
1636 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1637 if ((self = [super init]) != nil) {
1638 [self setMetaIndex:index inPool:pool];
1642 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1643 NSDictionary *lhr = [self record];
1644 NSDictionary *rhr = [source record];
1647 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1649 NSString *lhs = [self name];
1650 NSString *rhs = [source name];
1652 if ([lhs length] != 0 && [rhs length] != 0) {
1653 unichar lhc = [lhs characterAtIndex:0];
1654 unichar rhc = [rhs characterAtIndex:0];
1656 if (isalpha(lhc) && !isalpha(rhc))
1657 return NSOrderedAscending;
1658 else if (!isalpha(lhc) && isalpha(rhc))
1659 return NSOrderedDescending;
1662 return [lhs compare:rhs options:LaxCompareOptions_];
1665 - (NSString *) depictionForPackage:(NSString *)package {
1666 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1669 - (NSString *) supportForPackage:(NSString *)package {
1670 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1673 - (NSDictionary *) record {
1681 - (NSString *) uri {
1685 - (NSString *) distribution {
1686 return distribution_;
1689 - (NSString *) type {
1693 - (NSString *) key {
1694 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1697 - (NSString *) host {
1701 - (NSString *) name {
1702 return origin_.empty() ? authority_ : origin_;
1705 - (NSString *) description {
1706 return description_;
1709 - (NSString *) label {
1710 return label_.empty() ? authority_ : label_;
1713 - (NSString *) origin {
1717 - (NSString *) version {
1721 - (NSString *) defaultIcon {
1722 return defaultIcon_;
1727 /* CydiaOperation Class {{{ */
1728 @interface CydiaOperation : NSObject {
1729 NSString *operator_;
1733 - (NSString *) operator;
1734 - (NSString *) value;
1738 @implementation CydiaOperation
1741 [operator_ release];
1746 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1747 if ((self = [super init]) != nil) {
1748 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1749 value_ = [[NSString alloc] initWithUTF8String:value];
1753 + (NSArray *) _attributeKeys {
1754 return [NSArray arrayWithObjects:
1760 - (NSArray *) attributeKeys {
1761 return [[self class] _attributeKeys];
1764 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1765 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1768 - (NSString *) operator {
1772 - (NSString *) value {
1778 /* CydiaClause Class {{{ */
1779 @interface CydiaClause : NSObject {
1781 CydiaOperation *version_;
1784 - (NSString *) package;
1785 - (CydiaOperation *) version;
1789 @implementation CydiaClause
1797 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1798 if ((self = [super init]) != nil) {
1799 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1801 if (const char *version = dep.TargetVer())
1802 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1804 version_ = [[NSNull null] retain];
1808 + (NSArray *) _attributeKeys {
1809 return [NSArray arrayWithObjects:
1815 - (NSArray *) attributeKeys {
1816 return [[self class] _attributeKeys];
1819 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1820 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1823 - (NSString *) package {
1827 - (CydiaOperation *) version {
1833 /* CydiaRelation Class {{{ */
1834 @interface CydiaRelation : NSObject {
1835 NSString *relationship_;
1836 NSMutableArray *clauses_;
1839 - (NSString *) relationship;
1840 - (NSArray *) clauses;
1844 @implementation CydiaRelation
1847 [relationship_ release];
1852 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1853 if ((self = [super init]) != nil) {
1854 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1855 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1857 pkgCache::DepIterator start;
1858 pkgCache::DepIterator end;
1859 dep.GlobOr(start, end); // ++dep
1862 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1864 // yes, seriously. (wtf?)
1872 + (NSArray *) _attributeKeys {
1873 return [NSArray arrayWithObjects:
1879 - (NSArray *) attributeKeys {
1880 return [[self class] _attributeKeys];
1883 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1884 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1887 - (NSString *) relationship {
1888 return relationship_;
1891 - (NSArray *) clauses {
1895 - (void) addClause:(CydiaClause *)clause {
1896 [clauses_ addObject:clause];
1901 /* Package Class {{{ */
1902 struct ParsedPackage {
1907 CYString depiction_;
1917 @interface Package : NSObject {
1920 uint32_t essential_ : 1;
1921 uint32_t obsolete_ : 1;
1922 uint32_t ignored_ : 1;
1926 _transient Database *database_;
1928 pkgCache::VerIterator version_;
1929 pkgCache::PkgIterator iterator_;
1930 pkgCache::VerFileIterator file_;
1936 CYString installed_;
1938 const char *section_;
1939 _transient NSString *section$_;
1943 PackageValue *metadata_;
1944 ParsedPackage *parsed_;
1946 NSMutableArray *tags_;
1949 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1950 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1952 - (pkgCache::PkgIterator) iterator;
1955 - (NSString *) section;
1956 - (NSString *) simpleSection;
1958 - (NSString *) longSection;
1959 - (NSString *) shortSection;
1963 - (Address *) maintainer;
1965 - (NSString *) longDescription;
1966 - (NSString *) shortDescription;
1969 - (PackageValue *) metadata;
1972 - (bool) subscribed;
1973 - (bool) setSubscribed:(bool)subscribed;
1977 - (NSString *) latest;
1978 - (NSString *) installed;
1979 - (BOOL) uninstalled;
1982 - (BOOL) upgradableAndEssential:(BOOL)essential;
1985 - (BOOL) unfiltered;
1989 - (BOOL) halfConfigured;
1990 - (BOOL) halfInstalled;
1992 - (NSString *) mode;
1995 - (NSString *) name;
1997 - (NSString *) homepage;
1998 - (NSString *) depiction;
1999 - (Address *) author;
2001 - (NSString *) support;
2003 - (NSArray *) files;
2004 - (NSArray *) warnings;
2005 - (NSArray *) applications;
2007 - (Source *) source;
2009 - (BOOL) matches:(NSString *)text;
2011 - (bool) hasSupportingRole;
2012 - (BOOL) hasTag:(NSString *)tag;
2013 - (NSString *) primaryPurpose;
2014 - (NSArray *) purposes;
2015 - (bool) isCommercial;
2017 - (void) setIndex:(size_t)index;
2019 - (CYString &) cyname;
2021 - (uint32_t) compareBySection:(NSArray *)sections;
2026 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2027 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2028 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2029 - (bool) isVisibleInSection:(NSString *)section;
2030 - (bool) isVisibleInSource:(Source *)source;
2034 uint32_t PackageChangesRadix(Package *self, void *) {
2039 uint32_t timestamp : 30;
2040 uint32_t ignored : 1;
2041 uint32_t upgradable : 1;
2045 bool upgradable([self upgradableAndEssential:YES]);
2046 value.bits.upgradable = upgradable ? 1 : 0;
2049 value.bits.timestamp = 0;
2050 value.bits.ignored = [self ignored] ? 0 : 1;
2051 value.bits.upgradable = 1;
2053 value.bits.timestamp = [self seen] >> 2;
2054 value.bits.ignored = 0;
2055 value.bits.upgradable = 0;
2058 return _not(uint32_t) - value.key;
2061 uint32_t PackagePrefixRadix(Package *self, void *context) {
2062 size_t offset(reinterpret_cast<size_t>(context));
2063 CYString &name([self cyname]);
2065 size_t size(name.size());
2068 char *text(name.data());
2071 if (!isdigit(text[0]))
2075 while (size != digits && isdigit(text[digits]))
2083 if (offset == 0 && zeros != 0) {
2084 memset(data, '0', zeros);
2085 memcpy(data + zeros, text, 4 - zeros);
2087 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2088 if (size <= offset - zeros)
2091 text += offset - zeros;
2092 size -= offset - zeros;
2095 memcpy(data, text, 4);
2097 memcpy(data, text, size);
2098 memset(data + size, 0, 4 - size);
2101 for (size_t i(0); i != 4; ++i)
2102 if (isalpha(data[i]))
2110 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2112 /* XXX: ntohl may be more honest */
2113 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2116 CYString &(*PackageName)(Package *self, SEL sel);
2118 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2119 _profile(PackageNameCompare)
2120 CYString &lhi(PackageName(lhs, @selector(cyname)));
2121 CYString &rhi(PackageName(rhs, @selector(cyname)));
2122 CFStringRef lhn(lhi), rhn(rhi);
2125 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2126 else if (rhn == NULL)
2127 return NSOrderedDescending;
2129 _profile(PackageNameCompare$NumbersLast)
2130 if (!lhi.empty() && !rhi.empty()) {
2131 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2132 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2133 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2134 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2135 return lha ? NSOrderedAscending : NSOrderedDescending;
2139 CFIndex length = CFStringGetLength(lhn);
2141 _profile(PackageNameCompare$Compare)
2142 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2147 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2148 return PackageNameCompare(*lhs, *rhs, context);
2151 struct PackageNameOrdering :
2152 std::binary_function<Package *, Package *, bool>
2154 _finline bool operator ()(Package *lhs, Package *rhs) const {
2155 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2159 @implementation Package
2161 - (NSString *) description {
2162 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2166 if (parsed_ != NULL)
2175 + (NSString *) webScriptNameForSelector:(SEL)selector {
2177 else if (selector == @selector(clear))
2179 else if (selector == @selector(getField:))
2181 else if (selector == @selector(hasTag:))
2183 else if (selector == @selector(install))
2185 else if (selector == @selector(remove))
2191 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2192 return [self webScriptNameForSelector:selector] == nil;
2195 + (NSArray *) _attributeKeys {
2196 return [NSArray arrayWithObjects:
2214 @"shortDescription",
2225 - (NSArray *) attributeKeys {
2226 return [[self class] _attributeKeys];
2229 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2230 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2233 - (NSArray *) relations {
2234 @synchronized (database_) {
2235 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2236 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2237 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2241 - (NSString *) getField:(NSString *)name {
2242 @synchronized (database_) {
2243 if ([database_ era] != era_ || file_.end())
2246 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2248 const char *start, *end;
2249 if (!parser.Find([name UTF8String], start, end))
2250 return (NSString *) [NSNull null];
2252 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2256 if (parsed_ != NULL)
2258 @synchronized (database_) {
2259 if ([database_ era] != era_ || file_.end())
2262 ParsedPackage *parsed(new ParsedPackage);
2265 _profile(Package$parse)
2266 pkgRecords::Parser *parser;
2268 _profile(Package$parse$Lookup)
2269 parser = &[database_ records]->Lookup(file_);
2274 _profile(Package$parse$Find)
2279 {"icon", &parsed->icon_},
2280 {"depiction", &parsed->depiction_},
2281 {"homepage", &parsed->homepage_},
2282 {"website", &website},
2283 {"bugs", &parsed->bugs_},
2284 {"support", &parsed->support_},
2285 {"sponsor", &parsed->sponsor_},
2286 {"author", &parsed->author_},
2289 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2290 const char *start, *end;
2292 if (parser->Find(names[i].name_, start, end)) {
2293 CYString &value(*names[i].value_);
2294 _profile(Package$parse$Value)
2295 value.set(pool_, start, end - start);
2301 _profile(Package$parse$Tagline)
2302 const char *start, *end;
2303 if (parser->ShortDesc(start, end)) {
2304 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2307 while (stop != start && stop[-1] == '\r')
2309 parsed->tagline_.set(pool_, start, stop - start);
2313 _profile(Package$parse$Retain)
2314 if (parsed->homepage_.empty())
2315 parsed->homepage_ = website;
2316 if (parsed->homepage_ == parsed->depiction_)
2317 parsed->homepage_.clear();
2322 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2323 if ((self = [super init]) != nil) {
2324 _profile(Package$initWithVersion)
2327 database_ = database;
2328 era_ = [database era];
2332 pkgCache::PkgIterator iterator(version.ParentPkg());
2333 iterator_ = iterator;
2335 _profile(Package$initWithVersion$Version)
2336 if (!version_.end())
2337 file_ = version_.FileList();
2339 pkgCache &cache([database_ cache]);
2340 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2344 _profile(Package$initWithVersion$Cache)
2345 name_.set(NULL, iterator.Display());
2347 latest_.set(NULL, StripVersion_(version_.VerStr()));
2349 pkgCache::VerIterator current(iterator.CurrentVer());
2351 installed_.set(NULL, StripVersion_(current.VerStr()));
2354 _profile(Package$initWithVersion$Tags)
2355 pkgCache::TagIterator tag(iterator.TagList());
2357 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2359 const char *name(tag.Name());
2360 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2362 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2363 if (strcmp(name + 6, "enduser") == 0)
2365 else if (strcmp(name + 6, "hacker") == 0)
2367 else if (strcmp(name + 6, "developer") == 0)
2369 else if (strcmp(name + 6, "cydia") == 0)
2375 if (strncmp(name, "cydia::", 7) == 0) {
2376 if (strcmp(name + 7, "essential") == 0)
2378 else if (strcmp(name + 7, "obsolete") == 0)
2383 } while (!tag.end());
2387 _profile(Package$initWithVersion$Metadata)
2388 const char *mixed(iterator.Name());
2389 size_t size(strlen(mixed));
2390 char lower[size + 1];
2392 for (size_t i(0); i != size; ++i)
2393 lower[i] = mixed[i] | 0x20;
2396 PackageValue *metadata(PackageFind(lower, size));
2397 metadata_ = metadata;
2399 id_.set(NULL, metadata->name_, size);
2401 const char *latest(version_.VerStr());
2402 size_t length(strlen(latest));
2404 uint16_t vhash(hashlittle(latest, length));
2406 size_t capped(std::min<size_t>(8, length));
2407 latest = latest + length - capped;
2409 if (metadata->first_ == 0)
2410 metadata->first_ = now_;
2412 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2413 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2414 metadata->vhash_ = vhash;
2415 metadata->last_ = now_;
2416 } else if (metadata->last_ == 0)
2417 metadata->last_ = metadata->first_;
2420 _profile(Package$initWithVersion$Section)
2421 section_ = iterator.Section();
2424 _profile(Package$initWithVersion$Flags)
2425 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2426 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2431 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2432 pkgCache::VerIterator version;
2434 _profile(Package$packageWithIterator$GetCandidateVer)
2435 version = [database policy]->GetCandidateVer(iterator);
2443 _profile(Package$packageWithIterator$Allocate)
2444 package = [Package allocWithZone:zone];
2447 _profile(Package$packageWithIterator$Initialize)
2449 initWithVersion:version
2456 _profile(Package$packageWithIterator$Autorelease)
2457 package = [package autorelease];
2463 - (pkgCache::PkgIterator) iterator {
2467 - (NSString *) section {
2468 if (section$_ == nil) {
2469 if (section_ == NULL)
2472 _profile(Package$section$mappedSectionForPointer)
2473 section$_ = [database_ mappedSectionForPointer:section_];
2478 - (NSString *) simpleSection {
2479 if (NSString *section = [self section])
2480 return Simplify(section);
2485 - (NSString *) longSection {
2486 return LocalizeSection([self section]);
2489 - (NSString *) shortSection {
2490 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2493 - (NSString *) uri {
2496 pkgIndexFile *index;
2497 pkgCache::PkgFileIterator file(file_.File());
2498 if (![database_ list].FindIndex(file, index))
2500 return [NSString stringWithUTF8String:iterator_->Path];
2501 //return [NSString stringWithUTF8String:file.Site()];
2502 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2506 - (Address *) maintainer {
2507 @synchronized (database_) {
2508 if ([database_ era] != era_ || file_.end())
2511 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2512 const std::string &maintainer(parser->Maintainer());
2513 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2517 @synchronized (database_) {
2518 if ([database_ era] != era_ || version_.end())
2521 return version_->InstalledSize;
2524 - (NSString *) longDescription {
2525 @synchronized (database_) {
2526 if ([database_ era] != era_ || file_.end())
2529 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2530 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2532 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2533 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2534 if ([lines count] < 2)
2537 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2538 for (size_t i(1), e([lines count]); i != e; ++i) {
2539 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2540 [trimmed addObject:trim];
2543 return [trimmed componentsJoinedByString:@"\n"];
2546 - (NSString *) shortDescription {
2547 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2551 _profile(Package$index)
2552 CFStringRef name((CFStringRef) [self name]);
2553 if (CFStringGetLength(name) == 0)
2555 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2556 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2558 return toupper(character);
2562 - (PackageValue *) metadata {
2567 PackageValue *metadata([self metadata]);
2568 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2571 - (bool) subscribed {
2572 return [self metadata]->subscribed_;
2575 - (bool) setSubscribed:(bool)subscribed {
2576 PackageValue *metadata([self metadata]);
2577 if (metadata->subscribed_ == subscribed)
2579 metadata->subscribed_ = subscribed;
2587 - (NSString *) latest {
2591 - (NSString *) installed {
2595 - (BOOL) uninstalled {
2596 return installed_.empty();
2600 return !version_.end();
2603 - (BOOL) upgradableAndEssential:(BOOL)essential {
2604 _profile(Package$upgradableAndEssential)
2605 pkgCache::VerIterator current(iterator_.CurrentVer());
2607 return essential && essential_;
2609 return !version_.end() && version_ != current;
2613 - (BOOL) essential {
2618 return [database_ cache][iterator_].InstBroken();
2621 - (BOOL) unfiltered {
2622 _profile(Package$unfiltered$obsolete)
2623 if (_unlikely(obsolete_))
2627 _profile(Package$unfiltered$hasSupportingRole)
2628 if (_unlikely(![self hasSupportingRole]))
2636 if (![self unfiltered])
2641 _profile(Package$visible$section)
2642 section = [self section];
2645 _profile(Package$visible$isSectionVisible)
2646 if (!isSectionVisible(section))
2654 unsigned char current(iterator_->CurrentState);
2655 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2658 - (BOOL) halfConfigured {
2659 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2662 - (BOOL) halfInstalled {
2663 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2667 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2668 return state.Mode != pkgDepCache::ModeKeep;
2671 - (NSString *) mode {
2672 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2674 switch (state.Mode) {
2675 case pkgDepCache::ModeDelete:
2676 if ((state.iFlags & pkgDepCache::Purge) != 0)
2680 case pkgDepCache::ModeKeep:
2681 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2682 return @"REINSTALL";
2683 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2687 case pkgDepCache::ModeInstall:
2688 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2689 return @"REINSTALL";
2690 else*/ switch (state.Status) {
2692 return @"DOWNGRADE";
2698 return @"NEW_INSTALL";
2709 - (NSString *) name {
2710 return name_.empty() ? id_ : name_;
2713 - (UIImage *) icon {
2714 NSString *section = [self simpleSection];
2717 if (parsed_ != NULL)
2718 if (NSString *href = parsed_->icon_)
2719 if ([href hasPrefix:@"file:///"])
2720 // XXX: correct escaping
2721 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2722 if (icon == nil) if (section != nil)
2723 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2724 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2725 if ([dicon hasPrefix:@"file:///"])
2726 // XXX: correct escaping
2727 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2729 icon = [UIImage applicationImageNamed:@"unknown.png"];
2733 - (NSString *) homepage {
2734 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2737 - (NSString *) depiction {
2738 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2741 - (Address *) sponsor {
2742 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2745 - (Address *) author {
2746 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2749 - (NSString *) support {
2750 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2753 - (NSArray *) files {
2754 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2755 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2758 fin.open([path UTF8String]);
2763 while (std::getline(fin, line))
2764 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2769 - (NSArray *) warnings {
2770 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2771 const char *name(iterator_.Name());
2773 size_t length(strlen(name));
2774 if (length < 2) invalid:
2775 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2776 else for (size_t i(0); i != length; ++i)
2778 /* XXX: technically this is not allowed */
2779 (name[i] < 'A' || name[i] > 'Z') &&
2780 (name[i] < 'a' || name[i] > 'z') &&
2781 (name[i] < '0' || name[i] > '9') &&
2782 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2785 if (strcmp(name, "cydia") != 0) {
2788 bool _private = false;
2791 bool repository = [[self section] isEqualToString:@"Repositories"];
2793 if (NSArray *files = [self files])
2794 for (NSString *file in files)
2795 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2797 else if (!user && [file isEqualToString:@"/User"])
2799 else if (!_private && [file isEqualToString:@"/private"])
2801 else if (!stash && [file isEqualToString:@"/var/stash"])
2804 /* XXX: this is not sensitive enough. only some folders are valid. */
2805 if (cydia && !repository)
2806 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2808 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2810 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2812 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2815 return [warnings count] == 0 ? nil : warnings;
2818 - (NSArray *) applications {
2819 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2821 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2823 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2824 if (NSArray *files = [self files])
2825 for (NSString *file in files)
2826 if (application_r(file)) {
2827 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2828 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2829 if ([id isEqualToString:me])
2832 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2834 display = application_r[1];
2836 NSString *bundle([file stringByDeletingLastPathComponent]);
2837 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2838 if (icon == nil || [icon length] == 0)
2840 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2842 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2843 [applications addObject:application];
2845 [application addObject:id];
2846 [application addObject:display];
2847 [application addObject:url];
2850 return [applications count] == 0 ? nil : applications;
2853 - (Source *) source {
2854 if (source_ == nil) {
2855 @synchronized (database_) {
2856 if ([database_ era] != era_ || file_.end())
2857 source_ = (Source *) [NSNull null];
2859 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2863 return source_ == (Source *) [NSNull null] ? nil : source_;
2866 - (BOOL) matches:(NSString *)text {
2872 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2873 if (range.location != NSNotFound)
2876 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2877 if (range.location != NSNotFound)
2882 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2883 if (range.location != NSNotFound)
2889 - (bool) hasSupportingRole {
2894 if ([Role_ isEqualToString:@"User"])
2898 if ([Role_ isEqualToString:@"Hacker"])
2902 if ([Role_ isEqualToString:@"Developer"])
2907 - (BOOL) hasTag:(NSString *)tag {
2908 return tags_ == nil ? NO : [tags_ containsObject:tag];
2911 - (NSString *) primaryPurpose {
2912 for (NSString *tag in tags_)
2913 if ([tag hasPrefix:@"purpose::"])
2914 return [tag substringFromIndex:9];
2918 - (NSArray *) purposes {
2919 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2920 for (NSString *tag in tags_)
2921 if ([tag hasPrefix:@"purpose::"])
2922 [purposes addObject:[tag substringFromIndex:9]];
2923 return [purposes count] == 0 ? nil : purposes;
2926 - (bool) isCommercial {
2927 return [self hasTag:@"cydia::commercial"];
2930 - (void) setIndex:(size_t)index {
2931 if (metadata_->index_ != index)
2932 metadata_->index_ = index;
2935 - (CYString &) cyname {
2936 return name_.empty() ? id_ : name_;
2939 - (uint32_t) compareBySection:(NSArray *)sections {
2940 NSString *section([self section]);
2941 for (size_t i(0), e([sections count]); i != e; ++i) {
2942 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2946 return _not(uint32_t);
2950 @synchronized (database_) {
2951 pkgProblemResolver *resolver = [database_ resolver];
2952 resolver->Clear(iterator_);
2954 pkgCacheFile &cache([database_ cache]);
2955 cache->SetReInstall(iterator_, false);
2956 cache->MarkKeep(iterator_, false);
2960 @synchronized (database_) {
2961 pkgProblemResolver *resolver = [database_ resolver];
2962 resolver->Clear(iterator_);
2963 resolver->Protect(iterator_);
2965 pkgCacheFile &cache([database_ cache]);
2966 cache->SetReInstall(iterator_, false);
2967 cache->MarkInstall(iterator_, false);
2969 pkgDepCache::StateCache &state((*cache)[iterator_]);
2970 if (!state.Install())
2971 cache->SetReInstall(iterator_, true);
2975 @synchronized (database_) {
2976 pkgProblemResolver *resolver = [database_ resolver];
2977 resolver->Clear(iterator_);
2978 resolver->Remove(iterator_);
2979 resolver->Protect(iterator_);
2981 pkgCacheFile &cache([database_ cache]);
2982 cache->SetReInstall(iterator_, false);
2983 cache->MarkDelete(iterator_, true);
2986 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2987 _profile(Package$isUnfilteredAndSearchedForBy)
2990 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2991 value &= [self unfiltered];
2994 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2995 value &= [self matches:search];
3002 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3003 if ([search length] == 0)
3006 _profile(Package$isUnfilteredAndSelectedForBy)
3009 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3010 value &= [self unfiltered];
3013 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3014 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3021 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3022 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3025 - (bool) isVisibleInSection:(NSString *)name {
3026 NSString *section([self section]);
3030 section == nil && [name length] == 0 ||
3031 [name isEqualToString:section]
3032 ) && [self visible];
3035 - (bool) isVisibleInSource:(Source *)source {
3036 return [self source] == source && [self visible];
3041 /* Section Class {{{ */
3042 @interface Section : NSObject {
3047 NSString *localized_;
3050 - (NSComparisonResult) compareByLocalized:(Section *)section;
3051 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3052 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3053 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3054 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3055 - (NSString *) name;
3062 - (void) addToCount;
3064 - (void) setCount:(size_t)count;
3065 - (NSString *) localized;
3069 @implementation Section
3073 if (localized_ != nil)
3074 [localized_ release];
3078 - (NSComparisonResult) compareByLocalized:(Section *)section {
3079 NSString *lhs(localized_);
3080 NSString *rhs([section localized]);
3082 /*if ([lhs length] != 0 && [rhs length] != 0) {
3083 unichar lhc = [lhs characterAtIndex:0];
3084 unichar rhc = [rhs characterAtIndex:0];
3086 if (isalpha(lhc) && !isalpha(rhc))
3087 return NSOrderedAscending;
3088 else if (!isalpha(lhc) && isalpha(rhc))
3089 return NSOrderedDescending;
3092 return [lhs compare:rhs options:LaxCompareOptions_];
3095 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3096 if ((self = [self initWithName:name localize:NO]) != nil) {
3097 if (localized != nil)
3098 localized_ = [localized retain];
3102 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3103 return [self initWithName:name row:0 localize:localize];
3106 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3107 if ((self = [super init]) != nil) {
3108 name_ = [name retain];
3112 localized_ = [LocalizeSection(name_) retain];
3116 /* XXX: localize the index thingees */
3117 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3118 if ((self = [super init]) != nil) {
3119 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3125 - (NSString *) name {
3145 - (void) addToCount {
3149 - (void) setCount:(size_t)count {
3153 - (NSString *) localized {
3160 static NSString *Colon_;
3161 static NSString *Elision_;
3162 static NSString *Error_;
3163 static NSString *Warning_;
3165 /* Database Implementation {{{ */
3166 @implementation Database
3168 + (Database *) sharedInstance {
3169 static Database *instance;
3170 if (instance == nil)
3171 instance = [[Database alloc] init];
3179 - (void) releasePackages {
3180 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3181 CFArrayRemoveAllValues(packages_);
3185 // XXX: actually implement this thing
3187 [sourceList_ release];
3188 [self releasePackages];
3189 apr_pool_destroy(pool_);
3190 NSRecycleZone(zone_);
3194 - (void) _readCydia:(NSNumber *)fd { _pooled
3195 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3196 std::istream is(&ib);
3199 static Pcre finish_r("^finish:([^:]*)$");
3201 while (std::getline(is, line)) {
3202 const char *data(line.c_str());
3203 size_t size = line.size();
3204 lprintf("C:%s\n", data);
3206 if (finish_r(data, size)) {
3207 NSString *finish = finish_r[1];
3208 int index = [Finishes_ indexOfObject:finish];
3209 if (index != INT_MAX && index > Finish_)
3217 - (void) _readStatus:(NSNumber *)fd { _pooled
3218 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3219 std::istream is(&ib);
3222 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3223 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3225 while (std::getline(is, line)) {
3226 const char *data(line.c_str());
3227 size_t size(line.size());
3228 lprintf("S:%s\n", data);
3230 if (conffile_r(data, size))
3231 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3232 else if (strncmp(data, "status: ", 8) == 0)
3233 [delegate_ performSelectorOnMainThread:@selector(setProgressTitle:) withObject:[NSString stringWithUTF8String:(data + 8)] waitUntilDone:YES];
3234 else if (pmstatus_r(data, size)) {
3235 std::string type([pmstatus_r[1] UTF8String]);
3236 NSString *id = pmstatus_r[2];
3238 float percent([pmstatus_r[3] floatValue]);
3239 [delegate_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3241 NSString *string = pmstatus_r[4];
3243 if (type == "pmerror")
3244 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3245 withObject:[NSArray arrayWithObjects:string, id, nil]
3248 else if (type == "pmstatus")
3249 [delegate_ performSelectorOnMainThread:@selector(setProgressTitle:) withObject:string waitUntilDone:YES];
3250 else if (type == "pmconffile")
3251 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3253 lprintf("E:unknown pmstatus\n");
3255 lprintf("E:unknown status\n");
3261 - (void) _readOutput:(NSNumber *)fd { _pooled
3262 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3263 std::istream is(&ib);
3266 while (std::getline(is, line)) {
3267 lprintf("O:%s\n", line.c_str());
3269 [delegate_ performSelectorOnMainThread:@selector(addProgressOutput:) withObject:[NSString stringWithUTF8String:line.c_str()] waitUntilDone:YES];
3279 - (Package *) packageWithName:(NSString *)name {
3280 @synchronized (self) {
3281 if (static_cast<pkgDepCache *>(cache_) == NULL)
3283 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3284 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3288 if ((self = [super init]) != nil) {
3295 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3296 apr_pool_create(&pool_, NULL);
3298 size_t capacity(MetaFile_->active_);
3304 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3305 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3309 _assert(pipe(fds) != -1);
3312 _config->Set("APT::Keep-Fds::", cydiafd_);
3313 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3316 detachNewThreadSelector:@selector(_readCydia:)
3318 withObject:[NSNumber numberWithInt:fds[0]]
3321 _assert(pipe(fds) != -1);
3325 detachNewThreadSelector:@selector(_readStatus:)
3327 withObject:[NSNumber numberWithInt:fds[0]]
3330 _assert(pipe(fds) != -1);
3331 _assert(dup2(fds[0], 0) != -1);
3332 _assert(close(fds[0]) != -1);
3334 input_ = fdopen(fds[1], "a");
3336 _assert(pipe(fds) != -1);
3337 _assert(dup2(fds[1], 1) != -1);
3338 _assert(close(fds[1]) != -1);
3341 detachNewThreadSelector:@selector(_readOutput:)
3343 withObject:[NSNumber numberWithInt:fds[0]]
3348 - (pkgCacheFile &) cache {
3352 - (pkgDepCache::Policy *) policy {
3356 - (pkgRecords *) records {
3360 - (pkgProblemResolver *) resolver {
3364 - (pkgAcquire &) fetcher {
3368 - (pkgSourceList &) list {
3372 - (NSArray *) packages {
3373 return (NSArray *) packages_;
3376 - (NSArray *) sources {
3380 - (Source *) sourceWithKey:(NSString *)key {
3381 for (Source *source in [self sources]) {
3382 if ([[source key] isEqualToString:key])
3387 - (bool) popErrorWithTitle:(NSString *)title {
3389 std::string message;
3391 while (!_error->empty()) {
3393 bool warning(!_error->PopMessage(error));
3397 size_t size(error.size());
3398 if (size == 0 || error[size - 1] != '\n')
3400 error.resize(size - 1);
3402 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3404 if (!message.empty())
3409 if (fatal && !message.empty())
3410 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3415 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3416 return [self popErrorWithTitle:title] || !success;
3419 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3420 @synchronized (self) {
3423 [self releasePackages];
3426 [sourceList_ removeAllObjects];
3446 apr_pool_clear(pool_);
3448 NSRecycleZone(zone_);
3449 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3451 int chk(creat("/tmp/cydia.chk", 0644));
3455 if (invocation != nil)
3456 [invocation invoke];
3458 NSString *title(UCLocalize("DATABASE"));
3461 OpProgress progress;
3462 while (!cache_.Open(progress, true)) { pop:
3464 bool warning(!_error->PopMessage(error));
3465 lprintf("cache_.Open():[%s]\n", error.c_str());
3467 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3468 [delegate_ repairWithSelector:@selector(configure)];
3469 else if (error == "The package lists or status file could not be parsed or opened.")
3470 [delegate_ repairWithSelector:@selector(update)];
3471 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3472 else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3473 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, Error_, title]];
3474 // else if (error == "The list of sources could not be read.")
3476 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3486 unlink("/tmp/cydia.chk");
3488 now_ = [[NSDate date] timeIntervalSince1970];
3490 policy_ = new pkgDepCache::Policy();
3491 records_ = new pkgRecords(cache_);
3492 resolver_ = new pkgProblemResolver(cache_);
3493 fetcher_ = new pkgAcquire(&status_);
3496 list_ = new pkgSourceList();
3497 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3500 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3501 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3505 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3508 if (cache_->BrokenCount() != 0) {
3509 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3512 if (cache_->BrokenCount() != 0) {
3513 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3517 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3521 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3522 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3523 [sourceList_ addObject:object];
3525 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3526 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3527 // XXX: this could be more intelligent
3528 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3529 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3531 sourceMap_[cached->ID] = object;
3536 /*std::vector<Package *> packages;
3537 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3538 [packages_ release];
3543 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3544 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3545 //packages.push_back(package);
3546 CFArrayAppendValue(packages_, [package retain]);
3550 /*if (packages.empty())
3551 packages_ = [[NSArray alloc] init];
3553 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3556 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3557 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3558 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3566 /*if (!packages.empty())
3567 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3568 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3570 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3572 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3574 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3578 size_t count(CFArrayGetCount(packages_));
3579 MetaFile_->active_ = count;
3581 for (size_t index(0); index != count; ++index)
3582 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3586 } } CYPoolEnd() _trace(); }
3589 @synchronized (self) {
3591 resolver_ = new pkgProblemResolver(cache_);
3593 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3594 if (!cache_[iterator].Keep())
3595 cache_->MarkKeep(iterator, false);
3596 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3597 cache_->SetReInstall(iterator, false);
3600 - (void) configure {
3601 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3603 system([dpkg UTF8String]);
3608 // XXX: I don't remember this condition
3613 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3615 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3617 if ([self popErrorWithTitle:title])
3621 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3624 public pkgArchiveCleaner
3627 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3632 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3639 fetcher_->Shutdown();
3641 pkgRecords records(cache_);
3643 lock_ = new FileFd();
3644 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3646 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3648 if ([self popErrorWithTitle:title])
3652 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3655 manager_ = (_system->CreatePM(cache_));
3656 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3663 bool substrate(RestartSubstrate_);
3664 RestartSubstrate_ = false;
3666 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3668 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3670 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3672 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3673 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3676 [CydiaApp performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3678 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3683 bool failed = false;
3684 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3685 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3687 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3690 std::string uri = (*item)->DescURI();
3691 std::string error = (*item)->ErrorText;
3693 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3696 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3697 withObject:[NSArray arrayWithObjects:
3698 [NSString stringWithUTF8String:error.c_str()],
3704 [CydiaApp performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3712 RestartSubstrate_ = true;
3715 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3717 if (_error->PendingError()) {
3722 if (result == pkgPackageManager::Failed) {
3727 if (result != pkgPackageManager::Completed) {
3732 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3734 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3736 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3737 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3740 if (![before isEqualToArray:after])
3745 NSString *title(UCLocalize("UPGRADE"));
3746 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3752 [self updateWithStatus:status_];
3755 - (void) updateWithStatus:(Status &)status {
3756 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3757 NSString *title(UCLocalize("REFRESHING_DATA"));
3760 if (!list.ReadMainList())
3761 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3764 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3765 if ([self popErrorWithTitle:title])
3768 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3769 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3770 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3772 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3776 - (void) setDelegate:(id)delegate {
3777 delegate_ = delegate;
3778 status_.setDelegate(delegate);
3781 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3782 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3783 return i == sourceMap_.end() ? nil : i->second;
3786 - (NSString *) mappedSectionForPointer:(const char *)section {
3787 _H<NSString> *mapped;
3789 _profile(Database$mappedSectionForPointer$Cache)
3790 mapped = §ions_[section];
3793 if (*mapped == NULL) {
3794 size_t length(strlen(section));
3795 char spaced[length + 1];
3797 _profile(Database$mappedSectionForPointer$Replace)
3798 for (size_t index(0); index != length; ++index)
3799 spaced[index] = section[index] == '_' ? ' ' : section[index];
3800 spaced[length] = '\0';
3805 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3806 string = [NSString stringWithUTF8String:spaced];
3809 _profile(Database$mappedSectionForPointer$Map)
3810 string = [SectionMap_ objectForKey:string] ?: string;
3820 /* Web Scripting {{{ */
3821 @interface CydiaObject : NSObject {
3823 _transient id delegate_;
3826 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3830 @implementation CydiaObject
3833 [indirect_ release];
3837 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3838 if ((self = [super init]) != nil) {
3839 indirect_ = [indirect retain];
3843 - (void) setDelegate:(id)delegate {
3844 delegate_ = delegate;
3847 + (NSArray *) _attributeKeys {
3848 return [NSArray arrayWithObjects:
3858 - (NSArray *) attributeKeys {
3859 return [[self class] _attributeKeys];
3862 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3863 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3866 - (NSString *) device {
3867 return [[UIDevice currentDevice] uniqueIdentifier];
3870 - (NSString *) plmn {
3874 - (NSString *) ecid {
3878 - (NSString *) serial {
3879 return SerialNumber_;
3882 - (NSString *) role {
3886 - (NSString *) model {
3887 return [NSString stringWithUTF8String:Machine_];
3890 + (NSString *) webScriptNameForSelector:(SEL)selector {
3892 else if (selector == @selector(addTrivialSource:))
3893 return @"addTrivialSource";
3894 else if (selector == @selector(close))
3896 else if (selector == @selector(du:))
3898 else if (selector == @selector(stringWithFormat:arguments:))
3900 else if (selector == @selector(getAllSources))
3901 return @"getAllSourcs";
3902 else if (selector == @selector(getKernelNumber:))
3903 return @"getKernelNumber";
3904 else if (selector == @selector(getKernelString:))
3905 return @"getKernelString";
3906 else if (selector == @selector(getInstalledPackages))
3907 return @"getInstalledPackages";
3908 else if (selector == @selector(getPackageById:))
3909 return @"getPackageById";
3910 else if (selector == @selector(installPackages:))
3911 return @"installPackages";
3912 else if (selector == @selector(localizedStringForKey:value:table:))
3914 else if (selector == @selector(refreshSources))
3915 return @"refreshSources";
3916 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3917 return @"setButtonImage";
3918 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3919 return @"setButtonTitle";
3920 else if (selector == @selector(setPopupHook:))
3921 return @"setPopupHook";
3922 else if (selector == @selector(setToken:))
3924 else if (selector == @selector(setViewportWidth:))
3925 return @"setViewportWidth";
3926 else if (selector == @selector(statfs:))
3928 else if (selector == @selector(supports:))
3934 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3935 return [self webScriptNameForSelector:selector] == nil;
3938 - (BOOL) supports:(NSString *)feature {
3939 return [feature isEqualToString:@"window.open"];
3942 - (NSNumber *) getKernelNumber:(NSString *)name {
3943 const char *string([name UTF8String]);
3946 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3947 return (id) [NSNull null];
3949 if (size != sizeof(int))
3950 return (id) [NSNull null];
3953 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3954 return (id) [NSNull null];
3956 return [NSNumber numberWithInt:value];
3959 - (NSString *) getKernelString:(NSString *)name {
3960 const char *string([name UTF8String]);
3963 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3964 return (id) [NSNull null];
3966 char value[size + 1];
3967 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3968 return (id) [NSNull null];
3970 // XXX: just in case you request something ludicrous
3973 return [NSString stringWithCString:value];
3976 - (void) addTrivialSource:(NSString *)href {
3977 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
3980 - (void) refreshSources {
3981 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
3984 - (NSArray *) getAllSources {
3985 return [[Database sharedInstance] sources];
3988 - (NSArray *) getInstalledPackages {
3989 Database *database([Database sharedInstance]);
3990 @synchronized (database) {
3991 NSArray *packages([database packages]);
3992 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3993 for (Package *package in packages)
3994 if (![package uninstalled])
3995 [installed addObject:package];
3999 - (Package *) getPackageById:(NSString *)id {
4000 Package *package([[Database sharedInstance] packageWithName:id]);
4005 - (NSArray *) statfs:(NSString *)path {
4008 if (path == nil || statfs([path UTF8String], &stat) == -1)
4011 return [NSArray arrayWithObjects:
4012 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4013 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4014 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4018 - (NSNumber *) du:(NSString *)path {
4019 NSNumber *value(nil);
4022 _assert(pipe(fds) != -1);
4024 pid_t pid(ExecFork());
4026 _assert(dup2(fds[1], 1) != -1);
4027 _assert(close(fds[0]) != -1);
4028 _assert(close(fds[1]) != -1);
4029 /* XXX: this should probably not use du */
4030 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4035 _assert(close(fds[1]) != -1);
4037 if (FILE *du = fdopen(fds[0], "r")) {
4039 while (fgets(line, sizeof(line), du) != NULL) {
4040 size_t length(strlen(line));
4041 while (length != 0 && line[length - 1] == '\n')
4042 line[--length] = '\0';
4043 if (char *tab = strchr(line, '\t')) {
4045 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4050 } else _assert(close(fds[0]));
4054 if (waitpid(pid, &status, 0) == -1)
4057 else _assert(false);
4063 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4066 - (void) installPackages:(NSArray *)packages {
4067 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4070 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4071 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4074 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4075 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4078 - (void) _setToken:(NSString *)token {
4081 Token_ = [token retain];
4083 [Metadata_ setObject:Token_ forKey:@"Token"];
4087 - (void) setToken:(NSString *)token {
4088 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4091 - (void) setPopupHook:(id)function {
4092 [indirect_ setPopupHook:function];
4095 - (void) setViewportWidth:(float)width {
4096 [indirect_ setViewportWidthOnMainThread:width];
4099 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4100 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4101 unsigned count([arguments count]);
4103 for (unsigned i(0); i != count; ++i)
4104 values[i] = [arguments objectAtIndex:i];
4105 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4108 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4109 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4111 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4113 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4119 /* @ Loading... Indicator {{{ */
4120 @interface CYLoadingIndicator : UIView {
4121 UIActivityIndicatorView *spinner_;
4126 @property (readonly, nonatomic) UILabel *label;
4127 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4131 @implementation CYLoadingIndicator
4133 - (id) initWithFrame:(CGRect)frame {
4134 if ((self = [super initWithFrame:frame]) != nil) {
4135 container_ = [[[UIView alloc] init] autorelease];
4136 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4138 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4139 [spinner_ startAnimating];
4140 [container_ addSubview:spinner_];
4142 label_ = [[[UILabel alloc] init] autorelease];
4143 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4144 [label_ setBackgroundColor:[UIColor clearColor]];
4145 [label_ setTextColor:[UIColor blackColor]];
4146 [label_ setShadowColor:[UIColor whiteColor]];
4147 [label_ setShadowOffset:CGSizeMake(0, 1)];
4148 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4149 [container_ addSubview:label_];
4151 CGSize viewsize = frame.size;
4152 CGSize spinnersize = [spinner_ bounds].size;
4153 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4154 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4156 CGRect containrect = {
4157 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4158 CGSizeMake(bothwidth, spinnersize.height)
4161 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4169 [container_ setFrame:containrect];
4170 [spinner_ setFrame:spinrect];
4171 [label_ setFrame:textrect];
4172 [self addSubview:container_];
4176 - (UILabel *) label {
4180 - (UIActivityIndicatorView *) activityIndicatorView {
4186 /* Emulated Loading Controller {{{ */
4187 @interface CYEmulatedLoadingController : CYViewController <
4189 ConfigurationDelegate
4191 _transient Database *database_;
4192 CYLoadingIndicator *indicator_;
4194 UINavigationBar *navbar_;
4199 @implementation CYEmulatedLoadingController
4202 [self releaseSubviews];
4203 [database_ setDelegate:nil];
4208 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4209 CYAlertView *sheet([[[CYAlertView alloc]
4211 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4212 defaultButtonIndex:0
4215 [sheet setMessage:error];
4216 [sheet yieldToPopupAlertAnimated:YES];
4220 - (void) setProgressTitle:(NSString *)title { }
4221 - (void) setProgressPercent:(NSNumber *)percent { }
4222 - (void) startProgress { }
4223 - (void) addProgressOutput:(NSString *)output { }
4224 - (bool) isCancelling:(size_t)received { return NO; }
4225 - (void) setConfigurationData:(NSString *)data { }
4227 - (void) repairWithSelector:(SEL)selector {
4228 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("REPAIRING"), nil] waitUntilDone:YES];
4229 [database_ performSelector:selector];
4231 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil] waitUntilDone:YES];
4234 - (id) initWithDatabase:(Database *)database {
4235 if ((self = [super init]) != nil) {
4236 database_ = database;
4237 [database_ setDelegate:self];
4242 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4243 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4245 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4246 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4247 [[self view] addSubview:indicator_];
4249 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4250 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4251 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4252 [[self view] addSubview:tabbar_];
4254 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4255 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4256 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4257 [[self view] addSubview:navbar_];
4260 - (void) releaseSubviews {
4261 [indicator_ release];
4274 /* Cydia Browser Controller {{{ */
4275 @interface CYBrowserController : BrowserController {
4276 CydiaObject *cydia_;
4281 @implementation CYBrowserController
4288 - (NSURL *) navigationURL {
4289 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4292 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4295 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4296 [super webView:view didClearWindowObject:window forFrame:frame];
4298 WebDataSource *source([frame dataSource]);
4299 NSURLResponse *response([source response]);
4301 NSURL *url([response URL]);
4302 NSString *scheme([url scheme]);
4303 NSString *host([url host]);
4305 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4306 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4307 NSDictionary *headers([http allHeaderFields]);
4308 [self setHeaders:headers forHost:host];
4312 [host isEqualToString:@"cydia.saurik.com"] ||
4313 [host hasSuffix:@".cydia.saurik.com"] ||
4314 [scheme isEqualToString:@"file"]
4316 [window setValue:cydia_ forKey:@"cydia"];
4319 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4320 if (System_ != NULL)
4321 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4322 if (Machine_ != NULL)
4323 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4325 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4327 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4330 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4331 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4332 [self _setMoreHeaders:copy];
4336 - (void) setDelegate:(id)delegate {
4337 [super setDelegate:delegate];
4338 [cydia_ setDelegate:delegate];
4342 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4343 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4345 WebView *webview([[webview_ _documentView] webView]);
4347 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4349 NSString *application = package == nil ? @"Cydia" : [NSString
4350 stringWithFormat:@"Cydia/%@",
4355 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4357 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4358 if (Product_ != nil)
4359 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4361 [webview setApplicationNameForUserAgent:application];
4369 @interface NSObject (CydiaScript)
4370 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4373 @implementation NSObject (CydiaScript)
4375 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4381 @implementation NSArray (CydiaScript)
4383 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4384 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4385 for (size_t i(0), e([self count]); i != e; ++i)
4386 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4392 @implementation NSDictionary (CydiaScript)
4394 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4395 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4397 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4404 /* Confirmation Controller {{{ */
4405 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4406 if (!iterator.end())
4407 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4408 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4410 pkgCache::PkgIterator package(dep.TargetPkg());
4413 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4420 @protocol ConfirmationControllerDelegate
4421 - (void) cancelAndClear:(bool)clear;
4422 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4426 @interface ConfirmationController : CYBrowserController {
4427 _transient Database *database_;
4429 UIAlertView *essential_;
4431 NSDictionary *changes_;
4432 NSMutableArray *issues_;
4433 NSDictionary *sizes_;
4438 - (id) initWithDatabase:(Database *)database;
4442 @implementation ConfirmationController
4449 if (essential_ != nil)
4450 [essential_ release];
4457 RestartSubstrate_ = true;
4458 [delegate_ confirmWithNavigationController:[self navigationController]];
4461 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4462 NSString *context([alert context]);
4464 if ([context isEqualToString:@"remove"]) {
4465 if (button == [alert cancelButtonIndex])
4466 [self dismissModalViewControllerAnimated:YES];
4467 else if (button == [alert firstOtherButtonIndex]) {
4471 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4472 } else if ([context isEqualToString:@"unable"]) {
4473 [self dismissModalViewControllerAnimated:YES];
4474 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4476 [super alertView:alert clickedButtonAtIndex:button];
4480 - (void) _doContinue {
4481 [self dismissModalViewControllerAnimated:YES];
4482 [delegate_ cancelAndClear:NO];
4485 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4486 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4490 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4491 [super webView:view didClearWindowObject:window forFrame:frame];
4493 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4494 changes_, @"changes",
4498 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4501 - (id) initWithDatabase:(Database *)database {
4502 if ((self = [super init]) != nil) {
4503 database_ = database;
4505 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4506 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4507 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4508 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4509 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4513 pkgCacheFile &cache([database_ cache]);
4514 NSArray *packages([database_ packages]);
4515 pkgDepCache::Policy *policy([database_ policy]);
4517 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4519 for (Package *package in packages) {
4520 pkgCache::PkgIterator iterator([package iterator]);
4521 NSString *name([package id]);
4523 if ([package broken]) {
4524 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4526 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4528 reasons, @"reasons",
4531 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4535 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4536 pkgCache::DepIterator start;
4537 pkgCache::DepIterator end;
4538 dep.GlobOr(start, end); // ++dep
4540 if (!cache->IsImportantDep(end))
4542 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4545 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4547 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4548 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4549 clauses, @"clauses",
4553 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4555 pkgCache::PkgIterator target(start.TargetPkg());
4556 if (target->ProvidesList != 0)
4557 reason = @"missing";
4559 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4561 reason = @"installed";
4562 installed = [NSString stringWithUTF8String:ver.VerStr()];
4563 } else if (!cache[target].CandidateVerIter(cache).end())
4564 reason = @"uninstalled";
4565 else if (target->ProvidesList == 0)
4566 reason = @"uninstallable";
4568 reason = @"virtual";
4571 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4572 [NSString stringWithUTF8String:start.CompType()], @"operator",
4573 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4576 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4577 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4578 version, @"version",
4580 installed, @"installed",
4583 // yes, seriously. (wtf?)
4591 pkgDepCache::StateCache &state(cache[iterator]);
4593 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4595 if (state.NewInstall())
4596 [installs addObject:name];
4597 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4598 [reinstalls addObject:name];
4599 else if (state.Upgrade())
4600 [upgrades addObject:name];
4601 else if (state.Downgrade())
4602 [downgrades addObject:name];
4603 else if (!state.Delete())
4605 else if (special_r(name))
4606 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4607 [NSNull null], @"package",
4608 [NSArray arrayWithObjects:
4609 [NSDictionary dictionaryWithObjectsAndKeys:
4610 @"Conflicts", @"relationship",
4611 [NSArray arrayWithObjects:
4612 [NSDictionary dictionaryWithObjectsAndKeys:
4614 [NSNull null], @"version",
4615 @"installed", @"reason",
4622 if ([package essential])
4624 [removes addObject:name];
4627 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4628 substrate_ |= DepSubstrate(iterator.CurrentVer());
4633 else if (Advanced_) {
4634 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4636 essential_ = [[UIAlertView alloc]
4637 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4638 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4640 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4642 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4646 [essential_ setContext:@"remove"];
4648 essential_ = [[UIAlertView alloc]
4649 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4650 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4652 cancelButtonTitle:UCLocalize("OKAY")
4653 otherButtonTitles:nil
4656 [essential_ setContext:@"unable"];
4659 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4660 installs, @"installs",
4661 reinstalls, @"reinstalls",
4662 upgrades, @"upgrades",
4663 downgrades, @"downgrades",
4664 removes, @"removes",
4667 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4668 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4669 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4672 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4674 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4675 initWithTitle:UCLocalize("CANCEL")
4676 style:UIBarButtonItemStylePlain
4678 action:@selector(cancelButtonClicked)
4684 - (void) applyRightButton {
4685 if ([issues_ count] == 0 && ![self isLoading])
4686 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4687 initWithTitle:UCLocalize("CONFIRM")
4688 style:UIBarButtonItemStyleDone
4690 action:@selector(confirmButtonClicked)
4693 [[self navigationItem] setRightBarButtonItem:nil];
4697 - (void) cancelButtonClicked {
4698 [self dismissModalViewControllerAnimated:YES];
4699 [delegate_ cancelAndClear:YES];
4703 - (void) confirmButtonClicked {
4704 if (essential_ != nil)
4714 /* Progress Data {{{ */
4715 @interface ProgressData : NSObject {
4717 // XXX: should these really both be _transient?
4718 _transient id target_;
4719 _transient id object_;
4722 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4730 @implementation ProgressData
4732 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4733 if ((self = [super init]) != nil) {
4734 selector_ = selector;
4754 /* Progress Controller {{{ */
4755 @interface ProgressController : CYViewController <
4756 ConfigurationDelegate,
4759 _transient Database *database_;
4760 UIProgressBar *progress_;
4761 UITextView *output_;
4762 UITextLabel *status_;
4763 UIPushButton *close_;
4765 SHA1SumValue springlist_;
4766 SHA1SumValue notifyconf_;
4770 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4772 - (void) _retachThread;
4773 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4779 @protocol ProgressControllerDelegate
4780 - (void) progressControllerIsComplete:(ProgressController *)sender;
4783 @implementation ProgressController
4786 [database_ setDelegate:nil];
4787 [progress_ release];
4796 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4797 if ((self = [super init]) != nil) {
4798 database_ = database;
4799 [database_ setDelegate:self];
4800 delegate_ = delegate;
4802 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4804 progress_ = [[UIProgressBar alloc] init];
4805 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4806 [progress_ setStyle:0];
4808 status_ = [[UITextLabel alloc] init];
4809 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4810 [status_ setColor:[UIColor whiteColor]];
4811 [status_ setBackgroundColor:[UIColor clearColor]];
4812 [status_ setCentersHorizontally:YES];
4813 //[status_ setFont:font];
4815 output_ = [[UITextView alloc] init];
4816 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4817 //[output_ setTextFont:@"Courier New"];
4818 [output_ setFont:[[output_ font] fontWithSize:12]];
4819 [output_ setTextColor:[UIColor whiteColor]];
4820 [output_ setBackgroundColor:[UIColor clearColor]];
4821 [output_ setMarginTop:0];
4822 [output_ setAllowsRubberBanding:YES];
4823 [output_ setEditable:NO];
4824 [[self view] addSubview:output_];
4826 close_ = [[UIPushButton alloc] init];
4827 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4828 [close_ setAutosizesToFit:NO];
4829 [close_ setDrawsShadow:YES];
4830 [close_ setStretchBackground:YES];
4831 [close_ setEnabled:YES];
4832 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4833 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4834 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4835 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4839 - (void) positionViews {
4840 CGRect bounds = [[self view] bounds];
4841 CGSize prgsize = [UIProgressBar defaultSize];
4844 (bounds.size.width - prgsize.width) / 2,
4845 bounds.size.height - prgsize.height - 20
4848 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4850 [progress_ setFrame:prgrect];
4851 [status_ setFrame:CGRectMake(
4853 bounds.size.height - prgsize.height - 50,
4854 bounds.size.width - 20,
4857 [output_ setFrame:CGRectMake(
4860 bounds.size.width - 20,
4861 bounds.size.height - 96
4863 [close_ setFrame:CGRectMake(
4864 (bounds.size.width - closewidth) / 2,
4865 bounds.size.height - prgsize.height - 50,
4871 - (void) viewWillAppear:(BOOL)animated {
4872 [super viewDidAppear:animated];
4873 [[self navigationItem] setHidesBackButton:YES];
4874 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4876 [self positionViews];
4879 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4880 [self positionViews];
4883 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4884 NSString *context([alert context]);
4886 if ([context isEqualToString:@"conffile"]) {
4887 FILE *input = [database_ input];
4888 if (button == [alert cancelButtonIndex])
4889 fprintf(input, "N\n");
4890 else if (button == [alert firstOtherButtonIndex])
4891 fprintf(input, "Y\n");
4894 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4898 - (void) closeButtonPushed {
4901 UpdateExternalStatus(0);
4905 [self dismissModalViewControllerAnimated:YES];
4909 [delegate_ terminateWithSuccess];
4910 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4911 [delegate_ suspendWithAnimation:YES];
4913 [delegate_ suspend];*/
4925 system("/usr/bin/sbreload");
4931 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4932 SBReboot(SBSSpringBoardServerPort());
4934 reboot2(RB_AUTOBOOT);
4939 - (void) _retachThread {
4940 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4942 [[self view] addSubview:close_];
4943 [progress_ removeFromSuperview];
4944 [status_ removeFromSuperview];
4946 [database_ popErrorWithTitle:title_];
4947 [delegate_ progressControllerIsComplete:self];
4951 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4954 MMap mmap(file, MMap::ReadOnly);
4956 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4957 if (!(notifyconf_ == sha1.Result()))
4964 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4967 MMap mmap(file, MMap::ReadOnly);
4969 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4970 if (!(springlist_ == sha1.Result()))
4976 if (RestartSubstrate_)
4980 RestartSubstrate_ = false;
4983 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4984 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4985 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4986 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4987 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4991 system("su -c /usr/bin/uicache mobile");
4994 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4996 [delegate_ setStatusBarShowsProgress:NO];
4999 - (void) _detachNewThreadInvocation:(NSInvocation *)invocation { _pooled
5000 [invocation invoke];
5001 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
5004 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
5005 UpdateExternalStatus(1);
5012 title_ = [title retain];
5014 [[self navigationItem] setTitle:title_];
5016 [status_ setText:nil];
5017 [output_ setText:@""];
5018 [progress_ setProgress:0];
5020 [close_ removeFromSuperview];
5021 [[self view] addSubview:progress_];
5022 [[self view] addSubview:status_];
5024 [delegate_ setStatusBarShowsProgress:YES];
5029 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5032 MMap mmap(file, MMap::ReadOnly);
5034 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5035 notifyconf_ = sha1.Result();
5041 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5044 MMap mmap(file, MMap::ReadOnly);
5046 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5047 springlist_ = sha1.Result();
5051 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
5052 [invocation setTarget:target];
5053 [invocation setSelector:selector];
5054 _assert(object == nil);
5056 [NSThread detachNewThreadSelector:@selector(_detachNewThreadInvocation:) toTarget:self withObject:invocation];
5059 - (void) repairWithSelector:(SEL)selector {
5061 detachNewThreadSelector:selector
5064 title:UCLocalize("REPAIRING")
5068 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
5069 CYAlertView *sheet([[[CYAlertView alloc]
5071 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
5072 defaultButtonIndex:0
5075 [sheet setMessage:error];
5076 [sheet yieldToPopupAlertAnimated:YES];
5080 - (void) startProgress {
5083 - (bool) isCancelling:(size_t)received {
5087 - (void) setConfigurationData:(NSString *)data {
5088 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
5090 if (!conffile_r(data)) {
5091 lprintf("E:invalid conffile\n");
5095 NSString *ofile = conffile_r[1];
5096 //NSString *nfile = conffile_r[2];
5098 UIAlertView *alert = [[[UIAlertView alloc]
5099 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
5100 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
5102 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
5104 UCLocalize("ACCEPT_NEW_COPY"),
5105 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
5109 [alert setContext:@"conffile"];
5113 - (void) setProgressTitle:(NSString *)title {
5114 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
5115 for (size_t i(0), e([words count]); i != e; ++i) {
5116 NSString *word([words objectAtIndex:i]);
5117 if (Package *package = [database_ packageWithName:word])
5118 [words replaceObjectAtIndex:i withObject:[package name]];
5121 [status_ setText:[words componentsJoinedByString:@" "]];
5124 - (void) setProgressPercent:(NSNumber *)percent {
5125 [progress_ setProgress:[percent floatValue]];
5128 - (void) addProgressOutput:(NSString *)output {
5129 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
5130 CGSize size = [output_ contentSize];
5131 CGPoint offset = [output_ contentOffset];
5132 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
5133 CGRect rect = {{0, size.height-1}, {size.width, 1}};
5134 [output_ scrollRectToVisible:rect animated:YES];
5138 - (BOOL) isRunning {
5145 /* Cell Content View {{{ */
5146 @protocol ContentDelegate
5147 - (void) drawContentRect:(CGRect)rect;
5150 @interface ContentView : UIView {
5151 _transient id<ContentDelegate> delegate_;
5156 @implementation ContentView
5158 - (id) initWithFrame:(CGRect)frame {
5159 if ((self = [super initWithFrame:frame]) != nil) {
5160 [self setNeedsDisplayOnBoundsChange:YES];
5164 - (void) setDelegate:(id<ContentDelegate>)delegate {
5165 delegate_ = delegate;
5168 - (void) drawRect:(CGRect)rect {
5169 [super drawRect:rect];
5170 [delegate_ drawContentRect:rect];
5175 /* Cydia TableView Cell {{{ */
5176 @interface CYTableViewCell : UITableViewCell {
5177 ContentView *content_;
5183 @implementation CYTableViewCell
5190 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5191 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5193 if (view == content_) {
5194 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5195 highlighted_ = highlighted;
5198 [super _updateHighlightColorsForView:view highlighted:highlighted];
5201 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5202 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5203 highlighted_ = selected;
5205 [super setSelected:selected animated:animated];
5206 [content_ setNeedsDisplay];
5212 /* Package Cell {{{ */
5213 @interface PackageCell : CYTableViewCell <
5218 NSString *description_;
5226 - (PackageCell *) init;
5227 - (void) setPackage:(Package *)package;
5229 - (void) drawContentRect:(CGRect)rect;
5233 @implementation PackageCell
5235 - (void) clearPackage {
5246 if (description_ != nil) {
5247 [description_ release];
5251 if (source_ != nil) {
5256 if (badge_ != nil) {
5261 if (placard_ != nil) {
5271 [self clearPackage];
5275 - (PackageCell *) init {
5276 CGRect frame(CGRectMake(0, 0, 320, 74));
5277 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5278 UIView *content([self contentView]);
5279 CGRect bounds([content bounds]);
5281 content_ = [[ContentView alloc] initWithFrame:bounds];
5282 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5283 [content addSubview:content_];
5285 [content_ setDelegate:self];
5286 [content_ setOpaque:YES];
5290 - (NSString *) accessibilityLabel {
5291 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5294 - (void) setPackage:(Package *)package {
5295 [self clearPackage];
5298 Source *source = [package source];
5300 icon_ = [[package icon] retain];
5301 name_ = [[package name] retain];
5304 description_ = [package longDescription];
5305 if (description_ == nil)
5306 description_ = [package shortDescription];
5307 if (description_ != nil)
5308 description_ = [description_ retain];
5310 commercial_ = [package isCommercial];
5312 package_ = [package retain];
5314 NSString *label = nil;
5315 bool trusted = false;
5317 if (source != nil) {
5318 label = [source label];
5319 trusted = [source trusted];
5320 } else if ([[package id] isEqualToString:@"firmware"])
5321 label = UCLocalize("APPLE");
5323 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5325 NSString *from(label);
5327 NSString *section = [package simpleSection];
5328 if (section != nil && ![section isEqualToString:label]) {
5329 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5330 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5333 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5334 source_ = [from retain];
5336 if (NSString *purpose = [package primaryPurpose])
5337 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5338 badge_ = [badge_ retain];
5343 if (NSString *mode = [package_ mode]) {
5344 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5345 color = RemovingColor_;
5346 //placard = @"removing";
5348 color = InstallingColor_;
5349 //placard = @"installing";
5352 // XXX: the removing/installing placards are not @2x
5355 color = [UIColor whiteColor];
5357 if ([package installed] != nil)
5358 placard = @"installed";
5363 [content_ setBackgroundColor:color];
5366 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5367 placard_ = [placard_ retain];
5369 [self setNeedsDisplay];
5370 [content_ setNeedsDisplay];
5373 - (void) drawContentRect:(CGRect)rect {
5374 bool highlighted(highlighted_);
5375 float width([self bounds].size.width);
5378 CGContextRef context(UIGraphicsGetCurrentContext());
5379 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5380 CGContextFillRect(context, rect);
5385 rect.size = [icon_ size];
5387 rect.size.width /= 2;
5388 rect.size.height /= 2;
5390 rect.origin.x = 25 - rect.size.width / 2;
5391 rect.origin.y = 25 - rect.size.height / 2;
5393 [icon_ drawInRect:rect];
5396 if (badge_ != nil) {
5398 rect.size = [badge_ size];
5400 rect.size.width /= 2;
5401 rect.size.height /= 2;
5403 rect.origin.x = 36 - rect.size.width / 2;
5404 rect.origin.y = 36 - rect.size.height / 2;
5406 [badge_ drawInRect:rect];
5413 UISetColor(commercial_ ? Purple_ : Black_);
5414 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5415 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5418 UISetColor(commercial_ ? Purplish_ : Gray_);
5419 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5421 if (placard_ != nil)
5422 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5427 /* Section Cell {{{ */
5428 @interface SectionCell : CYTableViewCell <
5440 - (void) setSection:(Section *)section editing:(BOOL)editing;
5444 @implementation SectionCell
5446 - (void) clearSection {
5447 if (basic_ != nil) {
5452 if (section_ != nil) {
5462 if (count_ != nil) {
5469 [self clearSection];
5475 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5476 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5477 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5478 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5479 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5481 UIView *content([self contentView]);
5482 CGRect bounds([content bounds]);
5484 content_ = [[ContentView alloc] initWithFrame:bounds];
5485 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5486 [content addSubview:content_];
5487 [content_ setBackgroundColor:[UIColor whiteColor]];
5489 [content_ setDelegate:self];
5493 - (void) onSwitch:(id)sender {
5494 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5495 if (metadata == nil) {
5496 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5497 [Sections_ setObject:metadata forKey:basic_];
5500 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5504 - (void) setSection:(Section *)section editing:(BOOL)editing {
5505 if (editing != editing_) {
5507 [switch_ removeFromSuperview];
5509 [self addSubview:switch_];
5513 [self clearSection];
5515 if (section == nil) {
5516 name_ = [UCLocalize("ALL_PACKAGES") retain];
5519 basic_ = [section name];
5521 basic_ = [basic_ retain];
5523 section_ = [section localized];
5524 if (section_ != nil)
5525 section_ = [section_ retain];
5527 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5528 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5531 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5534 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5535 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5537 [content_ setNeedsDisplay];
5540 - (void) setFrame:(CGRect)frame {
5541 [super setFrame:frame];
5543 CGRect rect([switch_ frame]);
5544 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5547 - (NSString *) accessibilityLabel {
5551 - (void) drawContentRect:(CGRect)rect {
5552 bool highlighted(highlighted_ && !editing_);
5554 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5559 float width(rect.size.width);
5565 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5567 CGSize size = [count_ sizeWithFont:Font14_];
5571 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5577 /* File Table {{{ */
5578 @interface FileTable : CYViewController <
5579 UITableViewDataSource,
5582 _transient Database *database_;
5585 NSMutableArray *files_;
5589 - (id) initWithDatabase:(Database *)database;
5590 - (void) setPackage:(Package *)package;
5594 @implementation FileTable
5597 [self releaseSubviews];
5606 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5607 return files_ == nil ? 0 : [files_ count];
5610 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5614 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5615 static NSString *reuseIdentifier = @"Cell";
5617 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5619 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5620 [cell setFont:[UIFont systemFontOfSize:16]];
5622 [cell setText:[files_ objectAtIndex:indexPath.row]];
5623 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5628 - (NSURL *) navigationURL {
5629 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5633 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5635 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5636 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5637 [list_ setRowHeight:24.0f];
5638 [list_ setDataSource:self];
5639 [list_ setDelegate:self];
5640 [[self view] addSubview:list_];
5643 - (void) viewDidLoad {
5644 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5647 - (void) releaseSubviews {
5652 - (id) initWithDatabase:(Database *)database {
5653 if ((self = [super init]) != nil) {
5654 database_ = database;
5656 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5660 - (void) setPackage:(Package *)package {
5661 if (package_ != nil) {
5662 [package_ autorelease];
5671 [files_ removeAllObjects];
5673 if (package != nil) {
5674 package_ = [package retain];
5675 name_ = [[package id] retain];
5677 if (NSArray *files = [package files])
5678 [files_ addObjectsFromArray:files];
5680 if ([files_ count] != 0) {
5681 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5682 [files_ removeObjectAtIndex:0];
5683 [files_ sortUsingSelector:@selector(compareByPath:)];
5685 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5686 [stack addObject:@"/"];
5688 for (int i(0), e([files_ count]); i != e; ++i) {
5689 NSString *file = [files_ objectAtIndex:i];
5690 while (![file hasPrefix:[stack lastObject]])
5691 [stack removeLastObject];
5692 NSString *directory = [stack lastObject];
5693 [stack addObject:[file stringByAppendingString:@"/"]];
5694 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5695 ([stack count] - 2) * 3, "",
5696 [file substringFromIndex:[directory length]]
5705 - (void) reloadData {
5708 [self setPackage:[database_ packageWithName:name_]];
5713 /* Package Controller {{{ */
5714 @interface CYPackageController : CYBrowserController <
5715 UIActionSheetDelegate
5717 _transient Database *database_;
5721 NSMutableArray *buttons_;
5722 UIBarButtonItem *button_;
5725 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5729 @implementation CYPackageController
5732 if (package_ != nil)
5745 - (NSURL *) navigationURL {
5746 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5749 /* XXX: this is not safe at all... localization of /fail/ */
5750 - (void) _clickButtonWithName:(NSString *)name {
5751 if ([name isEqualToString:UCLocalize("CLEAR")])
5752 [delegate_ clearPackage:package_];
5753 else if ([name isEqualToString:UCLocalize("INSTALL")])
5754 [delegate_ installPackage:package_];
5755 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5756 [delegate_ installPackage:package_];
5757 else if ([name isEqualToString:UCLocalize("REMOVE")])
5758 [delegate_ removePackage:package_];
5759 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5760 [delegate_ installPackage:package_];
5761 else _assert(false);
5764 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5765 NSString *context([sheet context]);
5767 if ([context isEqualToString:@"modify"]) {
5768 if (button != [sheet cancelButtonIndex]) {
5769 NSString *buttonName = [buttons_ objectAtIndex:button];
5770 [self _clickButtonWithName:buttonName];
5773 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5777 - (bool) _allowJavaScriptPanel {
5782 - (void) _customButtonClicked {
5783 int count([buttons_ count]);
5788 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5790 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5791 [buttons addObjectsFromArray:buttons_];
5793 UIActionSheet *sheet = [[[UIActionSheet alloc]
5796 cancelButtonTitle:nil
5797 destructiveButtonTitle:nil
5798 otherButtonTitles:nil
5801 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5803 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5804 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5806 [sheet setContext:@"modify"];
5808 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5812 // We don't want to allow non-commercial packages to do custom things to the install button,
5813 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5814 - (void) customButtonClicked {
5816 [super customButtonClicked];
5818 [self _customButtonClicked];
5821 - (void) reloadButtonClicked {
5822 // Don't reload a commerical package by tapping the loading button,
5823 // but if it's not an Install button, we should forward it on.
5824 if (![package_ uninstalled])
5825 [self _customButtonClicked];
5828 - (void) applyLoadingTitle {
5829 // Don't show "Loading" as the title. Ever.
5832 - (UIBarButtonItem *) rightButton {
5837 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5838 if ((self = [super init]) != nil) {
5839 database_ = database;
5840 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5841 name_ = [[NSString alloc] initWithString:name];
5842 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5846 - (void) reloadData {
5847 if (package_ != nil)
5848 [package_ autorelease];
5849 package_ = [database_ packageWithName:name_];
5851 [buttons_ removeAllObjects];
5853 if (package_ != nil) {
5856 package_ = [package_ retain];
5857 commercial_ = [package_ isCommercial];
5859 if ([package_ mode] != nil)
5860 [buttons_ addObject:UCLocalize("CLEAR")];
5861 if ([package_ source] == nil);
5862 else if ([package_ upgradableAndEssential:NO])
5863 [buttons_ addObject:UCLocalize("UPGRADE")];
5864 else if ([package_ uninstalled])
5865 [buttons_ addObject:UCLocalize("INSTALL")];
5867 [buttons_ addObject:UCLocalize("REINSTALL")];
5868 if (![package_ uninstalled])
5869 [buttons_ addObject:UCLocalize("REMOVE")];
5876 switch ([buttons_ count]) {
5877 case 0: title = nil; break;
5878 case 1: title = [buttons_ objectAtIndex:0]; break;
5879 default: title = UCLocalize("MODIFY"); break;
5882 button_ = [[UIBarButtonItem alloc]
5884 style:UIBarButtonItemStylePlain
5886 action:@selector(customButtonClicked)
5892 - (bool) isLoading {
5893 return commercial_ ? [super isLoading] : false;
5899 /* Package List Controller {{{ */
5900 @interface PackageListController : CYViewController <
5901 UITableViewDataSource,
5904 _transient Database *database_;
5906 NSMutableArray *packages_;
5907 NSMutableArray *sections_;
5909 NSMutableArray *index_;
5910 NSMutableDictionary *indices_;
5914 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5915 - (void) setDelegate:(id)delegate;
5916 - (void) resetCursor;
5920 @implementation PackageListController
5923 [packages_ release];
5924 [sections_ release];
5933 - (void) deselectWithAnimation:(BOOL)animated {
5934 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5937 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5938 CGRect base = [[self view] bounds];
5939 base.size.height -= bounds.size.height;
5940 base.origin = [list_ frame].origin;
5942 [UIView beginAnimations:nil context:NULL];
5943 [UIView setAnimationBeginsFromCurrentState:YES];
5944 [UIView setAnimationCurve:curve];
5945 [UIView setAnimationDuration:duration];
5946 [list_ setFrame:base];
5947 [UIView commitAnimations];
5950 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5951 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5954 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5955 [self resizeForKeyboardBounds:bounds duration:0];
5958 - (void) keyboardWillShow:(NSNotification *)notification {
5961 NSTimeInterval duration;
5962 UIViewAnimationCurve curve;
5963 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5964 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5965 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5966 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5968 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);
5969 UIViewController *base = self;
5970 while ([base parentViewController] != nil)
5971 base = [base parentViewController];
5972 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5973 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5975 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5978 - (void) keyboardWillHide:(NSNotification *)notification {
5979 NSTimeInterval duration;
5980 UIViewAnimationCurve curve;
5981 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5982 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5984 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5987 - (void) viewWillAppear:(BOOL)animated {
5988 [super viewWillAppear:animated];
5990 [self resizeForKeyboardBounds:CGRectZero];
5991 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5992 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5995 - (void) viewWillDisappear:(BOOL)animated {
5996 [super viewWillDisappear:animated];
5998 [self resizeForKeyboardBounds:CGRectZero];
5999 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6000 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6003 - (void) viewDidAppear:(BOOL)animated {
6004 [super viewDidAppear:animated];
6005 [self deselectWithAnimation:animated];
6008 - (void) didSelectPackage:(Package *)package {
6009 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6010 [view setDelegate:delegate_];
6011 [[self navigationController] pushViewController:view animated:YES];
6014 #if TryIndexedCollation
6015 + (BOOL) hasIndexedCollation {
6016 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6020 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6021 NSInteger count([sections_ count]);
6022 return count == 0 ? 1 : count;
6025 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6026 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6028 return [[sections_ objectAtIndex:section] name];
6031 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6032 if ([sections_ count] == 0)
6034 return [[sections_ objectAtIndex:section] count];
6037 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6038 @synchronized (database_) {
6039 if ([database_ era] != era_)
6042 Section *section([sections_ objectAtIndex:[path section]]);
6043 NSInteger row([path row]);
6044 Package *package([packages_ objectAtIndex:([section row] + row)]);
6045 return [[package retain] autorelease];
6048 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6049 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6051 cell = [[[PackageCell alloc] init] autorelease];
6052 [cell setPackage:[self packageAtIndexPath:path]];
6056 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6057 Package *package([self packageAtIndexPath:path]);
6058 package = [database_ packageWithName:[package id]];
6059 [self didSelectPackage:package];
6062 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6063 // XXX: is 20 the most optimal number here?
6064 return [packages_ count] > 20 ? index_ : nil;
6067 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6068 #if TryIndexedCollation
6069 if ([[self class] hasIndexedCollation]) {
6070 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6077 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6078 if ((self = [super init]) != nil) {
6079 database_ = database;
6080 title_ = [title copy];
6081 [[self navigationItem] setTitle:title_];
6083 #if TryIndexedCollation
6084 if ([[self class] hasIndexedCollation])
6085 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6088 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6090 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6092 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6093 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6095 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6096 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6097 [list_ setRowHeight:73];
6098 [[self view] addSubview:list_];
6100 [list_ setDataSource:self];
6101 [list_ setDelegate:self];
6105 - (void) setDelegate:(id)delegate {
6106 delegate_ = delegate;
6109 - (bool) hasPackage:(Package *)package {
6113 - (void) reloadData {
6116 era_ = [database_ era];
6117 NSArray *packages = [database_ packages];
6119 [packages_ removeAllObjects];
6120 [sections_ removeAllObjects];
6122 _profile(PackageTable$reloadData$Filter)
6123 for (Package *package in packages)
6124 if ([self hasPackage:package])
6125 [packages_ addObject:package];
6128 [indices_ removeAllObjects];
6130 Section *section = nil;
6132 #if TryIndexedCollation
6133 if ([[self class] hasIndexedCollation]) {
6134 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6135 NSArray *titles = [collation sectionIndexTitles];
6138 _profile(PackageTable$reloadData$Section)
6139 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6143 _profile(PackageTable$reloadData$Section$Package)
6144 package = [packages_ objectAtIndex:offset];
6145 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6148 while (secidx < index) {
6151 _profile(PackageTable$reloadData$Section$Allocate)
6152 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6155 _profile(PackageTable$reloadData$Section$Add)
6156 [sections_ addObject:section];
6160 [section addToCount];
6166 [index_ removeAllObjects];
6168 _profile(PackageTable$reloadData$Section)
6169 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6173 _profile(PackageTable$reloadData$Section$Package)
6174 package = [packages_ objectAtIndex:offset];
6175 index = [package index];
6178 if (section == nil || [section index] != index) {
6179 _profile(PackageTable$reloadData$Section$Allocate)
6180 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6183 [index_ addObject:[section name]];
6184 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6186 _profile(PackageTable$reloadData$Section$Add)
6187 [sections_ addObject:section];
6191 [section addToCount];
6196 _profile(PackageTable$reloadData$List)
6201 - (void) resetCursor {
6202 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6207 /* Filtered Package List Controller {{{ */
6208 @interface FilteredPackageListController : PackageListController {
6214 - (void) setObject:(id)object;
6215 - (void) setObject:(id)object forFilter:(SEL)filter;
6217 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6221 @implementation FilteredPackageListController
6229 - (void) setFilter:(SEL)filter {
6232 /* XXX: this is an unsafe optimization of doomy hell */
6233 Method method(class_getInstanceMethod([Package class], filter));
6234 _assert(method != NULL);
6235 imp_ = method_getImplementation(method);
6236 _assert(imp_ != NULL);
6239 - (void) setObject:(id)object {
6245 object_ = [object retain];
6248 - (void) setObject:(id)object forFilter:(SEL)filter {
6249 [self setFilter:filter];
6250 [self setObject:object];
6253 - (bool) hasPackage:(Package *)package {
6254 _profile(FilteredPackageTable$hasPackage)
6255 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6259 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6260 if ((self = [super initWithDatabase:database title:title]) != nil) {
6261 [self setFilter:filter];
6262 [self setObject:object];
6269 /* Home Controller {{{ */
6270 @interface HomeController : CYBrowserController {
6275 @implementation HomeController
6277 + (BOOL) shouldHideNavigationBar {
6281 - (NSURL *) navigationURL {
6282 return [NSURL URLWithString:@"cydia://home"];
6285 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6286 [super _setMoreHeaders:request];
6289 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6290 if (UniqueID_ != nil)
6291 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6293 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6296 - (void) aboutButtonClicked {
6297 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6299 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6300 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6301 [alert setCancelButtonIndex:0];
6304 @"Copyright (C) 2008-2011\n"
6305 "Jay Freeman (saurik)\n"
6306 "saurik@saurik.com\n"
6307 "http://www.saurik.com/"
6313 - (void) viewWillDisappear:(BOOL)animated {
6314 [super viewWillDisappear:animated];
6316 if ([[self class] shouldHideNavigationBar])
6317 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6320 - (void) viewWillAppear:(BOOL)animated {
6321 if (![self hasLoaded])
6322 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6324 [super viewWillAppear:animated];
6326 if ([[self class] shouldHideNavigationBar])
6327 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6330 - (void) viewDidLoad {
6331 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6332 initWithTitle:UCLocalize("ABOUT")
6333 style:UIBarButtonItemStylePlain
6335 action:@selector(aboutButtonClicked)
6341 /* Manage Controller {{{ */
6342 @interface ManageController : CYBrowserController {
6345 - (void) queueStatusDidChange;
6349 @implementation ManageController
6351 - (NSURL *) navigationURL {
6352 return [NSURL URLWithString:@"cydia://manage"];
6355 - (void) viewWillAppear:(BOOL)animated {
6356 if (![self hasLoaded])
6357 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6359 [super viewWillAppear:animated];
6362 - (void) viewDidLoad {
6363 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6364 initWithTitle:UCLocalize("SETTINGS")
6365 style:UIBarButtonItemStylePlain
6367 action:@selector(settingsButtonClicked)
6370 [self queueStatusDidChange];
6373 - (void) settingsButtonClicked {
6374 [delegate_ showSettings];
6378 - (void) queueButtonClicked {
6382 - (void) applyLoadingTitle {
6383 // Disable "Loading" title.
6386 - (void) applyRightButton {
6387 // Disable right button.
6391 - (void) queueStatusDidChange {
6393 if (!IsWildcat_ && Queuing_) {
6394 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6395 initWithTitle:UCLocalize("QUEUE")
6396 style:UIBarButtonItemStyleDone
6398 action:@selector(queueButtonClicked)
6401 [[self navigationItem] setRightBarButtonItem:nil];
6406 - (bool) isLoading {
6407 // Never show as loading.
6414 /* Refresh Bar {{{ */
6415 @interface RefreshBar : UINavigationBar {
6416 UIProgressIndicator *indicator_;
6417 UITextLabel *prompt_;
6418 UIProgressBar *progress_;
6419 UINavigationButton *cancel_;
6424 @implementation RefreshBar
6427 [indicator_ release];
6429 [progress_ release];
6434 - (void) positionViews {
6435 CGRect frame = [cancel_ frame];
6436 frame.size = [cancel_ sizeThatFits:frame.size];
6437 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6438 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6439 [cancel_ setFrame:frame];
6441 CGSize prgsize = {75, 100};
6443 [self frame].size.width - prgsize.width - 10,
6444 ([self frame].size.height - prgsize.height) / 2
6446 [progress_ setFrame:prgrect];
6448 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6449 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6450 CGRect indrect = {{indoffset, indoffset}, indsize};
6451 [indicator_ setFrame:indrect];
6453 CGSize prmsize = {215, indsize.height + 4};
6455 indoffset * 2 + indsize.width,
6456 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6458 [prompt_ setFrame:prmrect];
6461 - (void) setFrame:(CGRect)frame {
6462 [super setFrame:frame];
6463 [self positionViews];
6466 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6467 if ((self = [super initWithFrame:frame]) != nil) {
6468 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6470 [self setBarStyle:UIBarStyleBlack];
6472 UIBarStyle barstyle([self _barStyle:NO]);
6473 bool ugly(barstyle == UIBarStyleDefault);
6475 UIProgressIndicatorStyle style = ugly ?
6476 UIProgressIndicatorStyleMediumBrown :
6477 UIProgressIndicatorStyleMediumWhite;
6479 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6480 [indicator_ setStyle:style];
6481 [indicator_ startAnimation];
6482 [self addSubview:indicator_];
6484 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6485 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6486 [prompt_ setBackgroundColor:[UIColor clearColor]];
6487 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6488 [self addSubview:prompt_];
6490 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6491 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6492 [progress_ setStyle:0];
6493 [self addSubview:progress_];
6495 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6496 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6497 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6498 [cancel_ setBarStyle:barstyle];
6500 [self positionViews];
6505 [cancel_ removeFromSuperview];
6509 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6510 [progress_ setProgress:0];
6511 [self addSubview:cancel_];
6515 [cancel_ removeFromSuperview];
6518 - (void) setPrompt:(NSString *)prompt {
6519 [prompt_ setText:prompt];
6522 - (void) setProgress:(float)progress {
6523 [progress_ setProgress:progress];
6529 @class CYNavigationController;
6531 /* Cydia Tab Bar Controller {{{ */
6532 @interface CYTabBarController : UITabBarController <
6533 UITabBarControllerDelegate,
6536 _transient Database *database_;
6537 RefreshBar *refreshbar_;
6541 // XXX: ok, "updatedelegate_"?...
6542 _transient NSObject<CydiaDelegate> *updatedelegate_;
6545 UIViewController *remembered_;
6546 _transient UIViewController *transient_;
6549 - (NSArray *) navigationURLCollection;
6550 - (void) dropBar:(BOOL)animated;
6551 - (void) beginUpdate;
6552 - (void) raiseBar:(BOOL)animated;
6557 @implementation CYTabBarController
6559 - (void) setUnselectedViewController:(UIViewController *)transient {
6560 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6561 if (transient != nil) {
6562 if (transient_ == nil)
6563 remembered_ = [[controllers objectAtIndex:0] retain];
6564 transient_ = transient;
6565 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6566 [controllers replaceObjectAtIndex:0 withObject:transient_];
6567 [self setSelectedIndex:0];
6568 [self setViewControllers:controllers];
6569 [self concealTabBarSelection];
6570 } else if (remembered_ != nil) {
6571 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6572 transient_ = transient;
6573 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6574 [remembered_ release];
6576 [self setViewControllers:controllers];
6577 [self revealTabBarSelection];
6581 - (UIViewController *) unselectedViewController {
6585 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6586 if ([self unselectedViewController])
6587 [self setUnselectedViewController:nil];
6590 - (NSArray *) navigationURLCollection {
6591 NSMutableArray *items([NSMutableArray array]);
6593 // XXX: Should this deal with transient view controllers?
6594 for (id navigation in [self viewControllers]) {
6595 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6597 [items addObject:stack];
6603 - (void) reloadData {
6604 for (CYViewController *controller in [self viewControllers])
6605 [controller reloadData];
6607 [(CYNavigationController *)[self unselectedViewController] reloadData];
6611 [refreshbar_ release];
6612 [[NSNotificationCenter defaultCenter] removeObserver:self];
6617 - (id) initWithDatabase:(Database *)database {
6618 if ((self = [super init]) != nil) {
6619 database_ = database;
6620 [self setDelegate:self];
6622 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6623 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6625 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6629 - (void) setUpdate:(NSDate *)date {
6633 - (void) beginUpdate {
6634 [refreshbar_ start];
6637 [updatedelegate_ retainNetworkActivityIndicator];
6641 detachNewThreadSelector:@selector(performUpdate)
6647 - (void) performUpdate { _pooled
6649 status.setDelegate(self);
6650 [database_ updateWithStatus:status];
6653 performSelectorOnMainThread:@selector(completeUpdate)
6659 - (void) stopUpdateWithSelector:(SEL)selector {
6661 [updatedelegate_ releaseNetworkActivityIndicator];
6663 [self raiseBar:YES];
6666 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6669 - (void) completeUpdate {
6672 [self stopUpdateWithSelector:@selector(reloadData)];
6675 - (void) cancelUpdate {
6676 [self stopUpdateWithSelector:@selector(updateData)];
6679 - (void) cancelPressed {
6680 [self cancelUpdate];
6687 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6688 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6691 - (void) startProgress {
6694 - (bool) isCancelling:(size_t)received {
6698 - (void) setProgressTitle:(NSString *)title {
6699 [refreshbar_ setPrompt:title];
6702 - (void) setProgressPercent:(NSNumber *)percent {
6703 [refreshbar_ setProgress:[percent floatValue]];
6706 - (void) addProgressOutput:(NSString *)output {
6709 - (void) setUpdateDelegate:(id)delegate {
6710 updatedelegate_ = delegate;
6713 - (CGFloat) statusBarHeight {
6714 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6715 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6717 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6721 - (UIView *) transitionView {
6722 if ([self respondsToSelector:@selector(_transitionView)])
6723 return [self _transitionView];
6725 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6728 - (void) dropBar:(BOOL)animated {
6733 UIView *transition([self transitionView]);
6734 [[self view] addSubview:refreshbar_];
6736 CGRect barframe([refreshbar_ frame]);
6738 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6739 barframe.origin.y = [self statusBarHeight];
6741 barframe.origin.y = 0;
6743 [refreshbar_ setFrame:barframe];
6746 [UIView beginAnimations:nil context:NULL];
6748 CGRect viewframe = [transition frame];
6749 viewframe.origin.y += barframe.size.height;
6750 viewframe.size.height -= barframe.size.height;
6751 [transition setFrame:viewframe];
6754 [UIView commitAnimations];
6756 // Ensure bar has the proper width for our view, it might have changed
6757 barframe.size.width = viewframe.size.width;
6758 [refreshbar_ setFrame:barframe];
6760 // XXX: fix Apple's layout bug
6761 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6764 - (void) raiseBar:(BOOL)animated {
6769 UIView *transition([self transitionView]);
6770 [refreshbar_ removeFromSuperview];
6772 CGRect barframe([refreshbar_ frame]);
6775 [UIView beginAnimations:nil context:NULL];
6777 CGRect viewframe = [transition frame];
6778 viewframe.origin.y -= barframe.size.height;
6779 viewframe.size.height += barframe.size.height;
6780 [transition setFrame:viewframe];
6783 [UIView commitAnimations];
6785 // XXX: fix Apple's layout bug
6786 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6790 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6791 // XXX: fix Apple's layout bug
6792 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6796 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6797 bool dropped(dropped_);
6802 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6807 // XXX: fix Apple's layout bug
6808 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6811 - (void) statusBarFrameChanged:(NSNotification *)notification {
6820 /* Cydia Navigation Controller {{{ */
6821 @interface CYNavigationController : UINavigationController {
6822 _transient Database *database_;
6823 _transient id<UINavigationControllerDelegate> delegate_;
6826 - (NSArray *) navigationURLCollection;
6827 - (id) initWithDatabase:(Database *)database;
6828 - (void) reloadData;
6833 @implementation CYNavigationController
6835 - (NSArray *) navigationURLCollection {
6836 NSMutableArray *stack([NSMutableArray array]);
6838 for (CYViewController *controller in [self viewControllers]) {
6839 NSString *url = [[controller navigationURL] absoluteString];
6841 [stack addObject:url];
6847 - (void) reloadData {
6848 for (CYViewController *page in [self viewControllers]) {
6849 // Only reload controllers that have already loaded.
6850 // This prevents a page from accidentally loading too
6851 // early if it hasn't been shown on the screen yet.
6852 if ([page hasLoaded])
6857 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6858 delegate_ = delegate;
6861 - (id) initWithDatabase:(Database *)database {
6862 if ((self = [super init]) != nil) {
6863 database_ = database;
6870 /* Cydia:// Protocol {{{ */
6871 @interface CydiaURLProtocol : NSURLProtocol {
6876 @implementation CydiaURLProtocol
6878 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6879 NSURL *url([request URL]);
6882 NSString *scheme([[url scheme] lowercaseString]);
6883 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6888 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6892 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6893 id<NSURLProtocolClient> client([self client]);
6895 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6897 NSData *data(UIImagePNGRepresentation(icon));
6899 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6900 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6901 [client URLProtocol:self didLoadData:data];
6902 [client URLProtocolDidFinishLoading:self];
6906 - (void) startLoading {
6907 id<NSURLProtocolClient> client([self client]);
6908 NSURLRequest *request([self request]);
6910 NSURL *url([request URL]);
6911 NSString *href([url absoluteString]);
6913 NSString *path([href substringFromIndex:8]);
6914 NSRange slash([path rangeOfString:@"/"]);
6917 if (slash.location == NSNotFound) {
6921 command = [path substringToIndex:slash.location];
6922 path = [path substringFromIndex:(slash.location + 1)];
6925 Database *database([Database sharedInstance]);
6927 if ([command isEqualToString:@"package-icon"]) {
6930 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6931 Package *package([database packageWithName:path]);
6934 UIImage *icon([package icon]);
6935 [self _returnPNGWithImage:icon forRequest:request];
6936 } else if ([command isEqualToString:@"source-icon"]) {
6939 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6940 NSString *source(Simplify(path));
6941 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6943 icon = [UIImage applicationImageNamed:@"unknown.png"];
6944 [self _returnPNGWithImage:icon forRequest:request];
6945 } else if ([command isEqualToString:@"uikit-image"]) {
6948 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6949 UIImage *icon(_UIImageWithName(path));
6950 [self _returnPNGWithImage:icon forRequest:request];
6951 } else if ([command isEqualToString:@"section-icon"]) {
6954 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6955 NSString *section(Simplify(path));
6956 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6958 icon = [UIImage applicationImageNamed:@"unknown.png"];
6959 [self _returnPNGWithImage:icon forRequest:request];
6961 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6965 - (void) stopLoading {
6971 /* Section Controller {{{ */
6972 @interface SectionController : FilteredPackageListController {
6976 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6980 @implementation SectionController
6982 - (NSURL *) navigationURL {
6983 NSString *name = section_;
6987 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6990 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6993 title = UCLocalize("ALL_PACKAGES");
6994 else if (![name isEqual:@""])
6995 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6997 title = UCLocalize("NO_SECTION");
6999 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7006 /* Sections Controller {{{ */
7007 @interface SectionsController : CYViewController <
7008 UITableViewDataSource,
7011 _transient Database *database_;
7012 NSMutableArray *sections_;
7013 NSMutableArray *filtered_;
7018 - (id) initWithDatabase:(Database *)database;
7019 - (void) editButtonClicked;
7023 @implementation SectionsController
7026 [self releaseSubviews];
7027 [sections_ release];
7028 [filtered_ release];
7033 - (NSURL *) navigationURL {
7034 return [NSURL URLWithString:@"cydia://sections"];
7037 - (void) updateNavigationItem {
7038 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7039 if ([sections_ count] == 0) {
7040 [[self navigationItem] setRightBarButtonItem:nil];
7042 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7043 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7045 action:@selector(editButtonClicked)
7046 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7050 - (BOOL) isEditing {
7054 - (void) setEditing:(BOOL)editing {
7055 if ((editing_ = editing))
7058 [delegate_ updateData];
7060 [self updateNavigationItem];
7063 - (void) viewDidAppear:(BOOL)animated {
7064 [super viewDidAppear:animated];
7065 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7068 - (void) viewWillDisappear:(BOOL)animated {
7069 [super viewWillDisappear:animated];
7070 if (editing_) [self setEditing:NO];
7073 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7074 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7078 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7079 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7082 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7086 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7087 static NSString *reuseIdentifier = @"SectionCell";
7089 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7091 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7093 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7098 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7102 Section *section = [self sectionAtIndexPath:indexPath];
7104 SectionController *controller = [[[SectionController alloc]
7105 initWithDatabase:database_
7106 section:[section name]
7108 [controller setDelegate:delegate_];
7110 [[self navigationController] pushViewController:controller animated:YES];
7114 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7116 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7117 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7118 [list_ setRowHeight:45.0f];
7119 [list_ setDataSource:self];
7120 [list_ setDelegate:self];
7121 [[self view] addSubview:list_];
7124 - (void) viewDidLoad {
7125 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7128 - (void) releaseSubviews {
7133 - (id) initWithDatabase:(Database *)database {
7134 if ((self = [super init]) != nil) {
7135 database_ = database;
7137 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7138 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7142 - (void) reloadData {
7145 NSArray *packages = [database_ packages];
7147 [sections_ removeAllObjects];
7148 [filtered_ removeAllObjects];
7150 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7153 for (Package *package in packages) {
7154 NSString *name([package section]);
7155 NSString *key(name == nil ? @"" : name);
7159 _profile(SectionsView$reloadData$Section)
7160 section = [sections objectForKey:key];
7161 if (section == nil) {
7162 _profile(SectionsView$reloadData$Section$Allocate)
7163 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7164 [sections setObject:section forKey:key];
7169 [section addToCount];
7171 _profile(SectionsView$reloadData$Filter)
7172 if (![package valid] || ![package visible])
7180 [sections_ addObjectsFromArray:[sections allValues]];
7182 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7184 for (Section *section in sections_) {
7185 size_t count([section row]);
7189 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7190 [section setCount:count];
7191 [filtered_ addObject:section];
7194 [self updateNavigationItem];
7199 - (void) editButtonClicked {
7200 [self setEditing:(!editing_)];
7206 /* Changes Controller {{{ */
7207 @interface ChangesController : CYViewController <
7208 UITableViewDataSource,
7211 _transient Database *database_;
7213 CFMutableArrayRef packages_;
7214 NSMutableArray *sections_;
7217 BOOL hasSentFirstLoad_;
7220 - (id) initWithDatabase:(Database *)database;
7224 @implementation ChangesController
7227 [self releaseSubviews];
7228 CFRelease(packages_);
7229 [sections_ release];
7234 - (NSURL *) navigationURL {
7235 return [NSURL URLWithString:@"cydia://changes"];
7238 - (void) viewWillAppear:(BOOL)animated {
7239 // Loads after it appears, so don't load beforehand.
7241 [super viewWillAppear:animated];
7244 - (void) viewDidAppear:(BOOL)animated {
7245 [super viewDidAppear:animated];
7247 if (!hasSentFirstLoad_) {
7248 hasSentFirstLoad_ = YES;
7249 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7251 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7255 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7256 NSInteger count([sections_ count]);
7257 return count == 0 ? 1 : count;
7260 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7261 if ([sections_ count] == 0)
7263 return [[sections_ objectAtIndex:section] name];
7266 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7267 if ([sections_ count] == 0)
7269 return [[sections_ objectAtIndex:section] count];
7272 - (Package *) packageAtIndex:(NSUInteger)index {
7273 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7276 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7277 @synchronized (database_) {
7278 if ([database_ era] != era_)
7281 NSUInteger sectionIndex([path section]);
7282 if (sectionIndex >= [sections_ count])
7284 Section *section([sections_ objectAtIndex:sectionIndex]);
7285 NSInteger row([path row]);
7286 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7289 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7290 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7292 cell = [[[PackageCell alloc] init] autorelease];
7293 [cell setPackage:[self packageAtIndexPath:path]];
7297 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7298 Package *package([self packageAtIndexPath:path]);
7299 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7300 [view setDelegate:delegate_];
7301 [[self navigationController] pushViewController:view animated:YES];
7305 - (void) refreshButtonClicked {
7306 [delegate_ beginUpdate];
7307 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7310 - (void) upgradeButtonClicked {
7311 [delegate_ distUpgrade];
7315 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7317 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7318 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7319 [list_ setRowHeight:73];
7320 [list_ setDataSource:self];
7321 [list_ setDelegate:self];
7322 [[self view] addSubview:list_];
7325 - (void) viewDidLoad {
7326 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7329 - (void) releaseSubviews {
7334 - (id) initWithDatabase:(Database *)database {
7335 if ((self = [super init]) != nil) {
7336 database_ = database;
7338 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7339 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7343 // this mostly works because reloadData (below) is @synchronized (database_)
7344 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7345 - (void) _reloadPackages:(NSArray *)packages {
7346 CFRelease(packages_);
7347 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7350 _profile(ChangesController$_reloadPackages$Filter)
7351 for (Package *package in packages)
7352 if ([package upgradableAndEssential:YES] || [package visible])
7353 CFArrayAppendValue(packages_, package);
7356 _profile(ChangesController$_reloadPackages$radixSort)
7357 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7362 - (void) reloadData {
7363 @synchronized (database_) {
7364 era_ = [database_ era];
7365 NSArray *packages = [database_ packages];
7367 [sections_ removeAllObjects];
7370 UIProgressHUD *hud([delegate_ addProgressHUD]);
7371 [hud setText:UCLocalize("LOADING")];
7372 //NSLog(@"HUD:%@::%@", delegate_, hud);
7373 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7374 [delegate_ removeProgressHUD:hud];
7376 [self _reloadPackages:packages];
7379 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7380 Section *ignored = nil;
7381 Section *section = nil;
7385 bool unseens = false;
7387 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7389 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7390 Package *package = [self packageAtIndex:offset];
7392 BOOL uae = [package upgradableAndEssential:YES];
7396 time_t seen([package seen]);
7398 if (section == nil || last != seen) {
7402 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7405 _profile(ChangesController$reloadData$Allocate)
7406 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7407 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7408 [sections_ addObject:section];
7412 [section addToCount];
7413 } else if ([package ignored]) {
7414 if (ignored == nil) {
7415 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7417 [ignored addToCount];
7420 [upgradable addToCount];
7425 CFRelease(formatter);
7428 Section *last = [sections_ lastObject];
7429 size_t count = [last count];
7430 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7431 [sections_ removeLastObject];
7434 if ([ignored count] != 0)
7435 [sections_ insertObject:ignored atIndex:0];
7437 [sections_ insertObject:upgradable atIndex:0];
7442 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7443 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7444 style:UIBarButtonItemStylePlain
7446 action:@selector(upgradeButtonClicked)
7449 if (![delegate_ updating])
7450 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7451 initWithTitle:UCLocalize("REFRESH")
7452 style:UIBarButtonItemStylePlain
7454 action:@selector(refreshButtonClicked)
7462 /* Search Controller {{{ */
7463 @interface SearchController : FilteredPackageListController <
7466 UISearchBar *search_;
7470 - (id) initWithDatabase:(Database *)database;
7471 - (void) setSearchTerm:(NSString *)term;
7472 - (void) reloadData;
7476 @implementation SearchController
7483 - (NSURL *) navigationURL {
7484 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7485 return [NSURL URLWithString:@"cydia://search"];
7487 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7490 - (void) setSearchTerm:(NSString *)searchTerm {
7491 [search_ setText:searchTerm];
7495 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7496 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7497 [search_ resignFirstResponder];
7501 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7502 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7506 - (id) initWithDatabase:(Database *)database {
7507 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7508 search_ = [[UISearchBar alloc] init];
7512 - (void) viewDidAppear:(BOOL)animated {
7513 [super viewDidAppear:animated];
7515 if (!searchloaded_) {
7516 searchloaded_ = YES;
7517 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7518 [search_ layoutSubviews];
7519 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7521 UITextField *textField;
7522 if ([search_ respondsToSelector:@selector(searchField)])
7523 textField = [search_ searchField];
7525 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7527 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7528 [search_ setDelegate:self];
7529 [textField setEnablesReturnKeyAutomatically:NO];
7530 [[self navigationItem] setTitleView:textField];
7534 - (void) reloadData {
7535 [self setObject:[search_ text]];
7540 - (void) didSelectPackage:(Package *)package {
7541 [search_ resignFirstResponder];
7542 [super didSelectPackage:package];
7547 /* Package Settings Controller {{{ */
7548 @interface PackageSettingsController : CYViewController <
7549 UITableViewDataSource,
7552 _transient Database *database_;
7555 UITableView *table_;
7556 UISwitch *subscribedSwitch_;
7557 UISwitch *ignoredSwitch_;
7558 UITableViewCell *subscribedCell_;
7559 UITableViewCell *ignoredCell_;
7562 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7566 @implementation PackageSettingsController
7569 [self releaseSubviews];
7576 - (NSURL *) navigationURL {
7577 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7580 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7581 if (package_ == nil)
7584 if ([package_ installed] == nil)
7590 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7591 if (package_ == nil)
7594 // both sections contain just one item right now.
7598 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7602 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7604 return UCLocalize("SHOW_ALL_CHANGES_EX");
7606 return UCLocalize("IGNORE_UPGRADES_EX");
7609 - (void) onSubscribed:(id)control {
7610 bool value([control isOn]);
7611 if (package_ == nil)
7613 if ([package_ setSubscribed:value])
7614 [delegate_ updateData];
7617 - (void) _updateIgnored {
7618 const char *package([name_ UTF8String]);
7619 bool on([ignoredSwitch_ isOn]);
7621 pid_t pid(ExecFork());
7623 FILE *dpkg(popen("dpkg --set-selections", "w"));
7624 fwrite(package, strlen(package), 1, dpkg);
7627 fwrite(" hold\n", 6, 1, dpkg);
7629 fwrite(" install\n", 9, 1, dpkg);
7639 int result(waitpid(pid, &status, 0));
7642 _assert(result == pid);
7648 - (void) onIgnored:(id)control {
7649 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7650 [invocation setTarget:self];
7651 [invocation setSelector:@selector(_updateIgnored)];
7653 [delegate_ reloadDataWithInvocation:invocation];
7656 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7657 if (package_ == nil)
7660 switch ([indexPath section]) {
7661 case 0: return subscribedCell_;
7662 case 1: return ignoredCell_;
7671 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7673 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7674 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7675 [table_ setDataSource:self];
7676 [table_ setDelegate:self];
7677 [[self view] addSubview:table_];
7679 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7680 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7681 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7683 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7684 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7685 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7687 subscribedCell_ = [[UITableViewCell alloc] init];
7688 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7689 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7690 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7692 ignoredCell_ = [[UITableViewCell alloc] init];
7693 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7694 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7695 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7698 - (void) viewDidLoad {
7699 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7702 - (void) releaseSubviews {
7703 [ignoredCell_ release];
7706 [subscribedCell_ release];
7707 subscribedCell_ = nil;
7712 [ignoredSwitch_ release];
7713 ignoredSwitch_ = nil;
7715 [subscribedSwitch_ release];
7716 subscribedSwitch_ = nil;
7719 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7720 if ((self = [super init]) != nil) {
7721 database_ = database;
7722 name_ = [package retain];
7726 - (void) reloadData {
7729 if (package_ != nil)
7730 [package_ autorelease];
7731 package_ = [database_ packageWithName:name_];
7733 if (package_ != nil) {
7734 package_ = [package_ retain];
7735 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7736 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7737 } // XXX: what now, G?
7739 [table_ reloadData];
7745 /* Installed Controller {{{ */
7746 @interface InstalledController : FilteredPackageListController {
7750 - (id) initWithDatabase:(Database *)database;
7752 - (void) updateRoleButton;
7753 - (void) queueStatusDidChange;
7757 @implementation InstalledController
7763 - (NSURL *) navigationURL {
7764 return [NSURL URLWithString:@"cydia://installed"];
7767 - (id) initWithDatabase:(Database *)database {
7768 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7769 [self updateRoleButton];
7770 [self queueStatusDidChange];
7775 - (void) queueButtonClicked {
7780 - (void) queueStatusDidChange {
7784 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7785 initWithTitle:UCLocalize("QUEUE")
7786 style:UIBarButtonItemStyleDone
7788 action:@selector(queueButtonClicked)
7791 [[self navigationItem] setLeftBarButtonItem:nil];
7797 - (void) updateRoleButton {
7798 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7799 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7800 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7801 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7803 action:@selector(roleButtonClicked)
7807 - (void) roleButtonClicked {
7808 [self setObject:[NSNumber numberWithBool:expert_]];
7812 [self updateRoleButton];
7818 /* Source Cell {{{ */
7819 @interface SourceCell : CYTableViewCell <
7827 - (void) setSource:(Source *)source;
7831 @implementation SourceCell
7833 - (void) clearSource {
7843 - (void) setSource:(Source *)source {
7847 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7849 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7850 icon_ = [icon_ retain];
7852 origin_ = [[source name] retain];
7853 label_ = [[source uri] retain];
7855 [content_ setNeedsDisplay];
7863 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7864 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7865 UIView *content([self contentView]);
7866 CGRect bounds([content bounds]);
7868 content_ = [[ContentView alloc] initWithFrame:bounds];
7869 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7870 [content_ setBackgroundColor:[UIColor whiteColor]];
7871 [content addSubview:content_];
7873 [content_ setDelegate:self];
7874 [content_ setOpaque:YES];
7878 - (NSString *) accessibilityLabel {
7882 - (void) drawContentRect:(CGRect)rect {
7883 bool highlighted(highlighted_);
7884 float width(rect.size.width);
7887 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7894 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7898 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7903 /* Source Controller {{{ */
7904 @interface SourceController : FilteredPackageListController {
7905 _transient Source *source_;
7909 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7913 @implementation SourceController
7915 - (NSURL *) navigationURL {
7916 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7919 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7920 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7922 key_ = [[source key] retain];
7926 - (void) reloadData {
7927 source_ = [database_ sourceWithKey:key_];
7929 key_ = [[source_ key] retain];
7930 [self setObject:source_];
7931 [[self navigationItem] setTitle:[source_ label]];
7938 /* Sources Controller {{{ */
7939 @interface SourcesController : CYViewController <
7940 UITableViewDataSource,
7943 _transient Database *database_;
7945 NSMutableArray *sources_;
7949 UIProgressHUD *hud_;
7952 //NSURLConnection *installer_;
7953 NSURLConnection *trivial_;
7954 NSURLConnection *trivial_bz2_;
7955 NSURLConnection *trivial_gz_;
7956 //NSURLConnection *automatic_;
7961 - (id) initWithDatabase:(Database *)database;
7962 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7966 @implementation SourcesController
7968 - (void) _releaseConnection:(NSURLConnection *)connection {
7969 if (connection != nil) {
7970 [connection cancel];
7971 //[connection setDelegate:nil];
7972 [connection release];
7977 [self releaseSubviews];
7983 //[self _releaseConnection:installer_];
7984 [self _releaseConnection:trivial_];
7985 [self _releaseConnection:trivial_gz_];
7986 [self _releaseConnection:trivial_bz2_];
7987 //[self _releaseConnection:automatic_];
7993 - (NSURL *) navigationURL {
7994 return [NSURL URLWithString:@"cydia://sources"];
7997 - (void) viewDidAppear:(BOOL)animated {
7998 [super viewDidAppear:animated];
7999 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8002 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8003 return offset_ == 0 ? 1 : 2;
8006 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8007 switch (section + (offset_ == 0 ? 1 : 0)) {
8008 case 0: return UCLocalize("ENTERED_BY_USER");
8009 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8015 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8016 int count = [sources_ count];
8018 case 0: return (offset_ == 0 ? count : offset_);
8019 case 1: return count - offset_;
8025 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8027 switch (indexPath.section) {
8028 case 0: idx = indexPath.row; break;
8029 case 1: idx = indexPath.row + offset_; break;
8033 return [sources_ objectAtIndex:idx];
8036 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8037 static NSString *cellIdentifier = @"SourceCell";
8039 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8040 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8041 [cell setSource:[self sourceAtIndexPath:indexPath]];
8042 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8047 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8048 Source *source = [self sourceAtIndexPath:indexPath];
8050 SourceController *controller = [[[SourceController alloc]
8051 initWithDatabase:database_
8055 [controller setDelegate:delegate_];
8057 [[self navigationController] pushViewController:controller animated:YES];
8060 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8061 Source *source = [self sourceAtIndexPath:indexPath];
8062 return [source record] != nil;
8065 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8066 Source *source = [self sourceAtIndexPath:indexPath];
8067 [Sources_ removeObjectForKey:[source key]];
8068 [delegate_ syncData];
8072 [delegate_ addTrivialSource:href_];
8073 [delegate_ syncData];
8076 - (NSString *) getWarning {
8077 NSString *href(href_);
8078 NSRange colon([href rangeOfString:@"://"]);
8079 if (colon.location != NSNotFound)
8080 href = [href substringFromIndex:(colon.location + 3)];
8081 href = [href stringByAddingPercentEscapes];
8082 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8083 href = [href stringByCachingURLWithCurrentCDN];
8085 NSURL *url([NSURL URLWithString:href]);
8087 NSStringEncoding encoding;
8088 NSError *error(nil);
8090 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8091 return [warning length] == 0 ? nil : warning;
8095 - (void) _endConnection:(NSURLConnection *)connection {
8096 // XXX: the memory management in this method is horribly awkward
8098 NSURLConnection **field = NULL;
8099 if (connection == trivial_)
8101 else if (connection == trivial_bz2_)
8102 field = &trivial_bz2_;
8103 else if (connection == trivial_gz_)
8104 field = &trivial_gz_;
8105 _assert(field != NULL);
8106 [connection release];
8111 trivial_bz2_ == nil &&
8117 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8120 UIAlertView *alert = [[[UIAlertView alloc]
8121 initWithTitle:UCLocalize("SOURCE_WARNING")
8124 cancelButtonTitle:UCLocalize("CANCEL")
8126 UCLocalize("ADD_ANYWAY"),
8130 [alert setContext:@"warning"];
8131 [alert setNumberOfRows:1];
8135 } else if (error_ != nil) {
8136 UIAlertView *alert = [[[UIAlertView alloc]
8137 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8138 message:[error_ localizedDescription]
8140 cancelButtonTitle:UCLocalize("OK")
8141 otherButtonTitles:nil
8144 [alert setContext:@"urlerror"];
8147 UIAlertView *alert = [[[UIAlertView alloc]
8148 initWithTitle:UCLocalize("NOT_REPOSITORY")
8149 message:UCLocalize("NOT_REPOSITORY_EX")
8151 cancelButtonTitle:UCLocalize("OK")
8152 otherButtonTitles:nil
8155 [alert setContext:@"trivial"];
8159 [delegate_ setStatusBarShowsProgress:NO];
8160 [delegate_ removeProgressHUD:hud_];
8170 if (error_ != nil) {
8177 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8178 switch ([response statusCode]) {
8184 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8185 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8187 error_ = [error retain];
8188 [self _endConnection:connection];
8191 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8192 [self _endConnection:connection];
8195 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8196 NSMutableURLRequest *request = [NSMutableURLRequest
8197 requestWithURL:[NSURL URLWithString:href]
8198 cachePolicy:NSURLRequestUseProtocolCachePolicy
8199 timeoutInterval:120.0
8202 [request setHTTPMethod:method];
8204 if (Machine_ != NULL)
8205 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8206 if (UniqueID_ != nil)
8207 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8209 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8211 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8214 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8215 NSString *context([alert context]);
8217 if ([context isEqualToString:@"source"]) {
8220 NSString *href = [[alert textField] text];
8222 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8224 if (![href hasSuffix:@"/"])
8225 href_ = [href stringByAppendingString:@"/"];
8228 href_ = [href_ retain];
8230 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8231 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8232 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8233 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8237 // XXX: this is stupid
8238 hud_ = [[delegate_ addProgressHUD] retain];
8239 [hud_ setText:UCLocalize("VERIFYING_URL")];
8248 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8249 } else if ([context isEqualToString:@"trivial"])
8250 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8251 else if ([context isEqualToString:@"urlerror"])
8252 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8253 else if ([context isEqualToString:@"warning"]) {
8268 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8273 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8275 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8276 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8277 [list_ setRowHeight:56];
8278 [list_ setDataSource:self];
8279 [list_ setDelegate:self];
8280 [[self view] addSubview:list_];
8283 - (void) viewDidLoad {
8284 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8285 [self updateButtonsForEditingStatus:NO animated:NO];
8288 - (void) releaseSubviews {
8293 - (id) initWithDatabase:(Database *)database {
8294 if ((self = [super init]) != nil) {
8295 database_ = database;
8296 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8300 - (void) reloadData {
8304 if (!list.ReadMainList())
8307 [sources_ removeAllObjects];
8308 [sources_ addObjectsFromArray:[database_ sources]];
8310 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8313 int count([sources_ count]);
8315 for (int i = 0; i != count; i++) {
8316 if ([[sources_ objectAtIndex:i] record] == nil)
8321 [list_ setEditing:NO];
8322 [self updateButtonsForEditingStatus:NO animated:NO];
8326 - (void) showAddSourcePrompt {
8327 UIAlertView *alert = [[[UIAlertView alloc]
8328 initWithTitle:UCLocalize("ENTER_APT_URL")
8331 cancelButtonTitle:UCLocalize("CANCEL")
8333 UCLocalize("ADD_SOURCE"),
8337 [alert setContext:@"source"];
8338 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8340 [alert setNumberOfRows:1];
8341 [alert addTextFieldWithValue:@"http://" label:@""];
8343 UITextInputTraits *traits = [[alert textField] textInputTraits];
8344 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8345 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8346 [traits setKeyboardType:UIKeyboardTypeURL];
8347 // XXX: UIReturnKeyDone
8348 [traits setReturnKeyType:UIReturnKeyNext];
8353 - (void) addButtonClicked {
8354 [self showAddSourcePrompt];
8357 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8358 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8359 initWithTitle:UCLocalize("ADD")
8360 style:UIBarButtonItemStylePlain
8362 action:@selector(addButtonClicked)
8363 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8365 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8366 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8367 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8369 action:@selector(editButtonClicked)
8370 ] autorelease] animated:animated];
8372 if (IsWildcat_ && !editing)
8373 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8374 initWithTitle:UCLocalize("SETTINGS")
8375 style:UIBarButtonItemStylePlain
8377 action:@selector(settingsButtonClicked)
8381 - (void) settingsButtonClicked {
8382 [delegate_ showSettings];
8385 - (void) editButtonClicked {
8386 [list_ setEditing:![list_ isEditing] animated:YES];
8388 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8394 /* Settings Controller {{{ */
8395 @interface SettingsController : CYViewController <
8396 UITableViewDataSource,
8399 _transient Database *database_;
8400 // XXX: ok, "roledelegate_"?...
8401 _transient id roledelegate_;
8402 UITableView *table_;
8403 UISegmentedControl *segment_;
8407 - (void) showDoneButton;
8408 - (void) resizeSegmentedControl;
8412 @implementation SettingsController
8415 [self releaseSubviews];
8421 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8423 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8424 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8425 [table_ setDelegate:self];
8426 [table_ setDataSource:self];
8427 [[self view] addSubview:table_];
8429 NSArray *items = [NSArray arrayWithObjects:
8431 UCLocalize("HACKER"),
8432 UCLocalize("DEVELOPER"),
8434 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8435 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8436 [container_ addSubview:segment_];
8439 - (void) viewDidLoad {
8440 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8443 if ([Role_ isEqualToString:@"User"]) index = 0;
8444 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8445 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8447 [segment_ setSelectedSegmentIndex:index];
8448 [self showDoneButton];
8451 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8452 [self resizeSegmentedControl];
8455 - (void) releaseSubviews {
8462 [container_ release];
8466 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8467 if ((self = [super init]) != nil) {
8468 database_ = database;
8469 roledelegate_ = delegate;
8473 - (void) resizeSegmentedControl {
8474 CGFloat width = [[self view] frame].size.width;
8475 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8478 - (void) viewWillAppear:(BOOL)animated {
8479 [super viewWillAppear:animated];
8481 [self resizeSegmentedControl];
8484 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8485 [self resizeSegmentedControl];
8488 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8489 [self resizeSegmentedControl];
8493 NSString *role(nil);
8495 switch ([segment_ selectedSegmentIndex]) {
8496 case 0: role = @"User"; break;
8497 case 1: role = @"Hacker"; break;
8498 case 2: role = @"Developer"; break;
8503 if (![role isEqualToString:Role_]) {
8504 bool rolling(Role_ == nil);
8507 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8511 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8515 [roledelegate_ loadData];
8517 [roledelegate_ updateData];
8521 - (void) segmentChanged:(UISegmentedControl *)control {
8522 [self showDoneButton];
8525 - (void) saveAndClose {
8528 [[self navigationItem] setRightBarButtonItem:nil];
8529 [[self navigationController] dismissModalViewControllerAnimated:YES];
8532 - (void) doneButtonClicked {
8533 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8534 [spinner startAnimating];
8535 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8536 [[self navigationItem] setRightBarButtonItem:spinItem];
8538 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8541 - (void) showDoneButton {
8542 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8543 initWithTitle:UCLocalize("DONE")
8544 style:UIBarButtonItemStyleDone
8546 action:@selector(doneButtonClicked)
8547 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8550 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8551 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8555 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8559 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8560 return nil; // This method is required by the protocol.
8563 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8565 return UCLocalize("ROLE_EX");
8567 return [NSString stringWithFormat:
8568 @"%@: %@\n%@: %@\n%@: %@",
8569 UCLocalize("USER"), UCLocalize("USER_EX"),
8570 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8571 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8576 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8577 return section == 3 ? 44.0f : 0;
8580 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8581 return section == 3 ? container_ : nil;
8584 - (void) reloadData {
8586 [table_ reloadData];
8591 /* Stash Controller {{{ */
8592 @interface StashController : CYViewController {
8593 UIActivityIndicatorView *spinner_;
8600 @implementation StashController
8603 [self releaseSubviews];
8609 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8610 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8612 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8613 CGRect spinrect = [spinner_ frame];
8614 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8615 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8616 [spinner_ setFrame:spinrect];
8617 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8618 [[self view] addSubview:spinner_];
8619 [spinner_ startAnimating];
8622 captrect.size.width = [[self view] frame].size.width;
8623 captrect.size.height = 40.0f;
8624 captrect.origin.x = 0;
8625 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8626 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8627 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8628 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8629 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8630 [caption_ setTextColor:[UIColor whiteColor]];
8631 [caption_ setBackgroundColor:[UIColor clearColor]];
8632 [caption_ setShadowColor:[UIColor blackColor]];
8633 [caption_ setTextAlignment:UITextAlignmentCenter];
8634 [[self view] addSubview:caption_];
8637 statusrect.size.width = [[self view] frame].size.width;
8638 statusrect.size.height = 30.0f;
8639 statusrect.origin.x = 0;
8640 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8641 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8642 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8643 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8644 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8645 [status_ setTextColor:[UIColor whiteColor]];
8646 [status_ setBackgroundColor:[UIColor clearColor]];
8647 [status_ setShadowColor:[UIColor blackColor]];
8648 [status_ setTextAlignment:UITextAlignmentCenter];
8649 [[self view] addSubview:status_];
8652 - (void) releaseSubviews {
8666 @interface Cydia : UIApplication <
8667 ConfirmationControllerDelegate,
8668 ProgressControllerDelegate,
8670 UINavigationControllerDelegate,
8671 UITabBarControllerDelegate
8673 // XXX: evaluate all fields for _transient
8676 CYTabBarController *tabbar_;
8678 NSMutableArray *essential_;
8679 NSMutableArray *broken_;
8681 Database *database_;
8688 StashController *stash_;
8697 @implementation Cydia
8699 - (void) beginUpdate {
8700 [tabbar_ beginUpdate];
8704 return [tabbar_ updating];
8708 if ([broken_ count] != 0) {
8709 int count = [broken_ count];
8711 UIAlertView *alert = [[[UIAlertView alloc]
8712 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8713 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8715 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8717 UCLocalize("TEMPORARY_IGNORE"),
8721 [alert setContext:@"fixhalf"];
8723 } else if (!Ignored_ && [essential_ count] != 0) {
8724 int count = [essential_ count];
8726 UIAlertView *alert = [[[UIAlertView alloc]
8727 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8728 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8730 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8732 UCLocalize("UPGRADE_ESSENTIAL"),
8733 UCLocalize("COMPLETE_UPGRADE"),
8737 [alert setContext:@"upgrade"];
8742 - (void) _saveConfig {
8748 NSString *error(nil);
8750 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8752 NSError *error(nil);
8753 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8754 NSLog(@"failure to save metadata data: %@", error);
8759 NSLog(@"failure to serialize metadata: %@", error);
8764 // Navigation controller for the queuing badge.
8765 - (CYNavigationController *) queueNavigationController {
8766 NSArray *controllers = [tabbar_ viewControllers];
8767 return [controllers objectAtIndex:3];
8770 - (void) _updateData {
8773 [tabbar_ reloadData];
8775 CYNavigationController *navigation = [self queueNavigationController];
8777 id queuedelegate = nil;
8778 if ([[navigation viewControllers] count] > 0)
8779 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8781 [queuedelegate queueStatusDidChange];
8782 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8785 - (void) _refreshIfPossible:(NSDate *)update {
8786 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8788 bool recently = false;
8789 if (update != nil) {
8790 NSTimeInterval interval([update timeIntervalSinceNow]);
8791 if (interval <= 0 && interval > -(15*60))
8795 // Don't automatic refresh if:
8796 // - We already refreshed recently.
8797 // - We already auto-refreshed this launch.
8798 // - Auto-refresh is disabled.
8799 if (recently || loaded_ || ManualRefresh) {
8800 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8802 // If we are cancelling, we need to make sure it knows it's already loaded.
8806 // We are going to load, so remember that.
8810 SCNetworkReachabilityFlags flags; {
8811 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8812 SCNetworkReachabilityGetFlags(reachability, &flags);
8813 CFRelease(reachability);
8816 // XXX: this elaborate mess is what Apple is using to determine this? :(
8817 // XXX: do we care if the user has to intervene? maybe that's ok?
8819 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8820 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8821 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8822 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8823 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8824 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8828 // If we can reach the server, auto-refresh!
8830 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8835 - (void) refreshIfPossible {
8836 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8839 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8840 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8841 [hud setText:UCLocalize("RELOADING_DATA")];
8843 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8846 [self removeProgressHUD:hud];
8850 [essential_ removeAllObjects];
8851 [broken_ removeAllObjects];
8853 NSArray *packages([database_ packages]);
8854 for (Package *package in packages) {
8856 [broken_ addObject:package];
8857 if ([package upgradableAndEssential:NO]) {
8858 if ([package essential])
8859 [essential_ addObject:package];
8864 NSLog(@"changes:#%u", changes);
8866 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8869 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8870 [changesItem setBadgeValue:badge];
8871 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8872 [self setApplicationIconBadgeNumber:changes];
8875 [changesItem setBadgeValue:nil];
8876 [changesItem setAnimatedBadge:NO];
8877 [self setApplicationIconBadgeNumber:0];
8882 [self refreshIfPossible];
8885 - (void) updateData {
8896 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8897 _assert(file != NULL);
8899 for (NSString *key in [Sources_ allKeys]) {
8900 NSDictionary *source([Sources_ objectForKey:key]);
8902 fprintf(file, "%s %s %s\n",
8903 [[source objectForKey:@"Type"] UTF8String],
8904 [[source objectForKey:@"URI"] UTF8String],
8905 [[source objectForKey:@"Distribution"] UTF8String]
8911 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8912 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8914 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8915 [tabbar_ presentModalViewController:navigation animated:YES];
8918 detachNewThreadSelector:@selector(update_)
8921 title:UCLocalize("UPDATING_SOURCES")
8925 - (void) addTrivialSource:(NSString *)href {
8926 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8929 @"./", @"Distribution",
8930 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8935 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8936 @synchronized (self) {
8937 [self _reloadDataWithInvocation:invocation];
8941 - (void) reloadData {
8942 [self reloadDataWithInvocation:nil];
8946 pkgProblemResolver *resolver = [database_ resolver];
8948 resolver->InstallProtect();
8949 if (!resolver->Resolve(true))
8954 // XXX: this is a really crappy way of doing this.
8955 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8956 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8957 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8958 if ([tabbar_ updating])
8959 [tabbar_ cancelUpdate];
8961 if (![database_ prepare])
8964 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8965 [page setDelegate:self];
8966 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8967 [confirm_ setDelegate:self];
8970 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8971 [tabbar_ presentModalViewController:confirm_ animated:YES];
8977 @synchronized (self) {
8982 - (void) clearPackage:(Package *)package {
8983 @synchronized (self) {
8990 - (void) installPackages:(NSArray *)packages {
8991 @synchronized (self) {
8992 for (Package *package in packages)
8999 - (void) installPackage:(Package *)package {
9000 @synchronized (self) {
9007 - (void) removePackage:(Package *)package {
9008 @synchronized (self) {
9015 - (void) distUpgrade {
9016 @synchronized (self) {
9017 if (![database_ upgrade])
9024 @synchronized (self) {
9025 [self _reloadDataWithInvocation:nil];
9029 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9032 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
9034 if (navigation != nil) {
9035 [navigation pushViewController:progress animated:YES];
9037 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
9039 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9040 [tabbar_ presentModalViewController:navigation animated:YES];
9044 detachNewThreadSelector:@selector(perform)
9047 title:UCLocalize("RUNNING")
9053 - (void) progressControllerIsComplete:(ProgressController *)progress {
9058 - (void) showSettings {
9059 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9060 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9062 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9063 [tabbar_ presentModalViewController:nav animated:YES];
9066 - (void) retainNetworkActivityIndicator {
9067 if (activity_++ == 0)
9068 [self setNetworkActivityIndicatorVisible:YES];
9071 - (void) releaseNetworkActivityIndicator {
9072 if (--activity_ == 0)
9073 [self setNetworkActivityIndicatorVisible:NO];
9076 - (void) cancelAndClear:(bool)clear {
9077 @synchronized (self) {
9089 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9090 NSString *context([alert context]);
9092 if ([context isEqualToString:@"fixhalf"]) {
9093 if (button == [alert cancelButtonIndex]) {
9094 @synchronized (self) {
9095 for (Package *broken in broken_) {
9098 NSString *id = [broken id];
9099 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9100 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9101 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9102 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9108 } else if (button == [alert firstOtherButtonIndex]) {
9109 [broken_ removeAllObjects];
9113 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9114 } else if ([context isEqualToString:@"upgrade"]) {
9115 if (button == [alert firstOtherButtonIndex]) {
9116 @synchronized (self) {
9117 for (Package *essential in essential_)
9118 [essential install];
9123 } else if (button == [alert firstOtherButtonIndex] + 1) {
9125 } else if (button == [alert cancelButtonIndex]) {
9129 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9133 - (void) system:(NSString *)command { _pooled
9135 system([command UTF8String]);
9139 - (void) applicationWillSuspend {
9141 [super applicationWillSuspend];
9144 - (BOOL) isSafeToSuspend {
9145 // Use external process status API internally.
9146 // This is probably a really bad idea.
9147 // XXX: what is the point of this? does this solve anything at all?
9148 uint64_t status = 0;
9150 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9151 notify_get_state(notify_token, &status);
9152 notify_cancel(notify_token);
9155 return locked_ == 0 && status == 0;
9158 - (void) applicationSuspend:(__GSEvent *)event {
9159 if ([self isSafeToSuspend])
9160 [super applicationSuspend:event];
9163 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9164 if ([self isSafeToSuspend])
9165 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9168 - (void) _setSuspended:(BOOL)value {
9169 if ([self isSafeToSuspend])
9170 [super _setSuspended:value];
9173 - (UIProgressHUD *) addProgressHUD {
9174 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9175 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9177 [window_ setUserInteractionEnabled:NO];
9180 UIViewController *target = tabbar_;
9181 while ([target modalViewController] != nil) target = [target modalViewController];
9182 [[target view] addSubview:hud];
9188 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9190 [hud removeFromSuperview];
9191 [window_ setUserInteractionEnabled:YES];
9195 - (CYViewController *) pageForPackage:(NSString *)name {
9196 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9199 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9200 NSString *scheme([[url scheme] lowercaseString]);
9201 if ([[url absoluteString] length] <= [scheme length] + 3)
9203 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9204 NSArray *components([path pathComponents]);
9206 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9207 return [self pageForPackage:[components objectAtIndex:1]];
9209 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9212 NSString *base([components objectAtIndex:0]);
9214 CYViewController *controller = nil;
9216 if ([base isEqualToString:@"url"]) {
9217 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9218 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9219 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9220 } else if (!external && [components count] == 1) {
9221 if ([base isEqualToString:@"manage"]) {
9222 controller = [[[ManageController alloc] init] autorelease];
9225 if ([base isEqualToString:@"sources"]) {
9226 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9229 if ([base isEqualToString:@"home"]) {
9230 controller = [[[HomeController alloc] init] autorelease];
9233 if ([base isEqualToString:@"sections"]) {
9234 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9237 if ([base isEqualToString:@"search"]) {
9238 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9241 if ([base isEqualToString:@"changes"]) {
9242 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9245 if ([base isEqualToString:@"installed"]) {
9246 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9248 } else if ([components count] == 2) {
9249 NSString *argument = [components objectAtIndex:1];
9251 if ([base isEqualToString:@"package"]) {
9252 controller = [self pageForPackage:argument];
9255 if (!external && [base isEqualToString:@"search"]) {
9256 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9257 [(SearchController *)controller setSearchTerm:argument];
9260 if (!external && [base isEqualToString:@"sections"]) {
9261 if ([argument isEqualToString:@"all"])
9263 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9266 if (!external && [base isEqualToString:@"sources"]) {
9267 if ([argument isEqualToString:@"add"]) {
9268 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9269 [(SourcesController *)controller showAddSourcePrompt];
9271 Source *source = [database_ sourceWithKey:argument];
9272 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9276 if (!external && [base isEqualToString:@"launch"]) {
9277 [self launchApplicationWithIdentifier:argument suspended:NO];
9280 } else if (!external && [components count] == 3) {
9281 NSString *arg1 = [components objectAtIndex:1];
9282 NSString *arg2 = [components objectAtIndex:2];
9284 if ([base isEqualToString:@"package"]) {
9285 if ([arg2 isEqualToString:@"settings"]) {
9286 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9287 } else if ([arg2 isEqualToString:@"files"]) {
9288 if (Package *package = [database_ packageWithName:arg1]) {
9289 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9290 [(FileTable *)controller setPackage:package];
9296 [controller setDelegate:self];
9300 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9301 CYViewController *page([self pageForURL:url forExternal:external]);
9304 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9305 [nav setViewControllers:[NSArray arrayWithObject:page]];
9306 [tabbar_ setUnselectedViewController:nav];
9312 - (void) applicationOpenURL:(NSURL *)url {
9313 [super applicationOpenURL:url];
9315 if (!loaded_) starturl_ = [url retain];
9316 else [self openCydiaURL:url forExternal:YES];
9319 - (void) applicationWillResignActive:(UIApplication *)application {
9320 // Stop refreshing if you get a phone call or lock the device.
9321 if ([tabbar_ updating])
9322 [tabbar_ cancelUpdate];
9324 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9325 [super applicationWillResignActive:application];
9328 - (void) applicationWillTerminate:(UIApplication *)application {
9330 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9331 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9332 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9337 - (void) addStashController {
9339 stash_ = [[StashController alloc] init];
9340 [window_ addSubview:[stash_ view]];
9343 - (void) removeStashController {
9344 [[stash_ view] removeFromSuperview];
9350 [self setIdleTimerDisabled:YES];
9352 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9353 [self setStatusBarShowsProgress:YES];
9354 UpdateExternalStatus(1);
9356 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9358 UpdateExternalStatus(0);
9359 [self setStatusBarShowsProgress:NO];
9361 [self removeStashController];
9363 if (ExecFork() == 0) {
9364 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9365 perror("launchctl stop");
9369 - (void) setupViewControllers {
9370 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9372 NSMutableArray *items([NSMutableArray arrayWithObjects:
9373 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9374 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9375 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9376 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9380 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9381 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9383 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9386 NSMutableArray *controllers([NSMutableArray array]);
9387 for (UITabBarItem *item in items) {
9388 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9389 [controller setTabBarItem:item];
9390 [controllers addObject:controller];
9392 [tabbar_ setViewControllers:controllers];
9394 [tabbar_ setUpdateDelegate:self];
9397 - (CYEmulatedLoadingController *) showEmulatedLoadingControllerInView:(UIView *)view {
9398 static CYEmulatedLoadingController *fake = nil;
9402 fake = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9403 [view addSubview:[fake view]];
9405 [[fake view] removeFromSuperview];
9413 - (void) applicationDidFinishLaunching:(id)unused {
9417 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9418 [self setApplicationSupportsShakeToEdit:NO];
9420 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9421 initWithMemoryCapacity:524288
9422 diskCapacity:10485760
9423 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9426 [CYBrowserController _initialize];
9428 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9430 Font12_ = [[UIFont systemFontOfSize:12] retain];
9431 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9432 Font14_ = [[UIFont systemFontOfSize:14] retain];
9433 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9434 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9436 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9437 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9439 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9440 [window_ orderFront:self];
9441 [window_ makeKey:self];
9442 [window_ setHidden:NO];
9445 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9446 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9447 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9448 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9449 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9450 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9451 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9452 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9453 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9456 [self addStashController];
9457 // XXX: this would be much cleaner as a yieldToSelector:
9458 // that way the removeStashController could happen right here inline
9459 // we also could no longer require the useless stash_ field anymore
9460 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9464 database_ = [Database sharedInstance];
9466 [window_ setUserInteractionEnabled:NO];
9467 [self setupViewControllers];
9468 [self showEmulatedLoadingControllerInView:window_];
9470 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9477 [window_ setUserInteractionEnabled:YES];
9479 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9480 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9482 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9483 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9487 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9488 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9489 [window_ setUserInteractionEnabled:NO];
9495 [window_ addSubview:[tabbar_ view]];
9496 [self showEmulatedLoadingControllerInView:nil];
9497 [window_ setUserInteractionEnabled:YES];
9499 int selectedIndex = 0;
9500 NSMutableArray *items = nil;
9502 bool recently = false;
9503 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9504 if (closed != nil) {
9505 NSTimeInterval interval([closed timeIntervalSinceNow]);
9506 // XXX: Is 15 minutes the optimal time here?
9507 if (interval <= 0 && interval > -(15*60))
9511 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9512 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9515 for (NSArray *entry in items)
9516 if ([entry count] <= 0)
9519 if (!recently || !items || !enough) {
9521 items = [NSMutableArray array];
9522 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9523 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9524 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9526 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9528 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9529 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9531 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9534 [tabbar_ setSelectedIndex:selectedIndex];
9535 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9536 NSArray *stack = [items objectAtIndex:tab];
9537 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9538 NSMutableArray *current = [NSMutableArray array];
9540 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9541 NSString *addr = [stack objectAtIndex:nav];
9542 NSURL *url = [NSURL URLWithString:addr];
9543 CYViewController *page = [self pageForURL:url forExternal:NO];
9545 [current addObject:page];
9548 [navigation setViewControllers:current];
9551 // (Try to) show the startup URL.
9552 if (starturl_ != nil) {
9553 [self openCydiaURL:starturl_ forExternal:NO];
9554 [starturl_ release];
9559 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9560 if (item != nil && IsWildcat_) {
9561 [sheet showFromBarButtonItem:item animated:YES];
9563 [sheet showInView:window_];
9570 id Alloc_(id self, SEL selector) {
9571 id object = alloc_(self, selector);
9572 lprintf("[%s]A-%p\n", self->isa->name, object);
9577 id Dealloc_(id self, SEL selector) {
9578 id object = dealloc_(self, selector);
9579 lprintf("[%s]D-%p\n", self->isa->name, object);
9583 Class $WebDefaultUIKitDelegate;
9585 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9586 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9587 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9588 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9591 static NSNumber *shouldPlayKeyboardSounds;
9595 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9597 case 1104: // Keyboard Button Clicked
9598 case 1105: // Keyboard Delete Repeated
9599 if (shouldPlayKeyboardSounds == nil) {
9600 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9601 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9604 if (![shouldPlayKeyboardSounds boolValue])
9608 _UIHardware$_playSystemSound$(self, _cmd, sound);
9612 Class $UIApplication;
9614 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9615 static BOOL initialized = NO;
9616 static BOOL started = NO;
9618 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9619 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9621 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9622 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9623 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9624 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9626 if (initialized && !enabled) {
9628 [bundle performSelector:@selector(_accessibilityStopServer)];
9629 } else if (enabled) {
9633 [bundle performSelector:@selector(_accessibilityStartServer)];
9639 int main(int argc, char *argv[]) { _pooled
9642 UpdateExternalStatus(0);
9644 if (Class $UIDevice = objc_getClass("UIDevice")) {
9645 UIDevice *device([$UIDevice currentDevice]);
9646 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9650 UIScreen *screen([UIScreen mainScreen]);
9651 if ([screen respondsToSelector:@selector(scale)])
9652 ScreenScale_ = [screen scale];
9656 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9657 if (ScreenScale_ > 1)
9658 [parts addObject:@"@2x"];
9659 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9660 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9662 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9664 /* Library Hacks {{{ */
9665 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9667 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9668 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9669 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9670 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9671 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9674 $UIHardware = objc_getClass("UIHardware");
9675 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9676 if (UIHardware$_playSystemSound$ != NULL) {
9677 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9678 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9681 $UIApplication = objc_getClass("UIApplication");
9682 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9683 if (UIApplication$_updateApplicationAccessibility != NULL) {
9684 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9685 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9688 /* Set Locale {{{ */
9689 Locale_ = CFLocaleCopyCurrent();
9690 Languages_ = [NSLocale preferredLanguages];
9691 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9692 //NSLog(@"%@", [Languages_ description]);
9695 if (Languages_ == nil || [Languages_ count] == 0)
9696 // XXX: consider just setting to C and then falling through?
9699 lang = [[Languages_ objectAtIndex:0] UTF8String];
9700 setenv("LANG", lang, true);
9703 //std::setlocale(LC_ALL, lang);
9704 NSLog(@"Setting Language: %s", lang);
9707 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9709 /* Parse Arguments {{{ */
9710 bool substrate(false);
9716 for (int argi(1); argi != argc; ++argi)
9717 if (strcmp(argv[argi], "--") == 0) {
9719 argv[argi] = argv[0];
9725 for (int argi(1); argi != arge; ++argi)
9726 if (strcmp(args[argi], "--substrate") == 0)
9729 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9733 App_ = [[NSBundle mainBundle] bundlePath];
9734 Home_ = NSHomeDirectory();
9740 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9741 alloc_ = alloc->method_imp;
9742 alloc->method_imp = (IMP) &Alloc_;*/
9744 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9745 dealloc_ = dealloc->method_imp;
9746 dealloc->method_imp = (IMP) &Dealloc_;*/
9748 /* System Information {{{ */
9752 size = sizeof(maxproc);
9753 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9754 perror("sysctlbyname(\"kern.maxproc\", ?)");
9755 else if (maxproc < 64) {
9757 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9758 perror("sysctlbyname(\"kern.maxproc\", #)");
9761 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9762 char *osversion = new char[size];
9763 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9764 perror("sysctlbyname(\"kern.osversion\", ?)");
9766 System_ = [NSString stringWithUTF8String:osversion];
9768 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9769 char *machine = new char[size];
9770 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9771 perror("sysctlbyname(\"hw.machine\", ?)");
9775 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9776 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9777 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9778 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9782 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9783 NSData *data((NSData *) ecid);
9784 size_t length([data length]);
9785 uint8_t bytes[length];
9786 [data getBytes:bytes];
9787 char string[length * 2 + 1];
9788 for (size_t i(0); i != length; ++i)
9789 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9790 ChipID_ = [NSString stringWithUTF8String:string];
9794 IOObjectRelease(service);
9798 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9800 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9801 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9802 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9804 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9805 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9806 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9808 if (mcc != NULL && mnc != NULL)
9809 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9816 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9817 Build_ = [system objectForKey:@"ProductBuildVersion"];
9818 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9819 Product_ = [info objectForKey:@"SafariProductVersion"];
9820 Safari_ = [info objectForKey:@"CFBundleVersion"];
9823 /* Load Database {{{ */
9825 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9827 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9829 if (Metadata_ == NULL)
9830 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9832 Settings_ = [Metadata_ objectForKey:@"Settings"];
9834 Packages_ = [Metadata_ objectForKey:@"Packages"];
9835 Sections_ = [Metadata_ objectForKey:@"Sections"];
9836 Sources_ = [Metadata_ objectForKey:@"Sources"];
9838 Token_ = [Metadata_ objectForKey:@"Token"];
9841 if (Settings_ != nil)
9842 Role_ = [Settings_ objectForKey:@"Role"];
9844 if (Sections_ == nil) {
9845 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9846 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9849 if (Sources_ == nil) {
9850 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9851 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9856 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9859 if (Packages_ != nil) {
9861 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9865 [Metadata_ removeObjectForKey:@"Packages"];
9871 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9873 #define MobileSubstrate_(name) \
9874 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) \
9875 dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL);
9877 MobileSubstrate_(Activator)
9878 MobileSubstrate_(libstatusbar)
9879 MobileSubstrate_(SimulatedKeyEvents)
9880 MobileSubstrate_(WinterBoard)
9882 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9883 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9885 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9887 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9888 unlink("/tmp/.cydia.fw");
9890 } else if (access("/User", F_OK) != 0 || version < 2) {
9893 system("/usr/libexec/cydia/firmware.sh");
9897 _assert([[NSFileManager defaultManager]
9898 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9899 withIntermediateDirectories:YES
9904 if (access("/tmp/cydia.chk", F_OK) == 0) {
9905 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9906 _assert(errno == ENOENT);
9907 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9908 _assert(errno == ENOENT);
9911 /* APT Initialization {{{ */
9912 _assert(pkgInitConfig(*_config));
9913 _assert(pkgInitSystem(*_config, _system));
9916 _config->Set("APT::Acquire::Translation", lang);
9918 // XXX: this timeout might be important :(
9919 //_config->Set("Acquire::http::Timeout", 15);
9921 _config->Set("Acquire::http::MaxParallel", 3);
9923 /* Color Choices {{{ */
9924 space_ = CGColorSpaceCreateDeviceRGB();
9926 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9927 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9928 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9929 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9930 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9931 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9932 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9933 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9934 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9936 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9937 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9939 /* UIKit Configuration {{{ */
9940 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9941 if ($GSFontSetUseLegacyFontMetrics != NULL)
9942 $GSFontSetUseLegacyFontMetrics(YES);
9944 // XXX: I have a feeling this was important
9945 //UIKeyboardDisableAutomaticAppearance();
9948 Colon_ = UCLocalize("COLON_DELIMITED");
9949 Elision_ = UCLocalize("ELISION");
9950 Error_ = UCLocalize("ERROR");
9951 Warning_ = UCLocalize("WARNING");
9954 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9956 CGColorSpaceRelease(space_);