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 NSArray *Finishes_;
992 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
993 #define NotifyConfig_ "/etc/notify.conf"
995 static bool Queuing_;
997 static CYColor Blue_;
998 static CYColor Blueish_;
999 static CYColor Black_;
1000 static CYColor Off_;
1001 static CYColor White_;
1002 static CYColor Gray_;
1003 static CYColor Green_;
1004 static CYColor Purple_;
1005 static CYColor Purplish_;
1007 static UIColor *InstallingColor_;
1008 static UIColor *RemovingColor_;
1010 static NSString *App_;
1011 static NSString *Home_;
1013 static BOOL Advanced_;
1014 static BOOL Ignored_;
1016 static UIFont *Font12_;
1017 static UIFont *Font12Bold_;
1018 static UIFont *Font14_;
1019 static UIFont *Font18Bold_;
1020 static UIFont *Font22Bold_;
1022 static const char *Machine_ = NULL;
1023 static NSString *System_ = nil;
1024 static NSString *SerialNumber_ = nil;
1025 static NSString *ChipID_ = nil;
1026 static NSString *Token_ = nil;
1027 static NSString *UniqueID_ = nil;
1028 static NSString *PLMN_ = nil;
1029 static NSString *Build_ = nil;
1030 static NSString *Product_ = nil;
1031 static NSString *Safari_ = nil;
1033 static CFLocaleRef Locale_;
1034 static NSArray *Languages_;
1035 static CGColorSpaceRef space_;
1037 static NSDictionary *SectionMap_;
1038 static NSMutableDictionary *Metadata_;
1039 static _transient NSMutableDictionary *Settings_;
1040 static _transient NSString *Role_;
1041 static _transient NSMutableDictionary *Packages_;
1042 static _transient NSMutableDictionary *Sections_;
1043 static _transient NSMutableDictionary *Sources_;
1044 static bool Changed_;
1048 static CGFloat ScreenScale_;
1051 /* Display Helpers {{{ */
1052 inline float Interpolate(float begin, float end, float fraction) {
1053 return (end - begin) * fraction + begin;
1056 static _finline const char *StripVersion_(const char *version) {
1057 const char *colon(strchr(version, ':'));
1058 return colon == NULL ? version : colon + 1;
1061 NSString *LocalizeSection(NSString *section) {
1062 static Pcre title_r("^(.*?) \\((.*)\\)$");
1063 if (title_r(section)) {
1064 NSString *parent(title_r[1]);
1065 NSString *child(title_r[2]);
1067 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1068 LocalizeSection(parent),
1069 LocalizeSection(child)
1073 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1076 NSString *Simplify(NSString *title) {
1077 const char *data = [title UTF8String];
1078 size_t size = [title length];
1080 static Pcre square_r("^\\[(.*)\\]$");
1081 if (square_r(data, size))
1082 return Simplify(square_r[1]);
1084 static Pcre paren_r("^\\((.*)\\)$");
1085 if (paren_r(data, size))
1086 return Simplify(paren_r[1]);
1088 static Pcre title_r("^(.*?) \\((.*)\\)$");
1089 if (title_r(data, size))
1090 return Simplify(title_r[1]);
1096 NSString *GetLastUpdate() {
1097 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1100 return UCLocalize("NEVER_OR_UNKNOWN");
1102 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1103 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1105 CFRelease(formatter);
1107 return [(NSString *) formatted autorelease];
1110 bool isSectionVisible(NSString *section) {
1111 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1112 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1113 return hidden == nil || ![hidden boolValue];
1118 /* Delegate Prototypes {{{ */
1122 @interface NSObject (ProgressDelegate)
1125 @protocol ProgressDelegate
1126 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1127 - (void) setProgressTitle:(NSString *)title;
1128 - (void) setProgressPercent:(float)percent;
1129 - (void) startProgress;
1130 - (void) addProgressOutput:(NSString *)output;
1131 - (bool) isCancelling:(size_t)received;
1134 @protocol ConfigurationDelegate
1135 - (void) repairWithSelector:(SEL)selector;
1136 - (void) setConfigurationData:(NSString *)data;
1139 @class CYPackageController;
1141 @protocol CydiaDelegate
1142 - (void) retainNetworkActivityIndicator;
1143 - (void) releaseNetworkActivityIndicator;
1144 - (void) clearPackage:(Package *)package;
1145 - (void) installPackage:(Package *)package;
1146 - (void) installPackages:(NSArray *)packages;
1147 - (void) removePackage:(Package *)package;
1148 - (void) beginUpdate;
1150 - (void) distUpgrade;
1152 - (void) updateData;
1154 - (void) addTrivialSource:(NSString *)href;
1155 - (void) showSettings;
1156 - (UIProgressHUD *) addProgressHUD;
1157 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1158 - (CYViewController *) pageForPackage:(NSString *)name;
1159 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1160 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1163 static id<CydiaDelegate> CydiaApp;
1166 /* Status Delegation {{{ */
1168 public pkgAcquireStatus
1171 _transient NSObject<ProgressDelegate> *delegate_;
1179 void setDelegate(id delegate) {
1180 delegate_ = delegate;
1183 NSObject<ProgressDelegate> *getDelegate() const {
1187 virtual bool MediaChange(std::string media, std::string drive) {
1191 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1194 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1195 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1196 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1199 virtual void Done(pkgAcquire::ItemDesc &item) {
1202 virtual void Fail(pkgAcquire::ItemDesc &item) {
1204 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1205 item.Owner->Status == pkgAcquire::Item::StatDone
1209 std::string &error(item.Owner->ErrorText);
1213 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1214 NSArray *fields([description componentsSeparatedByString:@" "]);
1215 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1217 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1218 withObject:[NSArray arrayWithObjects:
1219 [NSString stringWithUTF8String:error.c_str()],
1226 virtual bool Pulse(pkgAcquire *Owner) {
1227 bool value = pkgAcquireStatus::Pulse(Owner);
1230 double(CurrentBytes + CurrentItems) /
1231 double(TotalBytes + TotalItems)
1234 [delegate_ setProgressPercent:percent];
1235 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1238 virtual void Start() {
1239 [delegate_ startProgress];
1242 virtual void Stop() {
1246 /* Progress Delegation {{{ */
1251 _transient id<ProgressDelegate> delegate_;
1255 virtual void Update() {
1256 /*if (abs(Percent - percent_) > 2)
1257 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1261 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1262 [delegate_ setProgressPercent:(Percent / 100)];*/
1272 void setDelegate(id delegate) {
1273 delegate_ = delegate;
1276 id getDelegate() const {
1280 virtual void Done() {
1282 //[delegate_ setProgressPercent:1];
1287 /* Database Interface {{{ */
1288 typedef std::map< unsigned long, _H<Source> > SourceMap;
1290 @interface Database : NSObject {
1296 pkgCacheFile cache_;
1297 pkgDepCache::Policy *policy_;
1298 pkgRecords *records_;
1299 pkgProblemResolver *resolver_;
1300 pkgAcquire *fetcher_;
1302 SPtr<pkgPackageManager> manager_;
1303 pkgSourceList *list_;
1305 SourceMap sourceMap_;
1306 NSMutableArray *sourceList_;
1308 CFMutableArrayRef packages_;
1310 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1318 std::map<const char *, _H<NSString> > sections_;
1321 + (Database *) sharedInstance;
1324 - (void) _readCydia:(NSNumber *)fd;
1325 - (void) _readStatus:(NSNumber *)fd;
1326 - (void) _readOutput:(NSNumber *)fd;
1330 - (Package *) packageWithName:(NSString *)name;
1332 - (pkgCacheFile &) cache;
1333 - (pkgDepCache::Policy *) policy;
1334 - (pkgRecords *) records;
1335 - (pkgProblemResolver *) resolver;
1336 - (pkgAcquire &) fetcher;
1337 - (pkgSourceList &) list;
1338 - (NSArray *) packages;
1339 - (NSArray *) sources;
1340 - (Source *) sourceWithKey:(NSString *)key;
1341 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1349 - (void) updateWithStatus:(Status &)status;
1351 - (void) setDelegate:(id)delegate;
1352 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1354 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1358 /* Delegate Helpers {{{ */
1359 @implementation NSObject (ProgressDelegate)
1361 - (void) _setProgressErrorPackage:(NSArray *)args {
1362 [self performSelector:@selector(setProgressError:forPackage:)
1363 withObject:[args objectAtIndex:0]
1364 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1368 - (void) _setProgressErrorTitle:(NSArray *)args {
1369 [self performSelector:@selector(setProgressError:withTitle:)
1370 withObject:[args objectAtIndex:0]
1371 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1375 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1376 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1377 withObject:[NSArray arrayWithObjects:error, title, nil]
1382 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1383 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1385 [self performSelector:@selector(setProgressError:withTitle:)
1387 withObject:(package == nil ? id : [package name])
1394 // Cytore Definitions {{{
1395 struct PackageValue :
1398 Cytore::Offset<PackageValue> next_;
1400 uint32_t index_ : 23;
1401 uint32_t subscribed_ : 1;
1418 Cytore::Offset<PackageValue> packages_[1 << 16];
1421 static Cytore::File<MetaValue> MetaFile_;
1423 // Cytore Helper Functions {{{
1424 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1425 SplitHash nhash = { hashlittle(name, length) };
1427 PackageValue *metadata;
1429 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1430 offset: if (offset->IsNull()) {
1431 *offset = MetaFile_.New<PackageValue>(length + 1);
1432 metadata = &MetaFile_.Get(*offset);
1434 if (metadata == NULL) {
1438 metadata = new PackageValue();
1439 memset(metadata, 0, sizeof(*metadata));
1442 memcpy(metadata->name_, name, length + 1);
1443 metadata->nhash_ = nhash.u16[1];
1445 metadata = &MetaFile_.Get(*offset);
1447 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1448 offset = &metadata->next_;
1456 static void PackageImport(const void *key, const void *value, void *context) {
1457 bool &fail(*reinterpret_cast<bool *>(context));
1460 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1461 NSLog(@"failed to import package %@", key);
1465 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1466 NSDictionary *package((NSDictionary *) value);
1468 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1469 if ([subscribed boolValue] && !metadata->subscribed_)
1470 metadata->subscribed_ = true;
1472 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1473 time_t time([date timeIntervalSince1970]);
1474 if (metadata->first_ > time || metadata->first_ == 0)
1475 metadata->first_ = time;
1478 NSDate *date([package objectForKey:@"LastSeen"]);
1479 NSString *version([package objectForKey:@"LastVersion"]);
1481 if (date != nil && version != nil) {
1482 time_t time([date timeIntervalSince1970]);
1483 if (metadata->last_ < time || metadata->last_ == 0)
1484 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1485 size_t length(strlen(buffer));
1486 uint16_t vhash(hashlittle(buffer, length));
1488 size_t capped(std::min<size_t>(8, length));
1489 char *latest(buffer + length - capped);
1491 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1492 metadata->vhash_ = vhash;
1494 metadata->last_ = time;
1500 /* Source Class {{{ */
1501 @interface Source : NSObject {
1502 CYString depiction_;
1503 CYString description_;
1509 CYString distribution_;
1514 NSString *authority_;
1516 CYString defaultIcon_;
1518 NSDictionary *record_;
1522 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1524 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1526 - (NSString *) depictionForPackage:(NSString *)package;
1527 - (NSString *) supportForPackage:(NSString *)package;
1529 - (NSDictionary *) record;
1533 - (NSString *) distribution;
1534 - (NSString *) type;
1536 - (NSString *) host;
1538 - (NSString *) name;
1539 - (NSString *) description;
1540 - (NSString *) label;
1541 - (NSString *) origin;
1542 - (NSString *) version;
1544 - (NSString *) defaultIcon;
1548 @implementation Source
1552 distribution_.clear();
1555 description_.clear();
1561 defaultIcon_.clear();
1563 if (record_ != nil) {
1573 if (authority_ != nil) {
1574 [authority_ release];
1580 // XXX: this is a very inefficient way to call these deconstructors
1585 + (NSArray *) _attributeKeys {
1586 return [NSArray arrayWithObjects:
1601 - (NSArray *) attributeKeys {
1602 return [[self class] _attributeKeys];
1605 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1606 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1609 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1612 trusted_ = index->IsTrusted();
1614 uri_.set(pool, index->GetURI());
1615 distribution_.set(pool, index->GetDist());
1616 type_.set(pool, index->GetType());
1618 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1619 if (dindex != NULL) {
1621 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1624 pkgTagFile tags(&fd);
1626 pkgTagSection section;
1633 {"default-icon", &defaultIcon_},
1634 {"depiction", &depiction_},
1635 {"description", &description_},
1637 {"origin", &origin_},
1638 {"support", &support_},
1639 {"version", &version_},
1642 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1643 const char *start, *end;
1645 if (section.Find(names[i].name_, start, end)) {
1646 CYString &value(*names[i].value_);
1647 value.set(pool, start, end - start);
1653 record_ = [Sources_ objectForKey:[self key]];
1655 record_ = [record_ retain];
1657 NSURL *url([NSURL URLWithString:uri_]);
1661 host_ = [[host_ lowercaseString] retain];
1666 authority_ = [url path];
1668 if (authority_ != nil)
1669 authority_ = [authority_ retain];
1672 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1673 if ((self = [super init]) != nil) {
1674 [self setMetaIndex:index inPool:pool];
1678 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1679 NSDictionary *lhr = [self record];
1680 NSDictionary *rhr = [source record];
1683 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1685 NSString *lhs = [self name];
1686 NSString *rhs = [source name];
1688 if ([lhs length] != 0 && [rhs length] != 0) {
1689 unichar lhc = [lhs characterAtIndex:0];
1690 unichar rhc = [rhs characterAtIndex:0];
1692 if (isalpha(lhc) && !isalpha(rhc))
1693 return NSOrderedAscending;
1694 else if (!isalpha(lhc) && isalpha(rhc))
1695 return NSOrderedDescending;
1698 return [lhs compare:rhs options:LaxCompareOptions_];
1701 - (NSString *) depictionForPackage:(NSString *)package {
1702 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1705 - (NSString *) supportForPackage:(NSString *)package {
1706 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1709 - (NSDictionary *) record {
1717 - (NSString *) uri {
1721 - (NSString *) distribution {
1722 return distribution_;
1725 - (NSString *) type {
1729 - (NSString *) key {
1730 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1733 - (NSString *) host {
1737 - (NSString *) name {
1738 return origin_.empty() ? authority_ : origin_;
1741 - (NSString *) description {
1742 return description_;
1745 - (NSString *) label {
1746 return label_.empty() ? authority_ : label_;
1749 - (NSString *) origin {
1753 - (NSString *) version {
1757 - (NSString *) defaultIcon {
1758 return defaultIcon_;
1763 /* CydiaOperation Class {{{ */
1764 @interface CydiaOperation : NSObject {
1765 NSString *operator_;
1769 - (NSString *) operator;
1770 - (NSString *) value;
1774 @implementation CydiaOperation
1777 [operator_ release];
1782 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1783 if ((self = [super init]) != nil) {
1784 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1785 value_ = [[NSString alloc] initWithUTF8String:value];
1789 + (NSArray *) _attributeKeys {
1790 return [NSArray arrayWithObjects:
1796 - (NSArray *) attributeKeys {
1797 return [[self class] _attributeKeys];
1800 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1801 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1804 - (NSString *) operator {
1808 - (NSString *) value {
1814 /* CydiaClause Class {{{ */
1815 @interface CydiaClause : NSObject {
1817 CydiaOperation *version_;
1820 - (NSString *) package;
1821 - (CydiaOperation *) version;
1825 @implementation CydiaClause
1833 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1834 if ((self = [super init]) != nil) {
1835 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1837 if (const char *version = dep.TargetVer())
1838 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1840 version_ = [[NSNull null] retain];
1844 + (NSArray *) _attributeKeys {
1845 return [NSArray arrayWithObjects:
1851 - (NSArray *) attributeKeys {
1852 return [[self class] _attributeKeys];
1855 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1856 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1859 - (NSString *) package {
1863 - (CydiaOperation *) version {
1869 /* CydiaRelation Class {{{ */
1870 @interface CydiaRelation : NSObject {
1871 NSString *relationship_;
1872 NSMutableArray *clauses_;
1875 - (NSString *) relationship;
1876 - (NSArray *) clauses;
1880 @implementation CydiaRelation
1883 [relationship_ release];
1888 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1889 if ((self = [super init]) != nil) {
1890 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1891 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1893 pkgCache::DepIterator start;
1894 pkgCache::DepIterator end;
1895 dep.GlobOr(start, end); // ++dep
1898 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1900 // yes, seriously. (wtf?)
1908 + (NSArray *) _attributeKeys {
1909 return [NSArray arrayWithObjects:
1915 - (NSArray *) attributeKeys {
1916 return [[self class] _attributeKeys];
1919 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1920 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1923 - (NSString *) relationship {
1924 return relationship_;
1927 - (NSArray *) clauses {
1931 - (void) addClause:(CydiaClause *)clause {
1932 [clauses_ addObject:clause];
1937 /* Package Class {{{ */
1938 struct ParsedPackage {
1943 CYString depiction_;
1953 @interface Package : NSObject {
1956 uint32_t essential_ : 1;
1957 uint32_t obsolete_ : 1;
1958 uint32_t ignored_ : 1;
1962 _transient Database *database_;
1964 pkgCache::VerIterator version_;
1965 pkgCache::PkgIterator iterator_;
1966 pkgCache::VerFileIterator file_;
1972 CYString installed_;
1974 const char *section_;
1975 _transient NSString *section$_;
1979 PackageValue *metadata_;
1980 ParsedPackage *parsed_;
1982 NSMutableArray *tags_;
1985 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1986 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1988 - (pkgCache::PkgIterator) iterator;
1991 - (NSString *) section;
1992 - (NSString *) simpleSection;
1994 - (NSString *) longSection;
1995 - (NSString *) shortSection;
1999 - (Address *) maintainer;
2001 - (NSString *) longDescription;
2002 - (NSString *) shortDescription;
2005 - (PackageValue *) metadata;
2008 - (bool) subscribed;
2009 - (bool) setSubscribed:(bool)subscribed;
2013 - (NSString *) latest;
2014 - (NSString *) installed;
2015 - (BOOL) uninstalled;
2018 - (BOOL) upgradableAndEssential:(BOOL)essential;
2021 - (BOOL) unfiltered;
2025 - (BOOL) halfConfigured;
2026 - (BOOL) halfInstalled;
2028 - (NSString *) mode;
2031 - (NSString *) name;
2033 - (NSString *) homepage;
2034 - (NSString *) depiction;
2035 - (Address *) author;
2037 - (NSString *) support;
2039 - (NSArray *) files;
2040 - (NSArray *) warnings;
2041 - (NSArray *) applications;
2043 - (Source *) source;
2045 - (BOOL) matches:(NSString *)text;
2047 - (bool) hasSupportingRole;
2048 - (BOOL) hasTag:(NSString *)tag;
2049 - (NSString *) primaryPurpose;
2050 - (NSArray *) purposes;
2051 - (bool) isCommercial;
2053 - (void) setIndex:(size_t)index;
2055 - (CYString &) cyname;
2057 - (uint32_t) compareBySection:(NSArray *)sections;
2062 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2063 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2064 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2065 - (bool) isVisibleInSection:(NSString *)section;
2066 - (bool) isVisibleInSource:(Source *)source;
2070 uint32_t PackageChangesRadix(Package *self, void *) {
2075 uint32_t timestamp : 30;
2076 uint32_t ignored : 1;
2077 uint32_t upgradable : 1;
2081 bool upgradable([self upgradableAndEssential:YES]);
2082 value.bits.upgradable = upgradable ? 1 : 0;
2085 value.bits.timestamp = 0;
2086 value.bits.ignored = [self ignored] ? 0 : 1;
2087 value.bits.upgradable = 1;
2089 value.bits.timestamp = [self seen] >> 2;
2090 value.bits.ignored = 0;
2091 value.bits.upgradable = 0;
2094 return _not(uint32_t) - value.key;
2097 uint32_t PackagePrefixRadix(Package *self, void *context) {
2098 size_t offset(reinterpret_cast<size_t>(context));
2099 CYString &name([self cyname]);
2101 size_t size(name.size());
2104 char *text(name.data());
2107 if (!isdigit(text[0]))
2111 while (size != digits && isdigit(text[digits]))
2119 if (offset == 0 && zeros != 0) {
2120 memset(data, '0', zeros);
2121 memcpy(data + zeros, text, 4 - zeros);
2123 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2124 if (size <= offset - zeros)
2127 text += offset - zeros;
2128 size -= offset - zeros;
2131 memcpy(data, text, 4);
2133 memcpy(data, text, size);
2134 memset(data + size, 0, 4 - size);
2137 for (size_t i(0); i != 4; ++i)
2138 if (isalpha(data[i]))
2146 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2148 /* XXX: ntohl may be more honest */
2149 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2152 CYString &(*PackageName)(Package *self, SEL sel);
2154 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2155 _profile(PackageNameCompare)
2156 CYString &lhi(PackageName(lhs, @selector(cyname)));
2157 CYString &rhi(PackageName(rhs, @selector(cyname)));
2158 CFStringRef lhn(lhi), rhn(rhi);
2161 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2162 else if (rhn == NULL)
2163 return NSOrderedDescending;
2165 _profile(PackageNameCompare$NumbersLast)
2166 if (!lhi.empty() && !rhi.empty()) {
2167 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2168 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2169 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2170 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2171 return lha ? NSOrderedAscending : NSOrderedDescending;
2175 CFIndex length = CFStringGetLength(lhn);
2177 _profile(PackageNameCompare$Compare)
2178 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2183 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2184 return PackageNameCompare(*lhs, *rhs, context);
2187 struct PackageNameOrdering :
2188 std::binary_function<Package *, Package *, bool>
2190 _finline bool operator ()(Package *lhs, Package *rhs) const {
2191 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2195 @implementation Package
2197 - (NSString *) description {
2198 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2202 if (parsed_ != NULL)
2211 + (NSString *) webScriptNameForSelector:(SEL)selector {
2213 else if (selector == @selector(clear))
2215 else if (selector == @selector(hasTag:))
2217 else if (selector == @selector(install))
2219 else if (selector == @selector(remove))
2225 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2226 return [self webScriptNameForSelector:selector] == nil;
2229 + (NSArray *) _attributeKeys {
2230 return [NSArray arrayWithObjects:
2248 @"shortDescription",
2259 - (NSArray *) attributeKeys {
2260 return [[self class] _attributeKeys];
2263 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2264 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2267 - (NSArray *) relations {
2268 @synchronized (database_) {
2269 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2270 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2271 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2276 if (parsed_ != NULL)
2278 @synchronized (database_) {
2279 if ([database_ era] != era_ || file_.end())
2282 ParsedPackage *parsed(new ParsedPackage);
2285 _profile(Package$parse)
2286 pkgRecords::Parser *parser;
2288 _profile(Package$parse$Lookup)
2289 parser = &[database_ records]->Lookup(file_);
2294 _profile(Package$parse$Find)
2299 {"icon", &parsed->icon_},
2300 {"depiction", &parsed->depiction_},
2301 {"homepage", &parsed->homepage_},
2302 {"website", &website},
2303 {"bugs", &parsed->bugs_},
2304 {"support", &parsed->support_},
2305 {"sponsor", &parsed->sponsor_},
2306 {"author", &parsed->author_},
2309 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2310 const char *start, *end;
2312 if (parser->Find(names[i].name_, start, end)) {
2313 CYString &value(*names[i].value_);
2314 _profile(Package$parse$Value)
2315 value.set(pool_, start, end - start);
2321 _profile(Package$parse$Tagline)
2322 const char *start, *end;
2323 if (parser->ShortDesc(start, end)) {
2324 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2327 while (stop != start && stop[-1] == '\r')
2329 parsed->tagline_.set(pool_, start, stop - start);
2333 _profile(Package$parse$Retain)
2334 if (parsed->homepage_.empty())
2335 parsed->homepage_ = website;
2336 if (parsed->homepage_ == parsed->depiction_)
2337 parsed->homepage_.clear();
2342 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2343 if ((self = [super init]) != nil) {
2344 _profile(Package$initWithVersion)
2347 database_ = database;
2348 era_ = [database era];
2352 pkgCache::PkgIterator iterator(version.ParentPkg());
2353 iterator_ = iterator;
2355 _profile(Package$initWithVersion$Version)
2356 if (!version_.end())
2357 file_ = version_.FileList();
2359 pkgCache &cache([database_ cache]);
2360 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2364 _profile(Package$initWithVersion$Cache)
2365 name_.set(NULL, iterator.Display());
2367 latest_.set(NULL, StripVersion_(version_.VerStr()));
2369 pkgCache::VerIterator current(iterator.CurrentVer());
2371 installed_.set(NULL, StripVersion_(current.VerStr()));
2374 _profile(Package$initWithVersion$Tags)
2375 pkgCache::TagIterator tag(iterator.TagList());
2377 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2379 const char *name(tag.Name());
2380 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2382 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2383 if (strcmp(name + 6, "enduser") == 0)
2385 else if (strcmp(name + 6, "hacker") == 0)
2387 else if (strcmp(name + 6, "developer") == 0)
2389 else if (strcmp(name + 6, "cydia") == 0)
2395 if (strncmp(name, "cydia::", 7) == 0) {
2396 if (strcmp(name + 7, "essential") == 0)
2398 else if (strcmp(name + 7, "obsolete") == 0)
2403 } while (!tag.end());
2407 _profile(Package$initWithVersion$Metadata)
2408 const char *mixed(iterator.Name());
2409 size_t size(strlen(mixed));
2410 char lower[size + 1];
2412 for (size_t i(0); i != size; ++i)
2413 lower[i] = mixed[i] | 0x20;
2416 PackageValue *metadata(PackageFind(lower, size));
2417 metadata_ = metadata;
2419 id_.set(NULL, metadata->name_, size);
2421 const char *latest(version_.VerStr());
2422 size_t length(strlen(latest));
2424 uint16_t vhash(hashlittle(latest, length));
2426 size_t capped(std::min<size_t>(8, length));
2427 latest = latest + length - capped;
2429 if (metadata->first_ == 0)
2430 metadata->first_ = now_;
2432 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2433 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2434 metadata->vhash_ = vhash;
2435 metadata->last_ = now_;
2436 } else if (metadata->last_ == 0)
2437 metadata->last_ = metadata->first_;
2440 _profile(Package$initWithVersion$Section)
2441 section_ = iterator.Section();
2444 _profile(Package$initWithVersion$Flags)
2445 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2446 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2451 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2452 pkgCache::VerIterator version;
2454 _profile(Package$packageWithIterator$GetCandidateVer)
2455 version = [database policy]->GetCandidateVer(iterator);
2463 _profile(Package$packageWithIterator$Allocate)
2464 package = [Package allocWithZone:zone];
2467 _profile(Package$packageWithIterator$Initialize)
2469 initWithVersion:version
2476 _profile(Package$packageWithIterator$Autorelease)
2477 package = [package autorelease];
2483 - (pkgCache::PkgIterator) iterator {
2487 - (NSString *) section {
2488 if (section$_ == nil) {
2489 if (section_ == NULL)
2492 _profile(Package$section$mappedSectionForPointer)
2493 section$_ = [database_ mappedSectionForPointer:section_];
2498 - (NSString *) simpleSection {
2499 if (NSString *section = [self section])
2500 return Simplify(section);
2505 - (NSString *) longSection {
2506 return LocalizeSection([self section]);
2509 - (NSString *) shortSection {
2510 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2513 - (NSString *) uri {
2516 pkgIndexFile *index;
2517 pkgCache::PkgFileIterator file(file_.File());
2518 if (![database_ list].FindIndex(file, index))
2520 return [NSString stringWithUTF8String:iterator_->Path];
2521 //return [NSString stringWithUTF8String:file.Site()];
2522 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2526 - (Address *) maintainer {
2527 @synchronized (database_) {
2528 if ([database_ era] != era_ || file_.end())
2531 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2532 const std::string &maintainer(parser->Maintainer());
2533 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2537 @synchronized (database_) {
2538 if ([database_ era] != era_ || version_.end())
2541 return version_->InstalledSize;
2544 - (NSString *) longDescription {
2545 @synchronized (database_) {
2546 if ([database_ era] != era_ || file_.end())
2549 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2550 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2552 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2553 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2554 if ([lines count] < 2)
2557 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2558 for (size_t i(1), e([lines count]); i != e; ++i) {
2559 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2560 [trimmed addObject:trim];
2563 return [trimmed componentsJoinedByString:@"\n"];
2566 - (NSString *) shortDescription {
2567 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2571 _profile(Package$index)
2572 CFStringRef name((CFStringRef) [self name]);
2573 if (CFStringGetLength(name) == 0)
2575 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2576 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2578 return toupper(character);
2582 - (PackageValue *) metadata {
2587 PackageValue *metadata([self metadata]);
2588 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2591 - (bool) subscribed {
2592 return [self metadata]->subscribed_;
2595 - (bool) setSubscribed:(bool)subscribed {
2596 PackageValue *metadata([self metadata]);
2597 if (metadata->subscribed_ == subscribed)
2599 metadata->subscribed_ = subscribed;
2607 - (NSString *) latest {
2611 - (NSString *) installed {
2615 - (BOOL) uninstalled {
2616 return installed_.empty();
2620 return !version_.end();
2623 - (BOOL) upgradableAndEssential:(BOOL)essential {
2624 _profile(Package$upgradableAndEssential)
2625 pkgCache::VerIterator current(iterator_.CurrentVer());
2627 return essential && essential_;
2629 return !version_.end() && version_ != current;
2633 - (BOOL) essential {
2638 return [database_ cache][iterator_].InstBroken();
2641 - (BOOL) unfiltered {
2642 _profile(Package$unfiltered$obsolete)
2643 if (_unlikely(obsolete_))
2647 _profile(Package$unfiltered$hasSupportingRole)
2648 if (_unlikely(![self hasSupportingRole]))
2656 if (![self unfiltered])
2661 _profile(Package$visible$section)
2662 section = [self section];
2665 _profile(Package$visible$isSectionVisible)
2666 if (!isSectionVisible(section))
2674 unsigned char current(iterator_->CurrentState);
2675 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2678 - (BOOL) halfConfigured {
2679 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2682 - (BOOL) halfInstalled {
2683 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2687 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2688 return state.Mode != pkgDepCache::ModeKeep;
2691 - (NSString *) mode {
2692 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2694 switch (state.Mode) {
2695 case pkgDepCache::ModeDelete:
2696 if ((state.iFlags & pkgDepCache::Purge) != 0)
2700 case pkgDepCache::ModeKeep:
2701 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2702 return @"REINSTALL";
2703 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2707 case pkgDepCache::ModeInstall:
2708 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2709 return @"REINSTALL";
2710 else*/ switch (state.Status) {
2712 return @"DOWNGRADE";
2718 return @"NEW_INSTALL";
2729 - (NSString *) name {
2730 return name_.empty() ? id_ : name_;
2733 - (UIImage *) icon {
2734 NSString *section = [self simpleSection];
2737 if (parsed_ != NULL)
2738 if (NSString *href = parsed_->icon_)
2739 if ([href hasPrefix:@"file:///"])
2740 // XXX: correct escaping
2741 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2742 if (icon == nil) if (section != nil)
2743 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2744 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2745 if ([dicon hasPrefix:@"file:///"])
2746 // XXX: correct escaping
2747 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2749 icon = [UIImage applicationImageNamed:@"unknown.png"];
2753 - (NSString *) homepage {
2754 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2757 - (NSString *) depiction {
2758 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2761 - (Address *) sponsor {
2762 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2765 - (Address *) author {
2766 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2769 - (NSString *) support {
2770 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2773 - (NSArray *) files {
2774 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2775 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2778 fin.open([path UTF8String]);
2783 while (std::getline(fin, line))
2784 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2789 - (NSArray *) warnings {
2790 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2791 const char *name(iterator_.Name());
2793 size_t length(strlen(name));
2794 if (length < 2) invalid:
2795 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2796 else for (size_t i(0); i != length; ++i)
2798 /* XXX: technically this is not allowed */
2799 (name[i] < 'A' || name[i] > 'Z') &&
2800 (name[i] < 'a' || name[i] > 'z') &&
2801 (name[i] < '0' || name[i] > '9') &&
2802 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2805 if (strcmp(name, "cydia") != 0) {
2808 bool _private = false;
2811 bool repository = [[self section] isEqualToString:@"Repositories"];
2813 if (NSArray *files = [self files])
2814 for (NSString *file in files)
2815 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2817 else if (!user && [file isEqualToString:@"/User"])
2819 else if (!_private && [file isEqualToString:@"/private"])
2821 else if (!stash && [file isEqualToString:@"/var/stash"])
2824 /* XXX: this is not sensitive enough. only some folders are valid. */
2825 if (cydia && !repository)
2826 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2828 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2830 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2832 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2835 return [warnings count] == 0 ? nil : warnings;
2838 - (NSArray *) applications {
2839 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2841 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2843 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2844 if (NSArray *files = [self files])
2845 for (NSString *file in files)
2846 if (application_r(file)) {
2847 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2848 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2849 if ([id isEqualToString:me])
2852 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2854 display = application_r[1];
2856 NSString *bundle([file stringByDeletingLastPathComponent]);
2857 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2858 if (icon == nil || [icon length] == 0)
2860 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2862 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2863 [applications addObject:application];
2865 [application addObject:id];
2866 [application addObject:display];
2867 [application addObject:url];
2870 return [applications count] == 0 ? nil : applications;
2873 - (Source *) source {
2874 if (source_ == nil) {
2875 @synchronized (database_) {
2876 if ([database_ era] != era_ || file_.end())
2877 source_ = (Source *) [NSNull null];
2879 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2883 return source_ == (Source *) [NSNull null] ? nil : source_;
2886 - (BOOL) matches:(NSString *)text {
2892 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2893 if (range.location != NSNotFound)
2896 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2897 if (range.location != NSNotFound)
2902 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2903 if (range.location != NSNotFound)
2909 - (bool) hasSupportingRole {
2914 if ([Role_ isEqualToString:@"User"])
2918 if ([Role_ isEqualToString:@"Hacker"])
2922 if ([Role_ isEqualToString:@"Developer"])
2927 - (BOOL) hasTag:(NSString *)tag {
2928 return tags_ == nil ? NO : [tags_ containsObject:tag];
2931 - (NSString *) primaryPurpose {
2932 for (NSString *tag in tags_)
2933 if ([tag hasPrefix:@"purpose::"])
2934 return [tag substringFromIndex:9];
2938 - (NSArray *) purposes {
2939 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2940 for (NSString *tag in tags_)
2941 if ([tag hasPrefix:@"purpose::"])
2942 [purposes addObject:[tag substringFromIndex:9]];
2943 return [purposes count] == 0 ? nil : purposes;
2946 - (bool) isCommercial {
2947 return [self hasTag:@"cydia::commercial"];
2950 - (void) setIndex:(size_t)index {
2951 if (metadata_->index_ != index)
2952 metadata_->index_ = index;
2955 - (CYString &) cyname {
2956 return name_.empty() ? id_ : name_;
2959 - (uint32_t) compareBySection:(NSArray *)sections {
2960 NSString *section([self section]);
2961 for (size_t i(0), e([sections count]); i != e; ++i) {
2962 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2966 return _not(uint32_t);
2970 @synchronized (database_) {
2971 pkgProblemResolver *resolver = [database_ resolver];
2972 resolver->Clear(iterator_);
2974 pkgCacheFile &cache([database_ cache]);
2975 cache->SetReInstall(iterator_, false);
2976 cache->MarkKeep(iterator_, false);
2980 @synchronized (database_) {
2981 pkgProblemResolver *resolver = [database_ resolver];
2982 resolver->Clear(iterator_);
2983 resolver->Protect(iterator_);
2985 pkgCacheFile &cache([database_ cache]);
2986 cache->SetReInstall(iterator_, false);
2987 cache->MarkInstall(iterator_, false);
2989 pkgDepCache::StateCache &state((*cache)[iterator_]);
2990 if (!state.Install())
2991 cache->SetReInstall(iterator_, true);
2995 @synchronized (database_) {
2996 pkgProblemResolver *resolver = [database_ resolver];
2997 resolver->Clear(iterator_);
2998 resolver->Remove(iterator_);
2999 resolver->Protect(iterator_);
3001 pkgCacheFile &cache([database_ cache]);
3002 cache->SetReInstall(iterator_, false);
3003 cache->MarkDelete(iterator_, true);
3006 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3007 _profile(Package$isUnfilteredAndSearchedForBy)
3010 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3011 value &= [self unfiltered];
3014 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3015 value &= [self matches:search];
3022 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3023 if ([search length] == 0)
3026 _profile(Package$isUnfilteredAndSelectedForBy)
3029 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3030 value &= [self unfiltered];
3033 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3034 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3041 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3042 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3045 - (bool) isVisibleInSection:(NSString *)name {
3046 NSString *section([self section]);
3050 section == nil && [name length] == 0 ||
3051 [name isEqualToString:section]
3052 ) && [self visible];
3055 - (bool) isVisibleInSource:(Source *)source {
3056 return [self source] == source && [self visible];
3061 /* Section Class {{{ */
3062 @interface Section : NSObject {
3067 NSString *localized_;
3070 - (NSComparisonResult) compareByLocalized:(Section *)section;
3071 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3072 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3073 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3074 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3075 - (NSString *) name;
3082 - (void) addToCount;
3084 - (void) setCount:(size_t)count;
3085 - (NSString *) localized;
3089 @implementation Section
3093 if (localized_ != nil)
3094 [localized_ release];
3098 - (NSComparisonResult) compareByLocalized:(Section *)section {
3099 NSString *lhs(localized_);
3100 NSString *rhs([section localized]);
3102 /*if ([lhs length] != 0 && [rhs length] != 0) {
3103 unichar lhc = [lhs characterAtIndex:0];
3104 unichar rhc = [rhs characterAtIndex:0];
3106 if (isalpha(lhc) && !isalpha(rhc))
3107 return NSOrderedAscending;
3108 else if (!isalpha(lhc) && isalpha(rhc))
3109 return NSOrderedDescending;
3112 return [lhs compare:rhs options:LaxCompareOptions_];
3115 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3116 if ((self = [self initWithName:name localize:NO]) != nil) {
3117 if (localized != nil)
3118 localized_ = [localized retain];
3122 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3123 return [self initWithName:name row:0 localize:localize];
3126 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3127 if ((self = [super init]) != nil) {
3128 name_ = [name retain];
3132 localized_ = [LocalizeSection(name_) retain];
3136 /* XXX: localize the index thingees */
3137 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3138 if ((self = [super init]) != nil) {
3139 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3145 - (NSString *) name {
3165 - (void) addToCount {
3169 - (void) setCount:(size_t)count {
3173 - (NSString *) localized {
3180 static NSString *Colon_;
3181 static NSString *Elision_;
3182 static NSString *Error_;
3183 static NSString *Warning_;
3185 /* Database Implementation {{{ */
3186 @implementation Database
3188 + (Database *) sharedInstance {
3189 static Database *instance;
3190 if (instance == nil)
3191 instance = [[Database alloc] init];
3199 - (void) releasePackages {
3200 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3201 CFArrayRemoveAllValues(packages_);
3205 // XXX: actually implement this thing
3207 [sourceList_ release];
3208 [self releasePackages];
3209 apr_pool_destroy(pool_);
3210 NSRecycleZone(zone_);
3214 - (void) _readCydia:(NSNumber *)fd { _pooled
3215 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3216 std::istream is(&ib);
3219 static Pcre finish_r("^finish:([^:]*)$");
3221 while (std::getline(is, line)) {
3222 const char *data(line.c_str());
3223 size_t size = line.size();
3224 lprintf("C:%s\n", data);
3226 if (finish_r(data, size)) {
3227 NSString *finish = finish_r[1];
3228 int index = [Finishes_ indexOfObject:finish];
3229 if (index != INT_MAX && index > Finish_)
3237 - (void) _readStatus:(NSNumber *)fd { _pooled
3238 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3239 std::istream is(&ib);
3242 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3243 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3245 while (std::getline(is, line)) {
3246 const char *data(line.c_str());
3247 size_t size(line.size());
3248 lprintf("S:%s\n", data);
3250 if (conffile_r(data, size)) {
3251 [delegate_ setConfigurationData:conffile_r[1]];
3252 } else if (strncmp(data, "status: ", 8) == 0) {
3253 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3254 [delegate_ setProgressTitle:string];
3255 } else if (pmstatus_r(data, size)) {
3256 std::string type([pmstatus_r[1] UTF8String]);
3257 NSString *id = pmstatus_r[2];
3259 float percent([pmstatus_r[3] floatValue]);
3260 [delegate_ setProgressPercent:(percent / 100)];
3262 NSString *string = pmstatus_r[4];
3264 if (type == "pmerror")
3265 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3266 withObject:[NSArray arrayWithObjects:string, id, nil]
3269 else if (type == "pmstatus") {
3270 [delegate_ setProgressTitle:string];
3271 } else if (type == "pmconffile")
3272 [delegate_ setConfigurationData:string];
3274 lprintf("E:unknown pmstatus\n");
3276 lprintf("E:unknown status\n");
3282 - (void) _readOutput:(NSNumber *)fd { _pooled
3283 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3284 std::istream is(&ib);
3287 while (std::getline(is, line)) {
3288 lprintf("O:%s\n", line.c_str());
3289 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3299 - (Package *) packageWithName:(NSString *)name {
3300 @synchronized (self) {
3301 if (static_cast<pkgDepCache *>(cache_) == NULL)
3303 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3304 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3308 if ((self = [super init]) != nil) {
3315 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3316 apr_pool_create(&pool_, NULL);
3318 size_t capacity(MetaFile_->active_);
3324 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3325 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3329 _assert(pipe(fds) != -1);
3332 _config->Set("APT::Keep-Fds::", cydiafd_);
3333 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3336 detachNewThreadSelector:@selector(_readCydia:)
3338 withObject:[NSNumber numberWithInt:fds[0]]
3341 _assert(pipe(fds) != -1);
3345 detachNewThreadSelector:@selector(_readStatus:)
3347 withObject:[NSNumber numberWithInt:fds[0]]
3350 _assert(pipe(fds) != -1);
3351 _assert(dup2(fds[0], 0) != -1);
3352 _assert(close(fds[0]) != -1);
3354 input_ = fdopen(fds[1], "a");
3356 _assert(pipe(fds) != -1);
3357 _assert(dup2(fds[1], 1) != -1);
3358 _assert(close(fds[1]) != -1);
3361 detachNewThreadSelector:@selector(_readOutput:)
3363 withObject:[NSNumber numberWithInt:fds[0]]
3368 - (pkgCacheFile &) cache {
3372 - (pkgDepCache::Policy *) policy {
3376 - (pkgRecords *) records {
3380 - (pkgProblemResolver *) resolver {
3384 - (pkgAcquire &) fetcher {
3388 - (pkgSourceList &) list {
3392 - (NSArray *) packages {
3393 return (NSArray *) packages_;
3396 - (NSArray *) sources {
3400 - (Source *) sourceWithKey:(NSString *)key {
3401 for (Source *source in [self sources]) {
3402 if ([[source key] isEqualToString:key])
3407 - (bool) popErrorWithTitle:(NSString *)title {
3409 std::string message;
3411 while (!_error->empty()) {
3413 bool warning(!_error->PopMessage(error));
3417 size_t size(error.size());
3418 if (size == 0 || error[size - 1] != '\n')
3420 error.resize(size - 1);
3422 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3424 if (!message.empty())
3429 if (fatal && !message.empty())
3430 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3435 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3436 return [self popErrorWithTitle:title] || !success;
3439 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3440 @synchronized (self) {
3443 [self releasePackages];
3446 [sourceList_ removeAllObjects];
3466 apr_pool_clear(pool_);
3468 NSRecycleZone(zone_);
3469 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3471 int chk(creat("/tmp/cydia.chk", 0644));
3475 if (invocation != nil)
3476 [invocation invoke];
3478 NSString *title(UCLocalize("DATABASE"));
3481 while (!cache_.Open(progress_, true)) { pop:
3483 bool warning(!_error->PopMessage(error));
3484 lprintf("cache_.Open():[%s]\n", error.c_str());
3486 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3487 [delegate_ repairWithSelector:@selector(configure)];
3488 else if (error == "The package lists or status file could not be parsed or opened.")
3489 [delegate_ repairWithSelector:@selector(update)];
3490 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3491 else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3492 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, Error_, title]];
3493 // else if (error == "The list of sources could not be read.")
3495 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3505 unlink("/tmp/cydia.chk");
3507 now_ = [[NSDate date] timeIntervalSince1970];
3509 policy_ = new pkgDepCache::Policy();
3510 records_ = new pkgRecords(cache_);
3511 resolver_ = new pkgProblemResolver(cache_);
3512 fetcher_ = new pkgAcquire(&status_);
3515 list_ = new pkgSourceList();
3516 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3519 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3520 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3524 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3527 if (cache_->BrokenCount() != 0) {
3528 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3531 if (cache_->BrokenCount() != 0) {
3532 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3536 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3540 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3541 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3542 [sourceList_ addObject:object];
3544 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3545 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3546 // XXX: this could be more intelligent
3547 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3548 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3550 sourceMap_[cached->ID] = object;
3555 /*std::vector<Package *> packages;
3556 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3557 [packages_ release];
3562 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3563 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3564 //packages.push_back(package);
3565 CFArrayAppendValue(packages_, [package retain]);
3569 /*if (packages.empty())
3570 packages_ = [[NSArray alloc] init];
3572 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3575 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3576 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3577 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3585 /*if (!packages.empty())
3586 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3587 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3589 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3591 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3593 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3597 size_t count(CFArrayGetCount(packages_));
3598 MetaFile_->active_ = count;
3600 for (size_t index(0); index != count; ++index)
3601 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3605 } } CYPoolEnd() _trace(); }
3608 @synchronized (self) {
3610 resolver_ = new pkgProblemResolver(cache_);
3612 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3613 if (!cache_[iterator].Keep())
3614 cache_->MarkKeep(iterator, false);
3615 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3616 cache_->SetReInstall(iterator, false);
3619 - (void) configure {
3620 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3622 system([dpkg UTF8String]);
3627 // XXX: I don't remember this condition
3632 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3634 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3636 if ([self popErrorWithTitle:title])
3640 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3643 public pkgArchiveCleaner
3646 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3651 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3658 fetcher_->Shutdown();
3660 pkgRecords records(cache_);
3662 lock_ = new FileFd();
3663 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3665 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3667 if ([self popErrorWithTitle:title])
3671 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3674 manager_ = (_system->CreatePM(cache_));
3675 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3682 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3684 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3686 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3688 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3689 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3692 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3697 [CydiaApp retainNetworkActivityIndicator];
3699 bool failed = false;
3700 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3701 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3703 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3706 std::string uri = (*item)->DescURI();
3707 std::string error = (*item)->ErrorText;
3709 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3712 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3713 withObject:[NSArray arrayWithObjects:
3714 [NSString stringWithUTF8String:error.c_str()],
3720 [CydiaApp releaseNetworkActivityIndicator];
3728 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3730 if (_error->PendingError()) {
3735 if (result == pkgPackageManager::Failed) {
3740 if (result != pkgPackageManager::Completed) {
3745 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3747 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3749 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3750 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3753 if (![before isEqualToArray:after])
3758 NSString *title(UCLocalize("UPGRADE"));
3759 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3765 [self updateWithStatus:status_];
3768 - (void) updateWithStatus:(Status &)status {
3769 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3770 NSString *title(UCLocalize("REFRESHING_DATA"));
3773 if (!list.ReadMainList())
3774 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3777 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3778 if ([self popErrorWithTitle:title])
3781 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3782 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3783 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3785 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3789 - (void) setDelegate:(id)delegate {
3790 delegate_ = delegate;
3791 status_.setDelegate(delegate);
3792 progress_.setDelegate(delegate);
3795 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3796 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3797 return i == sourceMap_.end() ? nil : i->second;
3800 - (NSString *) mappedSectionForPointer:(const char *)section {
3801 _H<NSString> *mapped;
3803 _profile(Database$mappedSectionForPointer$Cache)
3804 mapped = §ions_[section];
3807 if (*mapped == NULL) {
3808 size_t length(strlen(section));
3809 char spaced[length + 1];
3811 _profile(Database$mappedSectionForPointer$Replace)
3812 for (size_t index(0); index != length; ++index)
3813 spaced[index] = section[index] == '_' ? ' ' : section[index];
3814 spaced[length] = '\0';
3819 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3820 string = [NSString stringWithUTF8String:spaced];
3823 _profile(Database$mappedSectionForPointer$Map)
3824 string = [SectionMap_ objectForKey:string] ?: string;
3834 /* Web Scripting {{{ */
3835 @interface CydiaObject : NSObject {
3837 _transient id delegate_;
3840 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3844 @implementation CydiaObject
3847 [indirect_ release];
3851 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3852 if ((self = [super init]) != nil) {
3853 indirect_ = [indirect retain];
3857 - (void) setDelegate:(id)delegate {
3858 delegate_ = delegate;
3861 + (NSArray *) _attributeKeys {
3862 return [NSArray arrayWithObjects:
3872 - (NSArray *) attributeKeys {
3873 return [[self class] _attributeKeys];
3876 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3877 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3880 - (NSString *) device {
3881 return [[UIDevice currentDevice] uniqueIdentifier];
3884 - (NSString *) plmn {
3888 - (NSString *) ecid {
3892 - (NSString *) serial {
3893 return SerialNumber_;
3896 - (NSString *) role {
3900 - (NSString *) model {
3901 return [NSString stringWithUTF8String:Machine_];
3904 + (NSString *) webScriptNameForSelector:(SEL)selector {
3906 else if (selector == @selector(addTrivialSource:))
3907 return @"addTrivialSource";
3908 else if (selector == @selector(close))
3910 else if (selector == @selector(du:))
3912 else if (selector == @selector(stringWithFormat:arguments:))
3914 else if (selector == @selector(getAllSources))
3915 return @"getAllSourcs";
3916 else if (selector == @selector(getKernelNumber:))
3917 return @"getKernelNumber";
3918 else if (selector == @selector(getKernelString:))
3919 return @"getKernelString";
3920 else if (selector == @selector(getInstalledPackages))
3921 return @"getInstalledPackages";
3922 else if (selector == @selector(getPackageById:))
3923 return @"getPackageById";
3924 else if (selector == @selector(installPackages:))
3925 return @"installPackages";
3926 else if (selector == @selector(localizedStringForKey:value:table:))
3928 else if (selector == @selector(refreshSources))
3929 return @"refreshSources";
3930 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3931 return @"setButtonImage";
3932 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3933 return @"setButtonTitle";
3934 else if (selector == @selector(setPopupHook:))
3935 return @"setPopupHook";
3936 else if (selector == @selector(setSpecial:))
3937 return @"setSpecial";
3938 else if (selector == @selector(setToken:))
3940 else if (selector == @selector(setViewportWidth:))
3941 return @"setViewportWidth";
3942 else if (selector == @selector(statfs:))
3944 else if (selector == @selector(supports:))
3950 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3951 return [self webScriptNameForSelector:selector] == nil;
3954 - (BOOL) supports:(NSString *)feature {
3955 return [feature isEqualToString:@"window.open"];
3958 - (NSNumber *) getKernelNumber:(NSString *)name {
3959 const char *string([name UTF8String]);
3962 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3963 return (id) [NSNull null];
3965 if (size != sizeof(int))
3966 return (id) [NSNull null];
3969 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3970 return (id) [NSNull null];
3972 return [NSNumber numberWithInt:value];
3975 - (NSString *) getKernelString:(NSString *)name {
3976 const char *string([name UTF8String]);
3979 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3980 return (id) [NSNull null];
3982 char value[size + 1];
3983 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3984 return (id) [NSNull null];
3986 // XXX: just in case you request something ludicrous
3989 return [NSString stringWithCString:value];
3992 - (void) addTrivialSource:(NSString *)href {
3993 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
3996 - (void) refreshSources {
3997 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4000 - (NSArray *) getAllSources {
4001 return [[Database sharedInstance] sources];
4004 - (NSArray *) getInstalledPackages {
4005 NSArray *packages([[Database sharedInstance] packages]);
4006 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4007 for (Package *package in packages)
4008 if ([package installed] != nil)
4009 [installed addObject:package];
4013 - (Package *) getPackageById:(NSString *)id {
4014 Package *package([[Database sharedInstance] packageWithName:id]);
4019 - (NSArray *) statfs:(NSString *)path {
4022 if (path == nil || statfs([path UTF8String], &stat) == -1)
4025 return [NSArray arrayWithObjects:
4026 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4027 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4028 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4032 - (NSNumber *) du:(NSString *)path {
4033 NSNumber *value(nil);
4036 _assert(pipe(fds) != -1);
4038 pid_t pid(ExecFork());
4040 _assert(dup2(fds[1], 1) != -1);
4041 _assert(close(fds[0]) != -1);
4042 _assert(close(fds[1]) != -1);
4043 /* XXX: this should probably not use du */
4044 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4049 _assert(close(fds[1]) != -1);
4051 if (FILE *du = fdopen(fds[0], "r")) {
4053 while (fgets(line, sizeof(line), du) != NULL) {
4054 size_t length(strlen(line));
4055 while (length != 0 && line[length - 1] == '\n')
4056 line[--length] = '\0';
4057 if (char *tab = strchr(line, '\t')) {
4059 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4064 } else _assert(close(fds[0]));
4068 if (waitpid(pid, &status, 0) == -1)
4071 else _assert(false);
4080 - (void) installPackages:(NSArray *)packages {
4081 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4084 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4085 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4088 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4089 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4092 - (void) setSpecial:(id)function {
4093 [indirect_ setSpecial:function];
4096 - (void) setToken:(NSString *)token {
4099 Token_ = [token retain];
4101 [Metadata_ setObject:Token_ forKey:@"Token"];
4105 - (void) setPopupHook:(id)function {
4106 [indirect_ setPopupHook:function];
4109 - (void) setViewportWidth:(float)width {
4110 [indirect_ setViewportWidth:width];
4113 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4114 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4115 unsigned count([arguments count]);
4117 for (unsigned i(0); i != count; ++i)
4118 values[i] = [arguments objectAtIndex:i];
4119 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4122 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4123 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4125 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4127 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4133 /* @ Loading... Indicator {{{ */
4134 @interface CYLoadingIndicator : UIView {
4135 UIActivityIndicatorView *spinner_;
4140 @property (readonly, nonatomic) UILabel *label;
4141 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4145 @implementation CYLoadingIndicator
4147 - (id) initWithFrame:(CGRect)frame {
4148 if ((self = [super initWithFrame:frame]) != nil) {
4149 container_ = [[[UIView alloc] init] autorelease];
4150 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4152 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4153 [spinner_ startAnimating];
4154 [container_ addSubview:spinner_];
4156 label_ = [[[UILabel alloc] init] autorelease];
4157 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4158 [label_ setBackgroundColor:[UIColor clearColor]];
4159 [label_ setTextColor:[UIColor blackColor]];
4160 [label_ setShadowColor:[UIColor whiteColor]];
4161 [label_ setShadowOffset:CGSizeMake(0, 1)];
4162 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4163 [container_ addSubview:label_];
4165 CGSize viewsize = frame.size;
4166 CGSize spinnersize = [spinner_ bounds].size;
4167 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4168 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4170 CGRect containrect = {
4171 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4172 CGSizeMake(bothwidth, spinnersize.height)
4175 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4183 [container_ setFrame:containrect];
4184 [spinner_ setFrame:spinrect];
4185 [label_ setFrame:textrect];
4186 [self addSubview:container_];
4190 - (UILabel *) label {
4194 - (UIActivityIndicatorView *) activityIndicatorView {
4200 /* Emulated Loading Controller {{{ */
4201 @interface CYEmulatedLoadingController : CYViewController <
4203 ConfigurationDelegate
4205 _transient Database *database_;
4206 CYLoadingIndicator *indicator_;
4208 UINavigationBar *navbar_;
4213 @implementation CYEmulatedLoadingController
4216 [self releaseSubviews];
4217 [database_ setDelegate:nil];
4222 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4223 CYAlertView *sheet([[[CYAlertView alloc]
4225 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4226 defaultButtonIndex:0
4229 [sheet setMessage:error];
4230 [sheet yieldToPopupAlertAnimated:YES];
4234 - (void) setProgressTitle:(NSString *)title { }
4235 - (void) setProgressPercent:(float)percent { }
4236 - (void) startProgress { }
4237 - (void) addProgressOutput:(NSString *)output { }
4238 - (bool) isCancelling:(size_t)received { return NO; }
4239 - (void) setConfigurationData:(NSString *)data { }
4241 - (void) repairWithSelector:(SEL)selector {
4242 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("REPAIRING"), nil] waitUntilDone:YES];
4243 [database_ performSelector:selector];
4245 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil] waitUntilDone:YES];
4248 - (id) initWithDatabase:(Database *)database {
4249 if ((self = [super init]) != nil) {
4250 database_ = database;
4251 [database_ setDelegate:self];
4256 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4257 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4259 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4260 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4261 [[self view] addSubview:indicator_];
4263 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4264 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4265 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4266 [[self view] addSubview:tabbar_];
4268 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4269 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4270 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4271 [[self view] addSubview:navbar_];
4274 - (void) releaseSubviews {
4275 [indicator_ release];
4288 /* Cydia Browser Controller {{{ */
4289 @interface CYBrowserController : BrowserController {
4290 CydiaObject *cydia_;
4295 @implementation CYBrowserController
4302 - (NSURL *) navigationURL {
4303 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4306 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4309 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4310 [super webView:view didClearWindowObject:window forFrame:frame];
4312 WebDataSource *source([frame dataSource]);
4313 NSURLResponse *response([source response]);
4315 NSURL *url([response URL]);
4316 NSString *scheme([url scheme]);
4317 NSString *host([url host]);
4319 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4320 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4321 NSDictionary *headers([http allHeaderFields]);
4322 [self setHeaders:headers forHost:host];
4326 [host isEqualToString:@"cydia.saurik.com"] ||
4327 [host hasSuffix:@".cydia.saurik.com"] ||
4328 [scheme isEqualToString:@"file"]
4330 [window setValue:cydia_ forKey:@"cydia"];
4333 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4334 if (System_ != NULL)
4335 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4336 if (Machine_ != NULL)
4337 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4339 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4341 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4344 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4345 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4346 [self _setMoreHeaders:copy];
4350 - (void) setDelegate:(id)delegate {
4351 [super setDelegate:delegate];
4352 [cydia_ setDelegate:delegate];
4356 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4357 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4359 WebView *webview([[webview_ _documentView] webView]);
4361 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4363 NSString *application = package == nil ? @"Cydia" : [NSString
4364 stringWithFormat:@"Cydia/%@",
4369 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4371 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4372 if (Product_ != nil)
4373 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4375 [webview setApplicationNameForUserAgent:application];
4383 @interface NSObject (CydiaScript)
4384 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4387 @implementation NSObject (CydiaScript)
4389 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4395 @implementation NSArray (CydiaScript)
4397 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4398 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4399 for (size_t i(0), e([self count]); i != e; ++i)
4400 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4406 @implementation NSDictionary (CydiaScript)
4408 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4409 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4411 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4418 /* Confirmation Controller {{{ */
4419 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4420 if (!iterator.end())
4421 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4422 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4424 pkgCache::PkgIterator package(dep.TargetPkg());
4427 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4434 @protocol ConfirmationControllerDelegate
4435 - (void) cancelAndClear:(bool)clear;
4436 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4440 @interface ConfirmationController : CYBrowserController {
4441 _transient Database *database_;
4443 UIAlertView *essential_;
4445 NSDictionary *changes_;
4446 NSMutableArray *issues_;
4447 NSDictionary *sizes_;
4452 - (id) initWithDatabase:(Database *)database;
4456 @implementation ConfirmationController
4463 if (essential_ != nil)
4464 [essential_ release];
4469 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4470 NSString *context([alert context]);
4472 if ([context isEqualToString:@"remove"]) {
4473 if (button == [alert cancelButtonIndex]) {
4474 [self dismissModalViewControllerAnimated:YES];
4475 } else if (button == [alert firstOtherButtonIndex]) {
4478 [delegate_ confirmWithNavigationController:[self navigationController]];
4481 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4482 } else if ([context isEqualToString:@"unable"]) {
4483 [self dismissModalViewControllerAnimated:YES];
4484 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4486 [super alertView:alert clickedButtonAtIndex:button];
4490 - (void) _doContinue {
4491 [self dismissModalViewControllerAnimated:YES];
4492 [delegate_ cancelAndClear:NO];
4495 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4496 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4500 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4501 [super webView:view didClearWindowObject:window forFrame:frame];
4503 [window setValue:[changes_ Cydia$webScriptObjectInContext:window] forKey:@"changes"];
4504 [window setValue:[issues_ Cydia$webScriptObjectInContext:window] forKey:@"issues"];
4505 [window setValue:[sizes_ Cydia$webScriptObjectInContext:window] forKey:@"sizes"];
4507 [window setValue:self forKey:@"queue"];
4510 - (id) initWithDatabase:(Database *)database {
4511 if ((self = [super init]) != nil) {
4512 database_ = database;
4514 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4515 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4516 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4517 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4518 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4522 pkgCacheFile &cache([database_ cache]);
4523 NSArray *packages([database_ packages]);
4524 pkgDepCache::Policy *policy([database_ policy]);
4526 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4528 for (Package *package in packages) {
4529 pkgCache::PkgIterator iterator([package iterator]);
4530 NSString *name([package id]);
4532 if ([package broken]) {
4533 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4535 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4537 reasons, @"reasons",
4540 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4544 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4545 pkgCache::DepIterator start;
4546 pkgCache::DepIterator end;
4547 dep.GlobOr(start, end); // ++dep
4549 if (!cache->IsImportantDep(end))
4551 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4554 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4556 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4557 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4558 clauses, @"clauses",
4562 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4564 pkgCache::PkgIterator target(start.TargetPkg());
4565 if (target->ProvidesList != 0)
4566 reason = @"missing";
4568 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4570 reason = @"installed";
4571 installed = [NSString stringWithUTF8String:ver.VerStr()];
4572 } else if (!cache[target].CandidateVerIter(cache).end())
4573 reason = @"uninstalled";
4574 else if (target->ProvidesList == 0)
4575 reason = @"uninstallable";
4577 reason = @"virtual";
4580 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4581 [NSString stringWithUTF8String:start.CompType()], @"operator",
4582 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4585 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4586 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4587 version, @"version",
4589 installed, @"installed",
4592 // yes, seriously. (wtf?)
4600 pkgDepCache::StateCache &state(cache[iterator]);
4602 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4604 if (state.NewInstall())
4605 [installs addObject:name];
4606 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4607 [reinstalls addObject:name];
4608 else if (state.Upgrade())
4609 [upgrades addObject:name];
4610 else if (state.Downgrade())
4611 [downgrades addObject:name];
4612 else if (!state.Delete())
4614 else if (special_r(name))
4615 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4616 [NSNull null], @"package",
4617 [NSArray arrayWithObjects:
4618 [NSDictionary dictionaryWithObjectsAndKeys:
4619 @"Conflicts", @"relationship",
4620 [NSArray arrayWithObjects:
4621 [NSDictionary dictionaryWithObjectsAndKeys:
4623 [NSNull null], @"version",
4624 @"installed", @"reason",
4631 if ([package essential])
4633 [removes addObject:name];
4636 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4637 substrate_ |= DepSubstrate(iterator.CurrentVer());
4642 else if (Advanced_) {
4643 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4645 essential_ = [[UIAlertView alloc]
4646 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4647 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4649 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4651 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4655 [essential_ setContext:@"remove"];
4657 essential_ = [[UIAlertView alloc]
4658 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4659 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4661 cancelButtonTitle:UCLocalize("OKAY")
4662 otherButtonTitles:nil
4665 [essential_ setContext:@"unable"];
4668 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4669 installs, @"installs",
4670 reinstalls, @"reinstalls",
4671 upgrades, @"upgrades",
4672 downgrades, @"downgrades",
4673 removes, @"removes",
4676 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4677 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4678 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4681 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4683 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4684 initWithTitle:UCLocalize("CANCEL")
4685 style:UIBarButtonItemStylePlain
4687 action:@selector(cancelButtonClicked)
4693 - (void) applyRightButton {
4694 if ([issues_ count] == 0 && ![self isLoading])
4695 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4696 initWithTitle:UCLocalize("CONFIRM")
4697 style:UIBarButtonItemStyleDone
4699 action:@selector(confirmButtonClicked)
4702 [[self navigationItem] setRightBarButtonItem:nil];
4706 - (void) cancelButtonClicked {
4707 [self dismissModalViewControllerAnimated:YES];
4708 [delegate_ cancelAndClear:YES];
4712 - (void) confirmButtonClicked {
4713 if (essential_ != nil)
4718 [delegate_ confirmWithNavigationController:[self navigationController]];
4726 /* Progress Data {{{ */
4727 @interface ProgressData : NSObject {
4729 // XXX: should these really both be _transient?
4730 _transient id target_;
4731 _transient id object_;
4734 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4742 @implementation ProgressData
4744 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4745 if ((self = [super init]) != nil) {
4746 selector_ = selector;
4766 /* Progress Controller {{{ */
4767 @interface ProgressController : CYViewController <
4768 ConfigurationDelegate,
4771 _transient Database *database_;
4772 UIProgressBar *progress_;
4773 UITextView *output_;
4774 UITextLabel *status_;
4775 UIPushButton *close_;
4777 SHA1SumValue springlist_;
4778 SHA1SumValue notifyconf_;
4782 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4784 - (void) _retachThread;
4785 - (void) _detachNewThreadData:(ProgressData *)data;
4786 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4792 @protocol ProgressControllerDelegate
4793 - (void) progressControllerIsComplete:(ProgressController *)sender;
4796 @implementation ProgressController
4799 [database_ setDelegate:nil];
4800 [progress_ release];
4809 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4810 if ((self = [super init]) != nil) {
4811 database_ = database;
4812 [database_ setDelegate:self];
4813 delegate_ = delegate;
4815 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4817 progress_ = [[UIProgressBar alloc] init];
4818 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4819 [progress_ setStyle:0];
4821 status_ = [[UITextLabel alloc] init];
4822 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4823 [status_ setColor:[UIColor whiteColor]];
4824 [status_ setBackgroundColor:[UIColor clearColor]];
4825 [status_ setCentersHorizontally:YES];
4826 //[status_ setFont:font];
4828 output_ = [[UITextView alloc] init];
4829 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4830 //[output_ setTextFont:@"Courier New"];
4831 [output_ setFont:[[output_ font] fontWithSize:12]];
4832 [output_ setTextColor:[UIColor whiteColor]];
4833 [output_ setBackgroundColor:[UIColor clearColor]];
4834 [output_ setMarginTop:0];
4835 [output_ setAllowsRubberBanding:YES];
4836 [output_ setEditable:NO];
4837 [[self view] addSubview:output_];
4839 close_ = [[UIPushButton alloc] init];
4840 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4841 [close_ setAutosizesToFit:NO];
4842 [close_ setDrawsShadow:YES];
4843 [close_ setStretchBackground:YES];
4844 [close_ setEnabled:YES];
4845 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4846 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4847 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4848 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4852 - (void) positionViews {
4853 CGRect bounds = [[self view] bounds];
4854 CGSize prgsize = [UIProgressBar defaultSize];
4857 (bounds.size.width - prgsize.width) / 2,
4858 bounds.size.height - prgsize.height - 20
4861 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4863 [progress_ setFrame:prgrect];
4864 [status_ setFrame:CGRectMake(
4866 bounds.size.height - prgsize.height - 50,
4867 bounds.size.width - 20,
4870 [output_ setFrame:CGRectMake(
4873 bounds.size.width - 20,
4874 bounds.size.height - 96
4876 [close_ setFrame:CGRectMake(
4877 (bounds.size.width - closewidth) / 2,
4878 bounds.size.height - prgsize.height - 50,
4884 - (void) viewWillAppear:(BOOL)animated {
4885 [super viewDidAppear:animated];
4886 [[self navigationItem] setHidesBackButton:YES];
4887 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4889 [self positionViews];
4892 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4893 [self positionViews];
4896 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4897 NSString *context([alert context]);
4899 if ([context isEqualToString:@"conffile"]) {
4900 FILE *input = [database_ input];
4901 if (button == [alert cancelButtonIndex])
4902 fprintf(input, "N\n");
4903 else if (button == [alert firstOtherButtonIndex])
4904 fprintf(input, "Y\n");
4909 - (void) closeButtonPushed {
4912 UpdateExternalStatus(0);
4916 [self dismissModalViewControllerAnimated:YES];
4920 [delegate_ terminateWithSuccess];
4921 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4922 [delegate_ suspendWithAnimation:YES];
4924 [delegate_ suspend];*/
4936 system("/usr/bin/sbreload");
4942 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4943 SBReboot(SBSSpringBoardServerPort());
4945 reboot2(RB_AUTOBOOT);
4950 - (void) _retachThread {
4951 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4953 [[self view] addSubview:close_];
4954 [progress_ removeFromSuperview];
4955 [status_ removeFromSuperview];
4957 [database_ popErrorWithTitle:title_];
4958 [delegate_ progressControllerIsComplete:self];
4962 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4965 MMap mmap(file, MMap::ReadOnly);
4967 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4968 if (!(notifyconf_ == sha1.Result()))
4975 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4978 MMap mmap(file, MMap::ReadOnly);
4980 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4981 if (!(springlist_ == sha1.Result()))
4987 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4988 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4989 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4990 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4991 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4995 system("su -c /usr/bin/uicache mobile");
4998 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
5000 [delegate_ setStatusBarShowsProgress:NO];
5003 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
5004 [[data target] performSelector:[data selector] withObject:[data object]];
5005 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
5008 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
5009 UpdateExternalStatus(1);
5016 title_ = [title retain];
5018 [[self navigationItem] setTitle:title_];
5020 [status_ setText:nil];
5021 [output_ setText:@""];
5022 [progress_ setProgress:0];
5024 [close_ removeFromSuperview];
5025 [[self view] addSubview:progress_];
5026 [[self view] addSubview:status_];
5028 [delegate_ setStatusBarShowsProgress:YES];
5033 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5036 MMap mmap(file, MMap::ReadOnly);
5038 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5039 notifyconf_ = sha1.Result();
5045 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5048 MMap mmap(file, MMap::ReadOnly);
5050 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5051 springlist_ = sha1.Result();
5056 detachNewThreadSelector:@selector(_detachNewThreadData:)
5058 withObject:[[[ProgressData alloc]
5059 initWithSelector:selector
5066 - (void) repairWithSelector:(SEL)selector {
5068 detachNewThreadSelector:selector
5071 title:UCLocalize("REPAIRING")
5075 - (void) setConfigurationData:(NSString *)data {
5077 performSelectorOnMainThread:@selector(_setConfigurationData:)
5083 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
5084 CYAlertView *sheet([[[CYAlertView alloc]
5086 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
5087 defaultButtonIndex:0
5090 [sheet setMessage:error];
5091 [sheet yieldToPopupAlertAnimated:YES];
5095 - (void) setProgressTitle:(NSString *)title {
5097 performSelectorOnMainThread:@selector(_setProgressTitle:)
5103 - (void) setProgressPercent:(float)percent {
5105 performSelectorOnMainThread:@selector(_setProgressPercent:)
5106 withObject:[NSNumber numberWithFloat:percent]
5111 - (void) startProgress {
5114 - (void) addProgressOutput:(NSString *)output {
5116 performSelectorOnMainThread:@selector(_addProgressOutput:)
5122 - (bool) isCancelling:(size_t)received {
5126 - (void) _setConfigurationData:(NSString *)data {
5127 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
5129 if (!conffile_r(data)) {
5130 lprintf("E:invalid conffile\n");
5134 NSString *ofile = conffile_r[1];
5135 //NSString *nfile = conffile_r[2];
5137 UIAlertView *alert = [[[UIAlertView alloc]
5138 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
5139 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
5141 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
5143 UCLocalize("ACCEPT_NEW_COPY"),
5144 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
5148 [alert setContext:@"conffile"];
5152 - (void) _setProgressTitle:(NSString *)title {
5153 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
5154 for (size_t i(0), e([words count]); i != e; ++i) {
5155 NSString *word([words objectAtIndex:i]);
5156 if (Package *package = [database_ packageWithName:word])
5157 [words replaceObjectAtIndex:i withObject:[package name]];
5160 [status_ setText:[words componentsJoinedByString:@" "]];
5163 - (void) _setProgressPercent:(NSNumber *)percent {
5164 [progress_ setProgress:[percent floatValue]];
5167 - (void) _addProgressOutput:(NSString *)output {
5168 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
5169 CGSize size = [output_ contentSize];
5170 CGPoint offset = [output_ contentOffset];
5171 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
5172 CGRect rect = {{0, size.height-1}, {size.width, 1}};
5173 [output_ scrollRectToVisible:rect animated:YES];
5177 - (BOOL) isRunning {
5184 /* Cell Content View {{{ */
5185 @protocol ContentDelegate
5186 - (void) drawContentRect:(CGRect)rect;
5189 @interface ContentView : UIView {
5190 _transient id<ContentDelegate> delegate_;
5195 @implementation ContentView
5197 - (id) initWithFrame:(CGRect)frame {
5198 if ((self = [super initWithFrame:frame]) != nil) {
5199 [self setNeedsDisplayOnBoundsChange:YES];
5203 - (void) setDelegate:(id<ContentDelegate>)delegate {
5204 delegate_ = delegate;
5207 - (void) drawRect:(CGRect)rect {
5208 [super drawRect:rect];
5209 [delegate_ drawContentRect:rect];
5214 /* Cydia TableView Cell {{{ */
5215 @interface CYTableViewCell : UITableViewCell {
5216 ContentView *content_;
5222 @implementation CYTableViewCell
5229 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5230 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5232 if (view == content_) {
5233 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5234 highlighted_ = highlighted;
5237 [super _updateHighlightColorsForView:view highlighted:highlighted];
5240 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5241 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5242 highlighted_ = selected;
5244 [super setSelected:selected animated:animated];
5245 [content_ setNeedsDisplay];
5251 /* Package Cell {{{ */
5252 @interface PackageCell : CYTableViewCell <
5257 NSString *description_;
5265 - (PackageCell *) init;
5266 - (void) setPackage:(Package *)package;
5268 - (void) drawContentRect:(CGRect)rect;
5272 @implementation PackageCell
5274 - (void) clearPackage {
5285 if (description_ != nil) {
5286 [description_ release];
5290 if (source_ != nil) {
5295 if (badge_ != nil) {
5300 if (placard_ != nil) {
5310 [self clearPackage];
5314 - (PackageCell *) init {
5315 CGRect frame(CGRectMake(0, 0, 320, 74));
5316 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5317 UIView *content([self contentView]);
5318 CGRect bounds([content bounds]);
5320 content_ = [[ContentView alloc] initWithFrame:bounds];
5321 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5322 [content addSubview:content_];
5324 [content_ setDelegate:self];
5325 [content_ setOpaque:YES];
5329 - (NSString *) accessibilityLabel {
5330 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5333 - (void) setPackage:(Package *)package {
5334 [self clearPackage];
5337 Source *source = [package source];
5339 icon_ = [[package icon] retain];
5340 name_ = [[package name] retain];
5343 description_ = [package longDescription];
5344 if (description_ == nil)
5345 description_ = [package shortDescription];
5346 if (description_ != nil)
5347 description_ = [description_ retain];
5349 commercial_ = [package isCommercial];
5351 package_ = [package retain];
5353 NSString *label = nil;
5354 bool trusted = false;
5356 if (source != nil) {
5357 label = [source label];
5358 trusted = [source trusted];
5359 } else if ([[package id] isEqualToString:@"firmware"])
5360 label = UCLocalize("APPLE");
5362 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5364 NSString *from(label);
5366 NSString *section = [package simpleSection];
5367 if (section != nil && ![section isEqualToString:label]) {
5368 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5369 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5372 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5373 source_ = [from retain];
5375 if (NSString *purpose = [package primaryPurpose])
5376 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5377 badge_ = [badge_ retain];
5382 if (NSString *mode = [package_ mode]) {
5383 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5384 color = RemovingColor_;
5385 //placard = @"removing";
5387 color = InstallingColor_;
5388 //placard = @"installing";
5391 // XXX: the removing/installing placards are not @2x
5394 color = [UIColor whiteColor];
5396 if ([package installed] != nil)
5397 placard = @"installed";
5402 [content_ setBackgroundColor:color];
5405 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5406 placard_ = [placard_ retain];
5408 [self setNeedsDisplay];
5409 [content_ setNeedsDisplay];
5412 - (void) drawContentRect:(CGRect)rect {
5413 bool highlighted(highlighted_);
5414 float width([self bounds].size.width);
5417 CGContextRef context(UIGraphicsGetCurrentContext());
5418 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5419 CGContextFillRect(context, rect);
5424 rect.size = [icon_ size];
5426 rect.size.width /= 2;
5427 rect.size.height /= 2;
5429 rect.origin.x = 25 - rect.size.width / 2;
5430 rect.origin.y = 25 - rect.size.height / 2;
5432 [icon_ drawInRect:rect];
5435 if (badge_ != nil) {
5437 rect.size = [badge_ size];
5439 rect.size.width /= 2;
5440 rect.size.height /= 2;
5442 rect.origin.x = 36 - rect.size.width / 2;
5443 rect.origin.y = 36 - rect.size.height / 2;
5445 [badge_ drawInRect:rect];
5452 UISetColor(commercial_ ? Purple_ : Black_);
5453 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5454 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5457 UISetColor(commercial_ ? Purplish_ : Gray_);
5458 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5460 if (placard_ != nil)
5461 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5466 /* Section Cell {{{ */
5467 @interface SectionCell : CYTableViewCell <
5479 - (void) setSection:(Section *)section editing:(BOOL)editing;
5483 @implementation SectionCell
5485 - (void) clearSection {
5486 if (basic_ != nil) {
5491 if (section_ != nil) {
5501 if (count_ != nil) {
5508 [self clearSection];
5514 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5515 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5516 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5517 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5518 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5520 UIView *content([self contentView]);
5521 CGRect bounds([content bounds]);
5523 content_ = [[ContentView alloc] initWithFrame:bounds];
5524 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5525 [content addSubview:content_];
5526 [content_ setBackgroundColor:[UIColor whiteColor]];
5528 [content_ setDelegate:self];
5532 - (void) onSwitch:(id)sender {
5533 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5534 if (metadata == nil) {
5535 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5536 [Sections_ setObject:metadata forKey:basic_];
5539 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5543 - (void) setSection:(Section *)section editing:(BOOL)editing {
5544 if (editing != editing_) {
5546 [switch_ removeFromSuperview];
5548 [self addSubview:switch_];
5552 [self clearSection];
5554 if (section == nil) {
5555 name_ = [UCLocalize("ALL_PACKAGES") retain];
5558 basic_ = [section name];
5560 basic_ = [basic_ retain];
5562 section_ = [section localized];
5563 if (section_ != nil)
5564 section_ = [section_ retain];
5566 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5567 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5570 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5573 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5574 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5576 [content_ setNeedsDisplay];
5579 - (void) setFrame:(CGRect)frame {
5580 [super setFrame:frame];
5582 CGRect rect([switch_ frame]);
5583 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5586 - (NSString *) accessibilityLabel {
5590 - (void) drawContentRect:(CGRect)rect {
5591 bool highlighted(highlighted_ && !editing_);
5593 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5598 float width(rect.size.width);
5604 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5606 CGSize size = [count_ sizeWithFont:Font14_];
5610 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5616 /* File Table {{{ */
5617 @interface FileTable : CYViewController <
5618 UITableViewDataSource,
5621 _transient Database *database_;
5624 NSMutableArray *files_;
5628 - (id) initWithDatabase:(Database *)database;
5629 - (void) setPackage:(Package *)package;
5633 @implementation FileTable
5636 [self releaseSubviews];
5645 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5646 return files_ == nil ? 0 : [files_ count];
5649 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5653 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5654 static NSString *reuseIdentifier = @"Cell";
5656 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5658 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5659 [cell setFont:[UIFont systemFontOfSize:16]];
5661 [cell setText:[files_ objectAtIndex:indexPath.row]];
5662 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5667 - (NSURL *) navigationURL {
5668 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5672 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5674 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5675 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5676 [list_ setRowHeight:24.0f];
5677 [list_ setDataSource:self];
5678 [list_ setDelegate:self];
5679 [[self view] addSubview:list_];
5682 - (void) viewDidLoad {
5683 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5686 - (void) releaseSubviews {
5691 - (id) initWithDatabase:(Database *)database {
5692 if ((self = [super init]) != nil) {
5693 database_ = database;
5695 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5699 - (void) setPackage:(Package *)package {
5700 if (package_ != nil) {
5701 [package_ autorelease];
5710 [files_ removeAllObjects];
5712 if (package != nil) {
5713 package_ = [package retain];
5714 name_ = [[package id] retain];
5716 if (NSArray *files = [package files])
5717 [files_ addObjectsFromArray:files];
5719 if ([files_ count] != 0) {
5720 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5721 [files_ removeObjectAtIndex:0];
5722 [files_ sortUsingSelector:@selector(compareByPath:)];
5724 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5725 [stack addObject:@"/"];
5727 for (int i(0), e([files_ count]); i != e; ++i) {
5728 NSString *file = [files_ objectAtIndex:i];
5729 while (![file hasPrefix:[stack lastObject]])
5730 [stack removeLastObject];
5731 NSString *directory = [stack lastObject];
5732 [stack addObject:[file stringByAppendingString:@"/"]];
5733 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5734 ([stack count] - 2) * 3, "",
5735 [file substringFromIndex:[directory length]]
5744 - (void) reloadData {
5747 [self setPackage:[database_ packageWithName:name_]];
5752 /* Package Controller {{{ */
5753 @interface CYPackageController : CYBrowserController <
5754 UIActionSheetDelegate
5756 _transient Database *database_;
5760 NSMutableArray *buttons_;
5761 UIBarButtonItem *button_;
5764 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5768 @implementation CYPackageController
5771 if (package_ != nil)
5784 - (NSURL *) navigationURL {
5785 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5788 /* XXX: this is not safe at all... localization of /fail/ */
5789 - (void) _clickButtonWithName:(NSString *)name {
5790 if ([name isEqualToString:UCLocalize("CLEAR")])
5791 [delegate_ clearPackage:package_];
5792 else if ([name isEqualToString:UCLocalize("INSTALL")])
5793 [delegate_ installPackage:package_];
5794 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5795 [delegate_ installPackage:package_];
5796 else if ([name isEqualToString:UCLocalize("REMOVE")])
5797 [delegate_ removePackage:package_];
5798 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5799 [delegate_ installPackage:package_];
5800 else _assert(false);
5803 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5804 NSString *context([sheet context]);
5806 if ([context isEqualToString:@"modify"]) {
5807 if (button != [sheet cancelButtonIndex]) {
5808 NSString *buttonName = [buttons_ objectAtIndex:button];
5809 [self _clickButtonWithName:buttonName];
5812 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5816 - (bool) _allowJavaScriptPanel {
5821 - (void) _customButtonClicked {
5822 int count([buttons_ count]);
5827 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5829 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5830 [buttons addObjectsFromArray:buttons_];
5832 UIActionSheet *sheet = [[[UIActionSheet alloc]
5835 cancelButtonTitle:nil
5836 destructiveButtonTitle:nil
5837 otherButtonTitles:nil
5840 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5842 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5843 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5845 [sheet setContext:@"modify"];
5847 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5851 // We don't want to allow non-commercial packages to do custom things to the install button,
5852 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5853 - (void) customButtonClicked {
5855 [super customButtonClicked];
5857 [self _customButtonClicked];
5860 - (void) reloadButtonClicked {
5861 // Don't reload a commerical package by tapping the loading button,
5862 // but if it's not an Install button, we should forward it on.
5863 if (![package_ uninstalled])
5864 [self _customButtonClicked];
5867 - (void) applyLoadingTitle {
5868 // Don't show "Loading" as the title. Ever.
5871 - (UIBarButtonItem *) rightButton {
5876 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5877 if ((self = [super init]) != nil) {
5878 database_ = database;
5879 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5880 name_ = [[NSString alloc] initWithString:name];
5881 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5885 - (void) reloadData {
5886 if (package_ != nil)
5887 [package_ autorelease];
5888 package_ = [database_ packageWithName:name_];
5890 [buttons_ removeAllObjects];
5892 if (package_ != nil) {
5895 package_ = [package_ retain];
5896 commercial_ = [package_ isCommercial];
5898 if ([package_ mode] != nil)
5899 [buttons_ addObject:UCLocalize("CLEAR")];
5900 if ([package_ source] == nil);
5901 else if ([package_ upgradableAndEssential:NO])
5902 [buttons_ addObject:UCLocalize("UPGRADE")];
5903 else if ([package_ uninstalled])
5904 [buttons_ addObject:UCLocalize("INSTALL")];
5906 [buttons_ addObject:UCLocalize("REINSTALL")];
5907 if (![package_ uninstalled])
5908 [buttons_ addObject:UCLocalize("REMOVE")];
5915 switch ([buttons_ count]) {
5916 case 0: title = nil; break;
5917 case 1: title = [buttons_ objectAtIndex:0]; break;
5918 default: title = UCLocalize("MODIFY"); break;
5921 button_ = [[UIBarButtonItem alloc]
5923 style:UIBarButtonItemStylePlain
5925 action:@selector(customButtonClicked)
5931 - (bool) isLoading {
5932 return commercial_ ? [super isLoading] : false;
5938 /* Package List Controller {{{ */
5939 @interface PackageListController : CYViewController <
5940 UITableViewDataSource,
5943 _transient Database *database_;
5945 NSMutableArray *packages_;
5946 NSMutableArray *sections_;
5948 NSMutableArray *index_;
5949 NSMutableDictionary *indices_;
5953 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5954 - (void) setDelegate:(id)delegate;
5955 - (void) resetCursor;
5959 @implementation PackageListController
5962 [packages_ release];
5963 [sections_ release];
5972 - (void) deselectWithAnimation:(BOOL)animated {
5973 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5976 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5977 CGRect base = [[self view] bounds];
5978 base.size.height -= bounds.size.height;
5979 base.origin = [list_ frame].origin;
5981 [UIView beginAnimations:nil context:NULL];
5982 [UIView setAnimationBeginsFromCurrentState:YES];
5983 [UIView setAnimationCurve:curve];
5984 [UIView setAnimationDuration:duration];
5985 [list_ setFrame:base];
5986 [UIView commitAnimations];
5989 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5990 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5993 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5994 [self resizeForKeyboardBounds:bounds duration:0];
5997 - (void) keyboardWillShow:(NSNotification *)notification {
6000 NSTimeInterval duration;
6001 UIViewAnimationCurve curve;
6002 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6003 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6004 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6005 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6007 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);
6008 UIViewController *base = self;
6009 while ([base parentViewController] != nil)
6010 base = [base parentViewController];
6011 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6012 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6014 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6017 - (void) keyboardWillHide:(NSNotification *)notification {
6018 NSTimeInterval duration;
6019 UIViewAnimationCurve curve;
6020 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6021 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6023 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6026 - (void) viewWillAppear:(BOOL)animated {
6027 [super viewWillAppear:animated];
6029 [self resizeForKeyboardBounds:CGRectZero];
6030 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6031 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6034 - (void) viewWillDisappear:(BOOL)animated {
6035 [super viewWillDisappear:animated];
6037 [self resizeForKeyboardBounds:CGRectZero];
6038 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6039 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6042 - (void) viewDidAppear:(BOOL)animated {
6043 [super viewDidAppear:animated];
6044 [self deselectWithAnimation:animated];
6047 - (void) didSelectPackage:(Package *)package {
6048 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6049 [view setDelegate:delegate_];
6050 [[self navigationController] pushViewController:view animated:YES];
6053 #if TryIndexedCollation
6054 + (BOOL) hasIndexedCollation {
6055 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6059 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6060 NSInteger count([sections_ count]);
6061 return count == 0 ? 1 : count;
6064 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6065 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6067 return [[sections_ objectAtIndex:section] name];
6070 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6071 if ([sections_ count] == 0)
6073 return [[sections_ objectAtIndex:section] count];
6076 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6077 @synchronized (database_) {
6078 if ([database_ era] != era_)
6081 Section *section([sections_ objectAtIndex:[path section]]);
6082 NSInteger row([path row]);
6083 Package *package([packages_ objectAtIndex:([section row] + row)]);
6084 return [[package retain] autorelease];
6087 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6088 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6090 cell = [[[PackageCell alloc] init] autorelease];
6091 [cell setPackage:[self packageAtIndexPath:path]];
6095 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6096 Package *package([self packageAtIndexPath:path]);
6097 package = [database_ packageWithName:[package id]];
6098 [self didSelectPackage:package];
6101 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6102 // XXX: is 20 the most optimal number here?
6103 return [packages_ count] > 20 ? index_ : nil;
6106 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6107 #if TryIndexedCollation
6108 if ([[self class] hasIndexedCollation]) {
6109 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6116 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6117 if ((self = [super init]) != nil) {
6118 database_ = database;
6119 title_ = [title copy];
6120 [[self navigationItem] setTitle:title_];
6122 #if TryIndexedCollation
6123 if ([[self class] hasIndexedCollation])
6124 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6127 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6129 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6131 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6132 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6134 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6135 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6136 [list_ setRowHeight:73];
6137 [[self view] addSubview:list_];
6139 [list_ setDataSource:self];
6140 [list_ setDelegate:self];
6144 - (void) setDelegate:(id)delegate {
6145 delegate_ = delegate;
6148 - (bool) hasPackage:(Package *)package {
6152 - (void) reloadData {
6155 era_ = [database_ era];
6156 NSArray *packages = [database_ packages];
6158 [packages_ removeAllObjects];
6159 [sections_ removeAllObjects];
6161 _profile(PackageTable$reloadData$Filter)
6162 for (Package *package in packages)
6163 if ([self hasPackage:package])
6164 [packages_ addObject:package];
6167 [indices_ removeAllObjects];
6169 Section *section = nil;
6171 #if TryIndexedCollation
6172 if ([[self class] hasIndexedCollation]) {
6173 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6174 NSArray *titles = [collation sectionIndexTitles];
6177 _profile(PackageTable$reloadData$Section)
6178 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6182 _profile(PackageTable$reloadData$Section$Package)
6183 package = [packages_ objectAtIndex:offset];
6184 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6187 while (secidx < index) {
6190 _profile(PackageTable$reloadData$Section$Allocate)
6191 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6194 _profile(PackageTable$reloadData$Section$Add)
6195 [sections_ addObject:section];
6199 [section addToCount];
6205 [index_ removeAllObjects];
6207 _profile(PackageTable$reloadData$Section)
6208 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6212 _profile(PackageTable$reloadData$Section$Package)
6213 package = [packages_ objectAtIndex:offset];
6214 index = [package index];
6217 if (section == nil || [section index] != index) {
6218 _profile(PackageTable$reloadData$Section$Allocate)
6219 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6222 [index_ addObject:[section name]];
6223 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6225 _profile(PackageTable$reloadData$Section$Add)
6226 [sections_ addObject:section];
6230 [section addToCount];
6235 _profile(PackageTable$reloadData$List)
6240 - (void) resetCursor {
6241 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6246 /* Filtered Package List Controller {{{ */
6247 @interface FilteredPackageListController : PackageListController {
6253 - (void) setObject:(id)object;
6254 - (void) setObject:(id)object forFilter:(SEL)filter;
6256 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6260 @implementation FilteredPackageListController
6268 - (void) setFilter:(SEL)filter {
6271 /* XXX: this is an unsafe optimization of doomy hell */
6272 Method method(class_getInstanceMethod([Package class], filter));
6273 _assert(method != NULL);
6274 imp_ = method_getImplementation(method);
6275 _assert(imp_ != NULL);
6278 - (void) setObject:(id)object {
6284 object_ = [object retain];
6287 - (void) setObject:(id)object forFilter:(SEL)filter {
6288 [self setFilter:filter];
6289 [self setObject:object];
6292 - (bool) hasPackage:(Package *)package {
6293 _profile(FilteredPackageTable$hasPackage)
6294 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6298 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6299 if ((self = [super initWithDatabase:database title:title]) != nil) {
6300 [self setFilter:filter];
6301 [self setObject:object];
6308 /* Home Controller {{{ */
6309 @interface HomeController : CYBrowserController {
6314 @implementation HomeController
6316 + (BOOL) shouldHideNavigationBar {
6320 - (NSURL *) navigationURL {
6321 return [NSURL URLWithString:@"cydia://home"];
6324 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6325 [super _setMoreHeaders:request];
6328 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6329 if (UniqueID_ != nil)
6330 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6332 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6335 - (void) aboutButtonClicked {
6336 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6338 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6339 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6340 [alert setCancelButtonIndex:0];
6343 @"Copyright (C) 2008-2011\n"
6344 "Jay Freeman (saurik)\n"
6345 "saurik@saurik.com\n"
6346 "http://www.saurik.com/"
6352 - (void) viewWillDisappear:(BOOL)animated {
6353 [super viewWillDisappear:animated];
6355 if ([[self class] shouldHideNavigationBar])
6356 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6359 - (void) viewWillAppear:(BOOL)animated {
6360 if (![self hasLoaded])
6361 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6363 [super viewWillAppear:animated];
6365 if ([[self class] shouldHideNavigationBar])
6366 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6369 - (void) viewDidLoad {
6370 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6371 initWithTitle:UCLocalize("ABOUT")
6372 style:UIBarButtonItemStylePlain
6374 action:@selector(aboutButtonClicked)
6380 /* Manage Controller {{{ */
6381 @interface ManageController : CYBrowserController {
6384 - (void) queueStatusDidChange;
6388 @implementation ManageController
6390 - (NSURL *) navigationURL {
6391 return [NSURL URLWithString:@"cydia://manage"];
6394 - (void) viewWillAppear:(BOOL)animated {
6395 if (![self hasLoaded])
6396 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6398 [super viewWillAppear:animated];
6401 - (void) viewDidLoad {
6402 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6403 initWithTitle:UCLocalize("SETTINGS")
6404 style:UIBarButtonItemStylePlain
6406 action:@selector(settingsButtonClicked)
6409 [self queueStatusDidChange];
6412 - (void) settingsButtonClicked {
6413 [delegate_ showSettings];
6417 - (void) queueButtonClicked {
6421 - (void) applyLoadingTitle {
6422 // Disable "Loading" title.
6425 - (void) applyRightButton {
6426 // Disable right button.
6430 - (void) queueStatusDidChange {
6432 if (!IsWildcat_ && Queuing_) {
6433 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6434 initWithTitle:UCLocalize("QUEUE")
6435 style:UIBarButtonItemStyleDone
6437 action:@selector(queueButtonClicked)
6440 [[self navigationItem] setRightBarButtonItem:nil];
6445 - (bool) isLoading {
6446 // Never show as loading.
6453 /* Refresh Bar {{{ */
6454 @interface RefreshBar : UINavigationBar {
6455 UIProgressIndicator *indicator_;
6456 UITextLabel *prompt_;
6457 UIProgressBar *progress_;
6458 UINavigationButton *cancel_;
6463 @implementation RefreshBar
6466 [indicator_ release];
6468 [progress_ release];
6473 - (void) positionViews {
6474 CGRect frame = [cancel_ frame];
6475 frame.size = [cancel_ sizeThatFits:frame.size];
6476 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6477 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6478 [cancel_ setFrame:frame];
6480 CGSize prgsize = {75, 100};
6482 [self frame].size.width - prgsize.width - 10,
6483 ([self frame].size.height - prgsize.height) / 2
6485 [progress_ setFrame:prgrect];
6487 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6488 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6489 CGRect indrect = {{indoffset, indoffset}, indsize};
6490 [indicator_ setFrame:indrect];
6492 CGSize prmsize = {215, indsize.height + 4};
6494 indoffset * 2 + indsize.width,
6495 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6497 [prompt_ setFrame:prmrect];
6500 - (void) setFrame:(CGRect)frame {
6501 [super setFrame:frame];
6502 [self positionViews];
6505 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6506 if ((self = [super initWithFrame:frame]) != nil) {
6507 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6509 [self setBarStyle:UIBarStyleBlack];
6511 UIBarStyle barstyle([self _barStyle:NO]);
6512 bool ugly(barstyle == UIBarStyleDefault);
6514 UIProgressIndicatorStyle style = ugly ?
6515 UIProgressIndicatorStyleMediumBrown :
6516 UIProgressIndicatorStyleMediumWhite;
6518 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6519 [indicator_ setStyle:style];
6520 [indicator_ startAnimation];
6521 [self addSubview:indicator_];
6523 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6524 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6525 [prompt_ setBackgroundColor:[UIColor clearColor]];
6526 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6527 [self addSubview:prompt_];
6529 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6530 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6531 [progress_ setStyle:0];
6532 [self addSubview:progress_];
6534 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6535 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6536 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6537 [cancel_ setBarStyle:barstyle];
6539 [self positionViews];
6544 [cancel_ removeFromSuperview];
6548 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6549 [progress_ setProgress:0];
6550 [self addSubview:cancel_];
6554 [cancel_ removeFromSuperview];
6557 - (void) setPrompt:(NSString *)prompt {
6558 [prompt_ setText:prompt];
6561 - (void) setProgress:(float)progress {
6562 [progress_ setProgress:progress];
6568 @class CYNavigationController;
6570 /* Cydia Tab Bar Controller {{{ */
6571 @interface CYTabBarController : UITabBarController <
6572 UITabBarControllerDelegate,
6575 _transient Database *database_;
6576 RefreshBar *refreshbar_;
6580 // XXX: ok, "updatedelegate_"?...
6581 _transient NSObject<CydiaDelegate> *updatedelegate_;
6584 UIViewController *remembered_;
6585 _transient UIViewController *transient_;
6588 - (NSArray *) navigationURLCollection;
6589 - (void) dropBar:(BOOL)animated;
6590 - (void) beginUpdate;
6591 - (void) raiseBar:(BOOL)animated;
6596 @implementation CYTabBarController
6598 - (void) setUnselectedViewController:(UIViewController *)transient {
6599 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6600 if (transient != nil) {
6601 if (transient_ == nil)
6602 remembered_ = [[controllers objectAtIndex:0] retain];
6603 transient_ = transient;
6604 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6605 [controllers replaceObjectAtIndex:0 withObject:transient_];
6606 [self setSelectedIndex:0];
6607 [self setViewControllers:controllers];
6608 [self concealTabBarSelection];
6609 } else if (remembered_ != nil) {
6610 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6611 transient_ = transient;
6612 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6613 [remembered_ release];
6615 [self setViewControllers:controllers];
6616 [self revealTabBarSelection];
6620 - (UIViewController *) unselectedViewController {
6624 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6625 if ([self unselectedViewController])
6626 [self setUnselectedViewController:nil];
6629 - (NSArray *) navigationURLCollection {
6630 NSMutableArray *items([NSMutableArray array]);
6632 // XXX: Should this deal with transient view controllers?
6633 for (id navigation in [self viewControllers]) {
6634 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6636 [items addObject:stack];
6642 - (void) reloadData {
6643 for (CYViewController *controller in [self viewControllers])
6644 [controller reloadData];
6646 [(CYNavigationController *)[self unselectedViewController] reloadData];
6650 [refreshbar_ release];
6651 [[NSNotificationCenter defaultCenter] removeObserver:self];
6656 - (id) initWithDatabase:(Database *)database {
6657 if ((self = [super init]) != nil) {
6658 database_ = database;
6659 [self setDelegate:self];
6661 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6662 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6664 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6668 - (void) setUpdate:(NSDate *)date {
6672 - (void) beginUpdate {
6673 [refreshbar_ start];
6676 [updatedelegate_ retainNetworkActivityIndicator];
6680 detachNewThreadSelector:@selector(performUpdate)
6686 - (void) performUpdate { _pooled
6688 status.setDelegate(self);
6689 [database_ updateWithStatus:status];
6692 performSelectorOnMainThread:@selector(completeUpdate)
6698 - (void) stopUpdateWithSelector:(SEL)selector {
6700 [updatedelegate_ releaseNetworkActivityIndicator];
6702 [self raiseBar:YES];
6705 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6708 - (void) completeUpdate {
6711 [self stopUpdateWithSelector:@selector(reloadData)];
6714 - (void) cancelUpdate {
6715 [self stopUpdateWithSelector:@selector(updateData)];
6718 - (void) cancelPressed {
6719 [self cancelUpdate];
6726 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6727 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6730 - (void) startProgress {
6733 - (void) setProgressTitle:(NSString *)title {
6735 performSelectorOnMainThread:@selector(_setProgressTitle:)
6741 - (bool) isCancelling:(size_t)received {
6745 - (void) setProgressPercent:(float)percent {
6747 performSelectorOnMainThread:@selector(_setProgressPercent:)
6748 withObject:[NSNumber numberWithFloat:percent]
6753 - (void) addProgressOutput:(NSString *)output {
6755 performSelectorOnMainThread:@selector(_addProgressOutput:)
6761 - (void) _setProgressTitle:(NSString *)title {
6762 [refreshbar_ setPrompt:title];
6765 - (void) _setProgressPercent:(NSNumber *)percent {
6766 [refreshbar_ setProgress:[percent floatValue]];
6769 - (void) _addProgressOutput:(NSString *)output {
6772 - (void) setUpdateDelegate:(id)delegate {
6773 updatedelegate_ = delegate;
6776 - (CGFloat) statusBarHeight {
6777 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6778 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6780 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6784 - (UIView *) transitionView {
6785 if ([self respondsToSelector:@selector(_transitionView)])
6786 return [self _transitionView];
6788 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6791 - (void) dropBar:(BOOL)animated {
6796 UIView *transition([self transitionView]);
6797 [[self view] addSubview:refreshbar_];
6799 CGRect barframe([refreshbar_ frame]);
6801 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6802 barframe.origin.y = [self statusBarHeight];
6804 barframe.origin.y = 0;
6806 [refreshbar_ setFrame:barframe];
6809 [UIView beginAnimations:nil context:NULL];
6811 CGRect viewframe = [transition frame];
6812 viewframe.origin.y += barframe.size.height;
6813 viewframe.size.height -= barframe.size.height;
6814 [transition setFrame:viewframe];
6817 [UIView commitAnimations];
6819 // Ensure bar has the proper width for our view, it might have changed
6820 barframe.size.width = viewframe.size.width;
6821 [refreshbar_ setFrame:barframe];
6823 // XXX: fix Apple's layout bug
6824 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6827 - (void) raiseBar:(BOOL)animated {
6832 UIView *transition([self transitionView]);
6833 [refreshbar_ removeFromSuperview];
6835 CGRect barframe([refreshbar_ frame]);
6838 [UIView beginAnimations:nil context:NULL];
6840 CGRect viewframe = [transition frame];
6841 viewframe.origin.y -= barframe.size.height;
6842 viewframe.size.height += barframe.size.height;
6843 [transition setFrame:viewframe];
6846 [UIView commitAnimations];
6848 // XXX: fix Apple's layout bug
6849 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6853 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6854 // XXX: fix Apple's layout bug
6855 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6859 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6860 bool dropped(dropped_);
6865 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6870 // XXX: fix Apple's layout bug
6871 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6874 - (void) statusBarFrameChanged:(NSNotification *)notification {
6883 /* Cydia Navigation Controller {{{ */
6884 @interface CYNavigationController : UINavigationController {
6885 _transient Database *database_;
6886 _transient id<UINavigationControllerDelegate> delegate_;
6889 - (NSArray *) navigationURLCollection;
6890 - (id) initWithDatabase:(Database *)database;
6891 - (void) reloadData;
6896 @implementation CYNavigationController
6898 - (NSArray *) navigationURLCollection {
6899 NSMutableArray *stack([NSMutableArray array]);
6901 for (CYViewController *controller in [self viewControllers]) {
6902 NSString *url = [[controller navigationURL] absoluteString];
6904 [stack addObject:url];
6910 - (void) reloadData {
6911 for (CYViewController *page in [self viewControllers]) {
6912 // Only reload controllers that have already loaded.
6913 // This prevents a page from accidentally loading too
6914 // early if it hasn't been shown on the screen yet.
6915 if ([page hasLoaded])
6920 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6921 delegate_ = delegate;
6924 - (id) initWithDatabase:(Database *)database {
6925 if ((self = [super init]) != nil) {
6926 database_ = database;
6933 /* Cydia:// Protocol {{{ */
6934 @interface CydiaURLProtocol : NSURLProtocol {
6939 @implementation CydiaURLProtocol
6941 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6942 NSURL *url([request URL]);
6945 NSString *scheme([[url scheme] lowercaseString]);
6946 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6951 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6955 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6956 id<NSURLProtocolClient> client([self client]);
6958 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6960 NSData *data(UIImagePNGRepresentation(icon));
6962 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6963 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6964 [client URLProtocol:self didLoadData:data];
6965 [client URLProtocolDidFinishLoading:self];
6969 - (void) startLoading {
6970 id<NSURLProtocolClient> client([self client]);
6971 NSURLRequest *request([self request]);
6973 NSURL *url([request URL]);
6974 NSString *href([url absoluteString]);
6976 NSString *path([href substringFromIndex:8]);
6977 NSRange slash([path rangeOfString:@"/"]);
6980 if (slash.location == NSNotFound) {
6984 command = [path substringToIndex:slash.location];
6985 path = [path substringFromIndex:(slash.location + 1)];
6988 Database *database([Database sharedInstance]);
6990 if ([command isEqualToString:@"package-icon"]) {
6993 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6994 Package *package([database packageWithName:path]);
6997 UIImage *icon([package icon]);
6998 [self _returnPNGWithImage:icon forRequest:request];
6999 } else if ([command isEqualToString:@"source-icon"]) {
7002 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7003 NSString *source(Simplify(path));
7004 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7006 icon = [UIImage applicationImageNamed:@"unknown.png"];
7007 [self _returnPNGWithImage:icon forRequest:request];
7008 } else if ([command isEqualToString:@"uikit-image"]) {
7011 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7012 UIImage *icon(_UIImageWithName(path));
7013 [self _returnPNGWithImage:icon forRequest:request];
7014 } else if ([command isEqualToString:@"section-icon"]) {
7017 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7018 NSString *section(Simplify(path));
7019 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7021 icon = [UIImage applicationImageNamed:@"unknown.png"];
7022 [self _returnPNGWithImage:icon forRequest:request];
7024 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7028 - (void) stopLoading {
7034 /* Section Controller {{{ */
7035 @interface SectionController : FilteredPackageListController {
7039 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7043 @implementation SectionController
7045 - (NSURL *) navigationURL {
7046 NSString *name = section_;
7050 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7053 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7056 title = UCLocalize("ALL_PACKAGES");
7057 else if (![name isEqual:@""])
7058 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7060 title = UCLocalize("NO_SECTION");
7062 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7069 /* Sections Controller {{{ */
7070 @interface SectionsController : CYViewController <
7071 UITableViewDataSource,
7074 _transient Database *database_;
7075 NSMutableArray *sections_;
7076 NSMutableArray *filtered_;
7081 - (id) initWithDatabase:(Database *)database;
7082 - (void) editButtonClicked;
7086 @implementation SectionsController
7089 [self releaseSubviews];
7090 [sections_ release];
7091 [filtered_ release];
7096 - (NSURL *) navigationURL {
7097 return [NSURL URLWithString:@"cydia://sections"];
7100 - (void) updateNavigationItem {
7101 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7102 if ([sections_ count] == 0) {
7103 [[self navigationItem] setRightBarButtonItem:nil];
7105 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7106 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7108 action:@selector(editButtonClicked)
7109 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7113 - (BOOL) isEditing {
7117 - (void) setEditing:(BOOL)editing {
7118 if ((editing_ = editing))
7121 [delegate_ updateData];
7123 [self updateNavigationItem];
7126 - (void) viewDidAppear:(BOOL)animated {
7127 [super viewDidAppear:animated];
7128 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7131 - (void) viewWillDisappear:(BOOL)animated {
7132 [super viewWillDisappear:animated];
7133 if (editing_) [self setEditing:NO];
7136 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7137 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7141 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7142 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7145 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7149 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7150 static NSString *reuseIdentifier = @"SectionCell";
7152 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7154 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7156 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7161 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7165 Section *section = [self sectionAtIndexPath:indexPath];
7167 SectionController *controller = [[[SectionController alloc]
7168 initWithDatabase:database_
7169 section:[section name]
7171 [controller setDelegate:delegate_];
7173 [[self navigationController] pushViewController:controller animated:YES];
7177 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7179 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7180 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7181 [list_ setRowHeight:45.0f];
7182 [list_ setDataSource:self];
7183 [list_ setDelegate:self];
7184 [[self view] addSubview:list_];
7187 - (void) viewDidLoad {
7188 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7191 - (void) releaseSubviews {
7196 - (id) initWithDatabase:(Database *)database {
7197 if ((self = [super init]) != nil) {
7198 database_ = database;
7200 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7201 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7205 - (void) reloadData {
7208 NSArray *packages = [database_ packages];
7210 [sections_ removeAllObjects];
7211 [filtered_ removeAllObjects];
7213 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7216 for (Package *package in packages) {
7217 NSString *name([package section]);
7218 NSString *key(name == nil ? @"" : name);
7222 _profile(SectionsView$reloadData$Section)
7223 section = [sections objectForKey:key];
7224 if (section == nil) {
7225 _profile(SectionsView$reloadData$Section$Allocate)
7226 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7227 [sections setObject:section forKey:key];
7232 [section addToCount];
7234 _profile(SectionsView$reloadData$Filter)
7235 if (![package valid] || ![package visible])
7243 [sections_ addObjectsFromArray:[sections allValues]];
7245 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7247 for (Section *section in sections_) {
7248 size_t count([section row]);
7252 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7253 [section setCount:count];
7254 [filtered_ addObject:section];
7257 [self updateNavigationItem];
7262 - (void) editButtonClicked {
7263 [self setEditing:(!editing_)];
7269 /* Changes Controller {{{ */
7270 @interface ChangesController : CYViewController <
7271 UITableViewDataSource,
7274 _transient Database *database_;
7276 CFMutableArrayRef packages_;
7277 NSMutableArray *sections_;
7280 BOOL hasSentFirstLoad_;
7283 - (id) initWithDatabase:(Database *)database;
7287 @implementation ChangesController
7290 [self releaseSubviews];
7291 CFRelease(packages_);
7292 [sections_ release];
7297 - (NSURL *) navigationURL {
7298 return [NSURL URLWithString:@"cydia://changes"];
7301 - (void) viewWillAppear:(BOOL)animated {
7302 // Loads after it appears, so don't load beforehand.
7304 [super viewWillAppear:animated];
7307 - (void) viewDidAppear:(BOOL)animated {
7308 [super viewDidAppear:animated];
7310 if (!hasSentFirstLoad_) {
7311 hasSentFirstLoad_ = YES;
7312 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7314 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7318 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7319 NSInteger count([sections_ count]);
7320 return count == 0 ? 1 : count;
7323 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7324 if ([sections_ count] == 0)
7326 return [[sections_ objectAtIndex:section] name];
7329 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7330 if ([sections_ count] == 0)
7332 return [[sections_ objectAtIndex:section] count];
7335 - (Package *) packageAtIndex:(NSUInteger)index {
7336 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7339 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7340 @synchronized (database_) {
7341 if ([database_ era] != era_)
7344 NSUInteger sectionIndex([path section]);
7345 if (sectionIndex >= [sections_ count])
7347 Section *section([sections_ objectAtIndex:sectionIndex]);
7348 NSInteger row([path row]);
7349 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7352 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7353 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7355 cell = [[[PackageCell alloc] init] autorelease];
7356 [cell setPackage:[self packageAtIndexPath:path]];
7360 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7361 Package *package([self packageAtIndexPath:path]);
7362 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7363 [view setDelegate:delegate_];
7364 [[self navigationController] pushViewController:view animated:YES];
7368 - (void) refreshButtonClicked {
7369 [delegate_ beginUpdate];
7370 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7373 - (void) upgradeButtonClicked {
7374 [delegate_ distUpgrade];
7378 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7380 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7381 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7382 [list_ setRowHeight:73];
7383 [list_ setDataSource:self];
7384 [list_ setDelegate:self];
7385 [[self view] addSubview:list_];
7388 - (void) viewDidLoad {
7389 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7392 - (void) releaseSubviews {
7397 - (id) initWithDatabase:(Database *)database {
7398 if ((self = [super init]) != nil) {
7399 database_ = database;
7401 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7402 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7406 - (void) _reloadPackages:(NSArray *)packages {
7407 CFRelease(packages_);
7408 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7411 _profile(ChangesController$_reloadPackages$Filter)
7412 for (Package *package in packages)
7413 if ([package upgradableAndEssential:YES] || [package visible])
7414 CFArrayAppendValue(packages_, package);
7417 _profile(ChangesController$_reloadPackages$radixSort)
7418 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7423 - (void) reloadData {
7424 @synchronized (database_) {
7425 era_ = [database_ era];
7426 NSArray *packages = [database_ packages];
7428 [sections_ removeAllObjects];
7431 UIProgressHUD *hud([delegate_ addProgressHUD]);
7432 [hud setText:UCLocalize("LOADING")];
7433 //NSLog(@"HUD:%@::%@", delegate_, hud);
7434 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7435 [delegate_ removeProgressHUD:hud];
7437 [self _reloadPackages:packages];
7440 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7441 Section *ignored = nil;
7442 Section *section = nil;
7446 bool unseens = false;
7448 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7450 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7451 Package *package = [self packageAtIndex:offset];
7453 BOOL uae = [package upgradableAndEssential:YES];
7457 time_t seen([package seen]);
7459 if (section == nil || last != seen) {
7463 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7466 _profile(ChangesController$reloadData$Allocate)
7467 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7468 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7469 [sections_ addObject:section];
7473 [section addToCount];
7474 } else if ([package ignored]) {
7475 if (ignored == nil) {
7476 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7478 [ignored addToCount];
7481 [upgradable addToCount];
7486 CFRelease(formatter);
7489 Section *last = [sections_ lastObject];
7490 size_t count = [last count];
7491 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7492 [sections_ removeLastObject];
7495 if ([ignored count] != 0)
7496 [sections_ insertObject:ignored atIndex:0];
7498 [sections_ insertObject:upgradable atIndex:0];
7503 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7504 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7505 style:UIBarButtonItemStylePlain
7507 action:@selector(upgradeButtonClicked)
7510 if (![delegate_ updating])
7511 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7512 initWithTitle:UCLocalize("REFRESH")
7513 style:UIBarButtonItemStylePlain
7515 action:@selector(refreshButtonClicked)
7523 /* Search Controller {{{ */
7524 @interface SearchController : FilteredPackageListController <
7527 UISearchBar *search_;
7531 - (id) initWithDatabase:(Database *)database;
7532 - (void) setSearchTerm:(NSString *)term;
7533 - (void) reloadData;
7537 @implementation SearchController
7544 - (NSURL *) navigationURL {
7545 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7546 return [NSURL URLWithString:@"cydia://search"];
7548 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7551 - (void) setSearchTerm:(NSString *)searchTerm {
7552 [search_ setText:searchTerm];
7556 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7557 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7558 [search_ resignFirstResponder];
7562 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7563 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7567 - (id) initWithDatabase:(Database *)database {
7568 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7569 search_ = [[UISearchBar alloc] init];
7573 - (void) viewDidAppear:(BOOL)animated {
7574 [super viewDidAppear:animated];
7576 if (!searchloaded_) {
7577 searchloaded_ = YES;
7578 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7579 [search_ layoutSubviews];
7580 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7582 UITextField *textField;
7583 if ([search_ respondsToSelector:@selector(searchField)])
7584 textField = [search_ searchField];
7586 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7588 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7589 [search_ setDelegate:self];
7590 [textField setEnablesReturnKeyAutomatically:NO];
7591 [[self navigationItem] setTitleView:textField];
7595 - (void) reloadData {
7596 [self setObject:[search_ text]];
7601 - (void) didSelectPackage:(Package *)package {
7602 [search_ resignFirstResponder];
7603 [super didSelectPackage:package];
7608 /* Package Settings Controller {{{ */
7609 @interface PackageSettingsController : CYViewController <
7610 UITableViewDataSource,
7613 _transient Database *database_;
7616 UITableView *table_;
7617 UISwitch *subscribedSwitch_;
7618 UISwitch *ignoredSwitch_;
7619 UITableViewCell *subscribedCell_;
7620 UITableViewCell *ignoredCell_;
7623 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7627 @implementation PackageSettingsController
7630 [self releaseSubviews];
7637 - (NSURL *) navigationURL {
7638 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7641 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7642 if (package_ == nil)
7645 if ([package_ installed] == nil)
7651 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7652 if (package_ == nil)
7655 // both sections contain just one item right now.
7659 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7663 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7665 return UCLocalize("SHOW_ALL_CHANGES_EX");
7667 return UCLocalize("IGNORE_UPGRADES_EX");
7670 - (void) onSubscribed:(id)control {
7671 bool value([control isOn]);
7672 if (package_ == nil)
7674 if ([package_ setSubscribed:value])
7675 [delegate_ updateData];
7678 - (void) _updateIgnored {
7679 const char *package([name_ UTF8String]);
7680 bool on([ignoredSwitch_ isOn]);
7682 pid_t pid(ExecFork());
7684 FILE *dpkg(popen("dpkg --set-selections", "w"));
7685 fwrite(package, strlen(package), 1, dpkg);
7688 fwrite(" hold\n", 6, 1, dpkg);
7690 fwrite(" install\n", 9, 1, dpkg);
7700 int result(waitpid(pid, &status, 0));
7703 _assert(result == pid);
7709 - (void) onIgnored:(id)control {
7710 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7711 [invocation setTarget:self];
7712 [invocation setSelector:@selector(_updateIgnored)];
7714 [delegate_ reloadDataWithInvocation:invocation];
7717 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7718 if (package_ == nil)
7721 switch ([indexPath section]) {
7722 case 0: return subscribedCell_;
7723 case 1: return ignoredCell_;
7732 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7734 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7735 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7736 [table_ setDataSource:self];
7737 [table_ setDelegate:self];
7738 [[self view] addSubview:table_];
7740 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7741 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7742 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7744 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7745 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7746 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7748 subscribedCell_ = [[UITableViewCell alloc] init];
7749 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7750 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7751 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7753 ignoredCell_ = [[UITableViewCell alloc] init];
7754 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7755 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7756 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7759 - (void) viewDidLoad {
7760 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7763 - (void) releaseSubviews {
7764 [ignoredCell_ release];
7767 [subscribedCell_ release];
7768 subscribedCell_ = nil;
7773 [ignoredSwitch_ release];
7774 ignoredSwitch_ = nil;
7776 [subscribedSwitch_ release];
7777 subscribedSwitch_ = nil;
7780 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7781 if ((self = [super init]) != nil) {
7782 database_ = database;
7783 name_ = [package retain];
7787 - (void) reloadData {
7790 if (package_ != nil)
7791 [package_ autorelease];
7792 package_ = [database_ packageWithName:name_];
7794 if (package_ != nil) {
7795 package_ = [package_ retain];
7796 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7797 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7798 } // XXX: what now, G?
7800 [table_ reloadData];
7806 /* Installed Controller {{{ */
7807 @interface InstalledController : FilteredPackageListController {
7811 - (id) initWithDatabase:(Database *)database;
7813 - (void) updateRoleButton;
7814 - (void) queueStatusDidChange;
7818 @implementation InstalledController
7824 - (NSURL *) navigationURL {
7825 return [NSURL URLWithString:@"cydia://installed"];
7828 - (id) initWithDatabase:(Database *)database {
7829 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7830 [self updateRoleButton];
7831 [self queueStatusDidChange];
7836 - (void) queueButtonClicked {
7841 - (void) queueStatusDidChange {
7845 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7846 initWithTitle:UCLocalize("QUEUE")
7847 style:UIBarButtonItemStyleDone
7849 action:@selector(queueButtonClicked)
7852 [[self navigationItem] setLeftBarButtonItem:nil];
7858 - (void) updateRoleButton {
7859 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7860 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7861 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7862 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7864 action:@selector(roleButtonClicked)
7868 - (void) roleButtonClicked {
7869 [self setObject:[NSNumber numberWithBool:expert_]];
7873 [self updateRoleButton];
7879 /* Source Cell {{{ */
7880 @interface SourceCell : CYTableViewCell <
7888 - (void) setSource:(Source *)source;
7892 @implementation SourceCell
7894 - (void) clearSource {
7904 - (void) setSource:(Source *)source {
7908 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7910 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7911 icon_ = [icon_ retain];
7913 origin_ = [[source name] retain];
7914 label_ = [[source uri] retain];
7916 [content_ setNeedsDisplay];
7924 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7925 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7926 UIView *content([self contentView]);
7927 CGRect bounds([content bounds]);
7929 content_ = [[ContentView alloc] initWithFrame:bounds];
7930 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7931 [content_ setBackgroundColor:[UIColor whiteColor]];
7932 [content addSubview:content_];
7934 [content_ setDelegate:self];
7935 [content_ setOpaque:YES];
7939 - (NSString *) accessibilityLabel {
7943 - (void) drawContentRect:(CGRect)rect {
7944 bool highlighted(highlighted_);
7945 float width(rect.size.width);
7948 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7955 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7959 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7964 /* Source Controller {{{ */
7965 @interface SourceController : FilteredPackageListController {
7966 _transient Source *source_;
7970 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7974 @implementation SourceController
7976 - (NSURL *) navigationURL {
7977 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7980 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7981 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7983 key_ = [[source key] retain];
7987 - (void) reloadData {
7988 source_ = [database_ sourceWithKey:key_];
7990 key_ = [[source_ key] retain];
7991 [self setObject:source_];
7992 [[self navigationItem] setTitle:[source_ label]];
7999 /* Sources Controller {{{ */
8000 @interface SourcesController : CYViewController <
8001 UITableViewDataSource,
8004 _transient Database *database_;
8006 NSMutableArray *sources_;
8010 UIProgressHUD *hud_;
8013 //NSURLConnection *installer_;
8014 NSURLConnection *trivial_;
8015 NSURLConnection *trivial_bz2_;
8016 NSURLConnection *trivial_gz_;
8017 //NSURLConnection *automatic_;
8022 - (id) initWithDatabase:(Database *)database;
8023 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8027 @implementation SourcesController
8029 - (void) _releaseConnection:(NSURLConnection *)connection {
8030 if (connection != nil) {
8031 [connection cancel];
8032 //[connection setDelegate:nil];
8033 [connection release];
8038 [self releaseSubviews];
8044 //[self _releaseConnection:installer_];
8045 [self _releaseConnection:trivial_];
8046 [self _releaseConnection:trivial_gz_];
8047 [self _releaseConnection:trivial_bz2_];
8048 //[self _releaseConnection:automatic_];
8054 - (NSURL *) navigationURL {
8055 return [NSURL URLWithString:@"cydia://sources"];
8058 - (void) viewDidAppear:(BOOL)animated {
8059 [super viewDidAppear:animated];
8060 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8063 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8064 return offset_ == 0 ? 1 : 2;
8067 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8068 switch (section + (offset_ == 0 ? 1 : 0)) {
8069 case 0: return UCLocalize("ENTERED_BY_USER");
8070 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8076 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8077 int count = [sources_ count];
8079 case 0: return (offset_ == 0 ? count : offset_);
8080 case 1: return count - offset_;
8086 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8088 switch (indexPath.section) {
8089 case 0: idx = indexPath.row; break;
8090 case 1: idx = indexPath.row + offset_; break;
8094 return [sources_ objectAtIndex:idx];
8097 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8098 static NSString *cellIdentifier = @"SourceCell";
8100 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8101 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8102 [cell setSource:[self sourceAtIndexPath:indexPath]];
8103 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8108 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8109 Source *source = [self sourceAtIndexPath:indexPath];
8111 SourceController *controller = [[[SourceController alloc]
8112 initWithDatabase:database_
8116 [controller setDelegate:delegate_];
8118 [[self navigationController] pushViewController:controller animated:YES];
8121 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8122 Source *source = [self sourceAtIndexPath:indexPath];
8123 return [source record] != nil;
8126 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8127 Source *source = [self sourceAtIndexPath:indexPath];
8128 [Sources_ removeObjectForKey:[source key]];
8129 [delegate_ syncData];
8133 [delegate_ addTrivialSource:href_];
8134 [delegate_ syncData];
8137 - (NSString *) getWarning {
8138 NSString *href(href_);
8139 NSRange colon([href rangeOfString:@"://"]);
8140 if (colon.location != NSNotFound)
8141 href = [href substringFromIndex:(colon.location + 3)];
8142 href = [href stringByAddingPercentEscapes];
8143 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8144 href = [href stringByCachingURLWithCurrentCDN];
8146 NSURL *url([NSURL URLWithString:href]);
8148 NSStringEncoding encoding;
8149 NSError *error(nil);
8151 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8152 return [warning length] == 0 ? nil : warning;
8156 - (void) _endConnection:(NSURLConnection *)connection {
8157 // XXX: the memory management in this method is horribly awkward
8159 NSURLConnection **field = NULL;
8160 if (connection == trivial_)
8162 else if (connection == trivial_bz2_)
8163 field = &trivial_bz2_;
8164 else if (connection == trivial_gz_)
8165 field = &trivial_gz_;
8166 _assert(field != NULL);
8167 [connection release];
8172 trivial_bz2_ == nil &&
8178 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8181 UIAlertView *alert = [[[UIAlertView alloc]
8182 initWithTitle:UCLocalize("SOURCE_WARNING")
8185 cancelButtonTitle:UCLocalize("CANCEL")
8187 UCLocalize("ADD_ANYWAY"),
8191 [alert setContext:@"warning"];
8192 [alert setNumberOfRows:1];
8196 } else if (error_ != nil) {
8197 UIAlertView *alert = [[[UIAlertView alloc]
8198 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8199 message:[error_ localizedDescription]
8201 cancelButtonTitle:UCLocalize("OK")
8202 otherButtonTitles:nil
8205 [alert setContext:@"urlerror"];
8208 UIAlertView *alert = [[[UIAlertView alloc]
8209 initWithTitle:UCLocalize("NOT_REPOSITORY")
8210 message:UCLocalize("NOT_REPOSITORY_EX")
8212 cancelButtonTitle:UCLocalize("OK")
8213 otherButtonTitles:nil
8216 [alert setContext:@"trivial"];
8220 [delegate_ setStatusBarShowsProgress:NO];
8221 [delegate_ removeProgressHUD:hud_];
8231 if (error_ != nil) {
8238 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8239 switch ([response statusCode]) {
8245 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8246 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8248 error_ = [error retain];
8249 [self _endConnection:connection];
8252 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8253 [self _endConnection:connection];
8256 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8257 NSMutableURLRequest *request = [NSMutableURLRequest
8258 requestWithURL:[NSURL URLWithString:href]
8259 cachePolicy:NSURLRequestUseProtocolCachePolicy
8260 timeoutInterval:120.0
8263 [request setHTTPMethod:method];
8265 if (Machine_ != NULL)
8266 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8267 if (UniqueID_ != nil)
8268 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8270 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8272 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8275 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8276 NSString *context([alert context]);
8278 if ([context isEqualToString:@"source"]) {
8281 NSString *href = [[alert textField] text];
8283 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8285 if (![href hasSuffix:@"/"])
8286 href_ = [href stringByAppendingString:@"/"];
8289 href_ = [href_ retain];
8291 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8292 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8293 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8294 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8298 // XXX: this is stupid
8299 hud_ = [[delegate_ addProgressHUD] retain];
8300 [hud_ setText:UCLocalize("VERIFYING_URL")];
8309 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8310 } else if ([context isEqualToString:@"trivial"])
8311 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8312 else if ([context isEqualToString:@"urlerror"])
8313 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8314 else if ([context isEqualToString:@"warning"]) {
8329 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8334 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8336 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8337 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8338 [list_ setRowHeight:56];
8339 [list_ setDataSource:self];
8340 [list_ setDelegate:self];
8341 [[self view] addSubview:list_];
8344 - (void) viewDidLoad {
8345 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8346 [self updateButtonsForEditingStatus:NO animated:NO];
8349 - (void) releaseSubviews {
8354 - (id) initWithDatabase:(Database *)database {
8355 if ((self = [super init]) != nil) {
8356 database_ = database;
8357 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8361 - (void) reloadData {
8365 if (!list.ReadMainList())
8368 [sources_ removeAllObjects];
8369 [sources_ addObjectsFromArray:[database_ sources]];
8371 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8374 int count([sources_ count]);
8376 for (int i = 0; i != count; i++) {
8377 if ([[sources_ objectAtIndex:i] record] == nil)
8382 [list_ setEditing:NO];
8383 [self updateButtonsForEditingStatus:NO animated:NO];
8387 - (void) showAddSourcePrompt {
8388 UIAlertView *alert = [[[UIAlertView alloc]
8389 initWithTitle:UCLocalize("ENTER_APT_URL")
8392 cancelButtonTitle:UCLocalize("CANCEL")
8394 UCLocalize("ADD_SOURCE"),
8398 [alert setContext:@"source"];
8399 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8401 [alert setNumberOfRows:1];
8402 [alert addTextFieldWithValue:@"http://" label:@""];
8404 UITextInputTraits *traits = [[alert textField] textInputTraits];
8405 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8406 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8407 [traits setKeyboardType:UIKeyboardTypeURL];
8408 // XXX: UIReturnKeyDone
8409 [traits setReturnKeyType:UIReturnKeyNext];
8414 - (void) addButtonClicked {
8415 [self showAddSourcePrompt];
8418 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8419 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8420 initWithTitle:UCLocalize("ADD")
8421 style:UIBarButtonItemStylePlain
8423 action:@selector(addButtonClicked)
8424 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8426 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8427 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8428 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8430 action:@selector(editButtonClicked)
8431 ] autorelease] animated:animated];
8433 if (IsWildcat_ && !editing)
8434 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8435 initWithTitle:UCLocalize("SETTINGS")
8436 style:UIBarButtonItemStylePlain
8438 action:@selector(settingsButtonClicked)
8442 - (void) settingsButtonClicked {
8443 [delegate_ showSettings];
8446 - (void) editButtonClicked {
8447 [list_ setEditing:![list_ isEditing] animated:YES];
8449 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8455 /* Settings Controller {{{ */
8456 @interface SettingsController : CYViewController <
8457 UITableViewDataSource,
8460 _transient Database *database_;
8461 // XXX: ok, "roledelegate_"?...
8462 _transient id roledelegate_;
8463 UITableView *table_;
8464 UISegmentedControl *segment_;
8468 - (void) showDoneButton;
8469 - (void) resizeSegmentedControl;
8473 @implementation SettingsController
8476 [self releaseSubviews];
8482 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8484 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8485 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8486 [table_ setDelegate:self];
8487 [table_ setDataSource:self];
8488 [[self view] addSubview:table_];
8490 NSArray *items = [NSArray arrayWithObjects:
8492 UCLocalize("HACKER"),
8493 UCLocalize("DEVELOPER"),
8495 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8496 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8497 [container_ addSubview:segment_];
8500 - (void) viewDidLoad {
8501 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8504 if ([Role_ isEqualToString:@"User"]) index = 0;
8505 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8506 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8508 [segment_ setSelectedSegmentIndex:index];
8509 [self showDoneButton];
8512 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8513 [self resizeSegmentedControl];
8516 - (void) releaseSubviews {
8523 [container_ release];
8527 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8528 if ((self = [super init]) != nil) {
8529 database_ = database;
8530 roledelegate_ = delegate;
8534 - (void) resizeSegmentedControl {
8535 CGFloat width = [[self view] frame].size.width;
8536 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8539 - (void) viewWillAppear:(BOOL)animated {
8540 [super viewWillAppear:animated];
8542 [self resizeSegmentedControl];
8545 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8546 [self resizeSegmentedControl];
8549 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8550 [self resizeSegmentedControl];
8554 NSString *role(nil);
8556 switch ([segment_ selectedSegmentIndex]) {
8557 case 0: role = @"User"; break;
8558 case 1: role = @"Hacker"; break;
8559 case 2: role = @"Developer"; break;
8564 if (![role isEqualToString:Role_]) {
8565 bool rolling(Role_ == nil);
8568 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8572 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8576 [roledelegate_ loadData];
8578 [roledelegate_ updateData];
8582 - (void) segmentChanged:(UISegmentedControl *)control {
8583 [self showDoneButton];
8586 - (void) saveAndClose {
8589 [[self navigationItem] setRightBarButtonItem:nil];
8590 [[self navigationController] dismissModalViewControllerAnimated:YES];
8593 - (void) doneButtonClicked {
8594 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8595 [spinner startAnimating];
8596 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8597 [[self navigationItem] setRightBarButtonItem:spinItem];
8599 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8602 - (void) showDoneButton {
8603 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8604 initWithTitle:UCLocalize("DONE")
8605 style:UIBarButtonItemStyleDone
8607 action:@selector(doneButtonClicked)
8608 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8611 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8612 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8616 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8620 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8621 return nil; // This method is required by the protocol.
8624 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8626 return UCLocalize("ROLE_EX");
8628 return [NSString stringWithFormat:
8629 @"%@: %@\n%@: %@\n%@: %@",
8630 UCLocalize("USER"), UCLocalize("USER_EX"),
8631 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8632 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8637 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8638 return section == 3 ? 44.0f : 0;
8641 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8642 return section == 3 ? container_ : nil;
8645 - (void) reloadData {
8647 [table_ reloadData];
8652 /* Stash Controller {{{ */
8653 @interface StashController : CYViewController {
8654 UIActivityIndicatorView *spinner_;
8661 @implementation StashController
8664 [self releaseSubviews];
8670 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8671 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8673 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8674 CGRect spinrect = [spinner_ frame];
8675 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8676 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8677 [spinner_ setFrame:spinrect];
8678 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8679 [[self view] addSubview:spinner_];
8680 [spinner_ startAnimating];
8683 captrect.size.width = [[self view] frame].size.width;
8684 captrect.size.height = 40.0f;
8685 captrect.origin.x = 0;
8686 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8687 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8688 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8689 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8690 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8691 [caption_ setTextColor:[UIColor whiteColor]];
8692 [caption_ setBackgroundColor:[UIColor clearColor]];
8693 [caption_ setShadowColor:[UIColor blackColor]];
8694 [caption_ setTextAlignment:UITextAlignmentCenter];
8695 [[self view] addSubview:caption_];
8698 statusrect.size.width = [[self view] frame].size.width;
8699 statusrect.size.height = 30.0f;
8700 statusrect.origin.x = 0;
8701 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8702 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8703 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8704 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8705 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8706 [status_ setTextColor:[UIColor whiteColor]];
8707 [status_ setBackgroundColor:[UIColor clearColor]];
8708 [status_ setShadowColor:[UIColor blackColor]];
8709 [status_ setTextAlignment:UITextAlignmentCenter];
8710 [[self view] addSubview:status_];
8713 - (void) releaseSubviews {
8727 @interface Cydia : UIApplication <
8728 ConfirmationControllerDelegate,
8729 ProgressControllerDelegate,
8731 UINavigationControllerDelegate,
8732 UITabBarControllerDelegate
8734 // XXX: evaluate all fields for _transient
8737 CYTabBarController *tabbar_;
8739 NSMutableArray *essential_;
8740 NSMutableArray *broken_;
8742 Database *database_;
8749 StashController *stash_;
8758 @implementation Cydia
8760 - (void) beginUpdate {
8761 [tabbar_ beginUpdate];
8765 return [tabbar_ updating];
8769 if ([broken_ count] != 0) {
8770 int count = [broken_ count];
8772 UIAlertView *alert = [[[UIAlertView alloc]
8773 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8774 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8776 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8778 UCLocalize("TEMPORARY_IGNORE"),
8782 [alert setContext:@"fixhalf"];
8784 } else if (!Ignored_ && [essential_ count] != 0) {
8785 int count = [essential_ count];
8787 UIAlertView *alert = [[[UIAlertView alloc]
8788 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8789 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8791 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8793 UCLocalize("UPGRADE_ESSENTIAL"),
8794 UCLocalize("COMPLETE_UPGRADE"),
8798 [alert setContext:@"upgrade"];
8803 - (void) _saveConfig {
8809 NSString *error(nil);
8811 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8813 NSError *error(nil);
8814 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8815 NSLog(@"failure to save metadata data: %@", error);
8820 NSLog(@"failure to serialize metadata: %@", error);
8825 // Navigation controller for the queuing badge.
8826 - (CYNavigationController *) queueNavigationController {
8827 NSArray *controllers = [tabbar_ viewControllers];
8828 return [controllers objectAtIndex:3];
8831 - (void) _updateData {
8834 [tabbar_ reloadData];
8836 CYNavigationController *navigation = [self queueNavigationController];
8838 id queuedelegate = nil;
8839 if ([[navigation viewControllers] count] > 0)
8840 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8842 [queuedelegate queueStatusDidChange];
8843 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8846 - (void) _refreshIfPossible {
8847 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8849 bool recently = false;
8850 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8851 if (update != nil) {
8852 NSTimeInterval interval([update timeIntervalSinceNow]);
8853 if (interval <= 0 && interval > -(15*60))
8857 // Don't automatic refresh if:
8858 // - We already refreshed recently.
8859 // - We already auto-refreshed this launch.
8860 // - Auto-refresh is disabled.
8861 if (recently || loaded_ || ManualRefresh) {
8862 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8864 // If we are cancelling, we need to make sure it knows it's already loaded.
8868 // We are going to load, so remember that.
8872 SCNetworkReachabilityFlags flags; {
8873 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8874 SCNetworkReachabilityGetFlags(reachability, &flags);
8875 CFRelease(reachability);
8878 // XXX: this elaborate mess is what Apple is using to determine this? :(
8879 // XXX: do we care if the user has to intervene? maybe that's ok?
8881 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8882 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8883 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8884 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8885 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8886 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8890 // If we can reach the server, auto-refresh!
8892 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8897 - (void) refreshIfPossible {
8898 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8901 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8902 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8903 [hud setText:UCLocalize("RELOADING_DATA")];
8905 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8908 [self removeProgressHUD:hud];
8912 [essential_ removeAllObjects];
8913 [broken_ removeAllObjects];
8915 NSArray *packages([database_ packages]);
8916 for (Package *package in packages) {
8918 [broken_ addObject:package];
8919 if ([package upgradableAndEssential:NO]) {
8920 if ([package essential])
8921 [essential_ addObject:package];
8926 NSLog(@"changes:#%u", changes);
8928 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8931 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8932 [changesItem setBadgeValue:badge];
8933 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8934 [self setApplicationIconBadgeNumber:changes];
8937 [changesItem setBadgeValue:nil];
8938 [changesItem setAnimatedBadge:NO];
8939 [self setApplicationIconBadgeNumber:0];
8944 [self refreshIfPossible];
8947 - (void) updateData {
8958 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8959 _assert(file != NULL);
8961 for (NSString *key in [Sources_ allKeys]) {
8962 NSDictionary *source([Sources_ objectForKey:key]);
8964 fprintf(file, "%s %s %s\n",
8965 [[source objectForKey:@"Type"] UTF8String],
8966 [[source objectForKey:@"URI"] UTF8String],
8967 [[source objectForKey:@"Distribution"] UTF8String]
8973 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8974 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8976 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8977 [tabbar_ presentModalViewController:navigation animated:YES];
8980 detachNewThreadSelector:@selector(update_)
8983 title:UCLocalize("UPDATING_SOURCES")
8987 - (void) addTrivialSource:(NSString *)href {
8988 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8991 @"./", @"Distribution",
8992 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8997 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8998 @synchronized (self) {
8999 [self _reloadDataWithInvocation:invocation];
9003 - (void) reloadData {
9004 [self reloadDataWithInvocation:nil];
9008 pkgProblemResolver *resolver = [database_ resolver];
9010 resolver->InstallProtect();
9011 if (!resolver->Resolve(true))
9016 // XXX: this is a really crappy way of doing this.
9017 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9018 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9019 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9020 if ([tabbar_ updating])
9021 [tabbar_ cancelUpdate];
9023 if (![database_ prepare])
9026 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9027 [page setDelegate:self];
9028 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9029 [confirm_ setDelegate:self];
9032 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9033 [tabbar_ presentModalViewController:confirm_ animated:YES];
9039 @synchronized (self) {
9044 - (void) clearPackage:(Package *)package {
9045 @synchronized (self) {
9052 - (void) installPackages:(NSArray *)packages {
9053 @synchronized (self) {
9054 for (Package *package in packages)
9061 - (void) installPackage:(Package *)package {
9062 @synchronized (self) {
9069 - (void) removePackage:(Package *)package {
9070 @synchronized (self) {
9077 - (void) distUpgrade {
9078 @synchronized (self) {
9079 if (![database_ upgrade])
9086 @synchronized (self) {
9087 [self _reloadDataWithInvocation:nil];
9091 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9094 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
9096 if (navigation != nil) {
9097 [navigation pushViewController:progress animated:YES];
9099 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
9101 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9102 [tabbar_ presentModalViewController:navigation animated:YES];
9106 detachNewThreadSelector:@selector(perform)
9109 title:UCLocalize("RUNNING")
9115 - (void) progressControllerIsComplete:(ProgressController *)progress {
9120 - (void) showSettings {
9121 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9122 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9124 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9125 [tabbar_ presentModalViewController:nav animated:YES];
9128 - (void) retainNetworkActivityIndicator {
9129 if (activity_++ == 0)
9130 [self setNetworkActivityIndicatorVisible:YES];
9133 - (void) releaseNetworkActivityIndicator {
9134 if (--activity_ == 0)
9135 [self setNetworkActivityIndicatorVisible:NO];
9138 - (void) cancelAndClear:(bool)clear {
9139 @synchronized (self) {
9151 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9152 NSString *context([alert context]);
9154 if ([context isEqualToString:@"fixhalf"]) {
9155 if (button == [alert cancelButtonIndex]) {
9156 @synchronized (self) {
9157 for (Package *broken in broken_) {
9160 NSString *id = [broken id];
9161 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9162 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9163 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9164 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9170 } else if (button == [alert firstOtherButtonIndex]) {
9171 [broken_ removeAllObjects];
9175 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9176 } else if ([context isEqualToString:@"upgrade"]) {
9177 if (button == [alert firstOtherButtonIndex]) {
9178 @synchronized (self) {
9179 for (Package *essential in essential_)
9180 [essential install];
9185 } else if (button == [alert firstOtherButtonIndex] + 1) {
9187 } else if (button == [alert cancelButtonIndex]) {
9191 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9195 - (void) system:(NSString *)command { _pooled
9197 system([command UTF8String]);
9201 - (void) applicationWillSuspend {
9203 [super applicationWillSuspend];
9206 - (BOOL) isSafeToSuspend {
9207 // Use external process status API internally.
9208 // This is probably a really bad idea.
9209 // XXX: what is the point of this? does this solve anything at all?
9210 uint64_t status = 0;
9212 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9213 notify_get_state(notify_token, &status);
9214 notify_cancel(notify_token);
9217 return locked_ == 0 && status == 0;
9220 - (void) applicationSuspend:(__GSEvent *)event {
9221 if ([self isSafeToSuspend])
9222 [super applicationSuspend:event];
9225 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9226 if ([self isSafeToSuspend])
9227 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9230 - (void) _setSuspended:(BOOL)value {
9231 if ([self isSafeToSuspend])
9232 [super _setSuspended:value];
9235 - (UIProgressHUD *) addProgressHUD {
9236 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9237 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9239 [window_ setUserInteractionEnabled:NO];
9242 UIViewController *target = tabbar_;
9243 while ([target modalViewController] != nil) target = [target modalViewController];
9244 [[target view] addSubview:hud];
9250 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9252 [hud removeFromSuperview];
9253 [window_ setUserInteractionEnabled:YES];
9257 - (CYViewController *) pageForPackage:(NSString *)name {
9258 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9261 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9262 NSString *scheme([[url scheme] lowercaseString]);
9263 if ([[url absoluteString] length] <= [scheme length] + 3)
9265 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9266 NSArray *components([path pathComponents]);
9268 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9269 return [self pageForPackage:[components objectAtIndex:1]];
9271 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9274 NSString *base([components objectAtIndex:0]);
9276 CYViewController *controller = nil;
9278 if ([base isEqualToString:@"url"]) {
9279 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9280 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9281 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9282 } else if (!external && [components count] == 1) {
9283 if ([base isEqualToString:@"manage"]) {
9284 controller = [[[ManageController alloc] init] autorelease];
9287 if ([base isEqualToString:@"sources"]) {
9288 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9291 if ([base isEqualToString:@"home"]) {
9292 controller = [[[HomeController alloc] init] autorelease];
9295 if ([base isEqualToString:@"sections"]) {
9296 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9299 if ([base isEqualToString:@"search"]) {
9300 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9303 if ([base isEqualToString:@"changes"]) {
9304 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9307 if ([base isEqualToString:@"installed"]) {
9308 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9310 } else if ([components count] == 2) {
9311 NSString *argument = [components objectAtIndex:1];
9313 if ([base isEqualToString:@"package"]) {
9314 controller = [self pageForPackage:argument];
9317 if (!external && [base isEqualToString:@"search"]) {
9318 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9319 [(SearchController *)controller setSearchTerm:argument];
9322 if (!external && [base isEqualToString:@"sections"]) {
9323 if ([argument isEqualToString:@"all"])
9325 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9328 if (!external && [base isEqualToString:@"sources"]) {
9329 if ([argument isEqualToString:@"add"]) {
9330 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9331 [(SourcesController *)controller showAddSourcePrompt];
9333 Source *source = [database_ sourceWithKey:argument];
9334 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9338 if (!external && [base isEqualToString:@"launch"]) {
9339 [self launchApplicationWithIdentifier:argument suspended:NO];
9342 } else if (!external && [components count] == 3) {
9343 NSString *arg1 = [components objectAtIndex:1];
9344 NSString *arg2 = [components objectAtIndex:2];
9346 if ([base isEqualToString:@"package"]) {
9347 if ([arg2 isEqualToString:@"settings"]) {
9348 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9349 } else if ([arg2 isEqualToString:@"files"]) {
9350 if (Package *package = [database_ packageWithName:arg1]) {
9351 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9352 [(FileTable *)controller setPackage:package];
9358 [controller setDelegate:self];
9362 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9363 CYViewController *page([self pageForURL:url forExternal:external]);
9366 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9367 [nav setViewControllers:[NSArray arrayWithObject:page]];
9368 [tabbar_ setUnselectedViewController:nav];
9374 - (void) applicationOpenURL:(NSURL *)url {
9375 [super applicationOpenURL:url];
9377 if (!loaded_) starturl_ = [url retain];
9378 else [self openCydiaURL:url forExternal:YES];
9381 - (void) applicationWillResignActive:(UIApplication *)application {
9382 // Stop refreshing if you get a phone call or lock the device.
9383 if ([tabbar_ updating])
9384 [tabbar_ cancelUpdate];
9386 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9387 [super applicationWillResignActive:application];
9390 - (void) applicationWillTerminate:(UIApplication *)application {
9392 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9393 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9394 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9399 - (void) addStashController {
9401 stash_ = [[StashController alloc] init];
9402 [window_ addSubview:[stash_ view]];
9405 - (void) removeStashController {
9406 [[stash_ view] removeFromSuperview];
9412 [self setIdleTimerDisabled:YES];
9414 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9415 [self setStatusBarShowsProgress:YES];
9416 UpdateExternalStatus(1);
9418 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9420 UpdateExternalStatus(0);
9421 [self setStatusBarShowsProgress:NO];
9423 [self removeStashController];
9425 if (ExecFork() == 0) {
9426 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9427 perror("launchctl stop");
9431 - (void) setupViewControllers {
9432 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9434 NSMutableArray *items([NSMutableArray arrayWithObjects:
9435 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9436 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9437 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9438 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9442 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9443 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9445 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9448 NSMutableArray *controllers([NSMutableArray array]);
9449 for (UITabBarItem *item in items) {
9450 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9451 [controller setTabBarItem:item];
9452 [controllers addObject:controller];
9454 [tabbar_ setViewControllers:controllers];
9456 [tabbar_ setUpdateDelegate:self];
9459 - (CYEmulatedLoadingController *) showEmulatedLoadingControllerInView:(UIView *)view {
9460 static CYEmulatedLoadingController *fake = nil;
9464 fake = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9465 [view addSubview:[fake view]];
9467 [[fake view] removeFromSuperview];
9475 - (void) applicationDidFinishLaunching:(id)unused {
9479 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9480 [self setApplicationSupportsShakeToEdit:NO];
9482 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9483 initWithMemoryCapacity:524288
9484 diskCapacity:10485760
9485 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9488 [CYBrowserController _initialize];
9490 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9492 Font12_ = [[UIFont systemFontOfSize:12] retain];
9493 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9494 Font14_ = [[UIFont systemFontOfSize:14] retain];
9495 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9496 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9498 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9499 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9501 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9502 [window_ orderFront:self];
9503 [window_ makeKey:self];
9504 [window_ setHidden:NO];
9507 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9508 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9509 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9510 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9511 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9512 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9513 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9514 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9515 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9518 [self addStashController];
9519 // XXX: this would be much cleaner as a yieldToSelector:
9520 // that way the removeStashController could happen right here inline
9521 // we also could no longer require the useless stash_ field anymore
9522 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9526 database_ = [Database sharedInstance];
9528 [window_ setUserInteractionEnabled:NO];
9529 [self setupViewControllers];
9530 [self showEmulatedLoadingControllerInView:window_];
9532 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9539 [window_ setUserInteractionEnabled:YES];
9541 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9542 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9544 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9545 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9549 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9550 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9551 [window_ setUserInteractionEnabled:NO];
9557 [window_ addSubview:[tabbar_ view]];
9558 [self showEmulatedLoadingControllerInView:nil];
9559 [window_ setUserInteractionEnabled:YES];
9561 int selectedIndex = 0;
9562 NSMutableArray *items = nil;
9564 bool recently = false;
9565 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9566 if (closed != nil) {
9567 NSTimeInterval interval([closed timeIntervalSinceNow]);
9568 // XXX: Is 15 minutes the optimal time here?
9569 if (interval <= 0 && interval > -(15*60))
9573 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9574 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9577 for (NSArray *entry in items)
9578 if ([entry count] <= 0)
9581 if (!recently || !items || !enough) {
9583 items = [NSMutableArray array];
9584 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9585 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9586 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9588 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9590 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9591 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9593 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9596 [tabbar_ setSelectedIndex:selectedIndex];
9597 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9598 NSArray *stack = [items objectAtIndex:tab];
9599 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9600 NSMutableArray *current = [NSMutableArray array];
9602 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9603 NSString *addr = [stack objectAtIndex:nav];
9604 NSURL *url = [NSURL URLWithString:addr];
9605 CYViewController *page = [self pageForURL:url forExternal:NO];
9607 [current addObject:page];
9610 [navigation setViewControllers:current];
9613 // (Try to) show the startup URL.
9614 if (starturl_ != nil) {
9615 [self openCydiaURL:starturl_ forExternal:NO];
9616 [starturl_ release];
9621 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9622 if (item != nil && IsWildcat_) {
9623 [sheet showFromBarButtonItem:item animated:YES];
9625 [sheet showInView:window_];
9632 id Alloc_(id self, SEL selector) {
9633 id object = alloc_(self, selector);
9634 lprintf("[%s]A-%p\n", self->isa->name, object);
9639 id Dealloc_(id self, SEL selector) {
9640 id object = dealloc_(self, selector);
9641 lprintf("[%s]D-%p\n", self->isa->name, object);
9645 Class $WebDefaultUIKitDelegate;
9647 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9648 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9649 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9650 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9653 static NSNumber *shouldPlayKeyboardSounds;
9657 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9659 case 1104: // Keyboard Button Clicked
9660 case 1105: // Keyboard Delete Repeated
9661 if (shouldPlayKeyboardSounds == nil) {
9662 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9663 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9666 if (![shouldPlayKeyboardSounds boolValue])
9670 _UIHardware$_playSystemSound$(self, _cmd, sound);
9674 Class $UIApplication;
9676 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9677 static BOOL initialized = NO;
9678 static BOOL started = NO;
9680 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9681 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9683 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9684 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9685 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9686 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9688 if (initialized && !enabled) {
9690 [bundle performSelector:@selector(_accessibilityStopServer)];
9691 } else if (enabled) {
9695 [bundle performSelector:@selector(_accessibilityStartServer)];
9701 int main(int argc, char *argv[]) { _pooled
9704 if (Class $UIDevice = objc_getClass("UIDevice")) {
9705 UIDevice *device([$UIDevice currentDevice]);
9706 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9710 UIScreen *screen([UIScreen mainScreen]);
9711 if ([screen respondsToSelector:@selector(scale)])
9712 ScreenScale_ = [screen scale];
9716 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9717 if (ScreenScale_ > 1)
9718 [parts addObject:@"@2x"];
9719 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9720 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9722 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9724 /* Library Hacks {{{ */
9725 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9727 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9728 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9729 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9730 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9731 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9734 $UIHardware = objc_getClass("UIHardware");
9735 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9736 if (UIHardware$_playSystemSound$ != NULL) {
9737 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9738 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9741 $UIApplication = objc_getClass("UIApplication");
9742 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9743 if (UIApplication$_updateApplicationAccessibility != NULL) {
9744 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9745 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9748 /* Set Locale {{{ */
9749 Locale_ = CFLocaleCopyCurrent();
9750 Languages_ = [NSLocale preferredLanguages];
9751 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9752 //NSLog(@"%@", [Languages_ description]);
9755 if (Languages_ == nil || [Languages_ count] == 0)
9756 // XXX: consider just setting to C and then falling through?
9759 lang = [[Languages_ objectAtIndex:0] UTF8String];
9760 setenv("LANG", lang, true);
9763 //std::setlocale(LC_ALL, lang);
9764 NSLog(@"Setting Language: %s", lang);
9767 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9769 /* Parse Arguments {{{ */
9770 bool substrate(false);
9776 for (int argi(1); argi != argc; ++argi)
9777 if (strcmp(argv[argi], "--") == 0) {
9779 argv[argi] = argv[0];
9785 for (int argi(1); argi != arge; ++argi)
9786 if (strcmp(args[argi], "--substrate") == 0)
9789 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9793 App_ = [[NSBundle mainBundle] bundlePath];
9794 Home_ = NSHomeDirectory();
9800 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9801 alloc_ = alloc->method_imp;
9802 alloc->method_imp = (IMP) &Alloc_;*/
9804 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9805 dealloc_ = dealloc->method_imp;
9806 dealloc->method_imp = (IMP) &Dealloc_;*/
9808 /* System Information {{{ */
9812 size = sizeof(maxproc);
9813 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9814 perror("sysctlbyname(\"kern.maxproc\", ?)");
9815 else if (maxproc < 64) {
9817 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9818 perror("sysctlbyname(\"kern.maxproc\", #)");
9821 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9822 char *osversion = new char[size];
9823 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9824 perror("sysctlbyname(\"kern.osversion\", ?)");
9826 System_ = [NSString stringWithUTF8String:osversion];
9828 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9829 char *machine = new char[size];
9830 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9831 perror("sysctlbyname(\"hw.machine\", ?)");
9835 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9836 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9837 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9838 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9842 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9843 NSData *data((NSData *) ecid);
9844 size_t length([data length]);
9845 uint8_t bytes[length];
9846 [data getBytes:bytes];
9847 char string[length * 2 + 1];
9848 for (size_t i(0); i != length; ++i)
9849 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9850 ChipID_ = [NSString stringWithUTF8String:string];
9854 IOObjectRelease(service);
9858 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9860 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9861 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9862 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9864 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9865 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9866 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9868 if (mcc != NULL && mnc != NULL)
9869 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9876 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9877 Build_ = [system objectForKey:@"ProductBuildVersion"];
9878 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9879 Product_ = [info objectForKey:@"SafariProductVersion"];
9880 Safari_ = [info objectForKey:@"CFBundleVersion"];
9883 /* Load Database {{{ */
9885 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9887 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9889 if (Metadata_ == NULL)
9890 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9892 Settings_ = [Metadata_ objectForKey:@"Settings"];
9894 Packages_ = [Metadata_ objectForKey:@"Packages"];
9895 Sections_ = [Metadata_ objectForKey:@"Sections"];
9896 Sources_ = [Metadata_ objectForKey:@"Sources"];
9898 Token_ = [Metadata_ objectForKey:@"Token"];
9901 if (Settings_ != nil)
9902 Role_ = [Settings_ objectForKey:@"Role"];
9904 if (Sections_ == nil) {
9905 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9906 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9909 if (Sources_ == nil) {
9910 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9911 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9916 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9919 if (Packages_ != nil) {
9921 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9925 [Metadata_ removeObjectForKey:@"Packages"];
9931 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9933 #define MobileSubstrate_(name) \
9934 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) \
9935 dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL);
9937 MobileSubstrate_(Activator)
9938 MobileSubstrate_(libstatusbar)
9939 MobileSubstrate_(SimulatedKeyEvents)
9940 MobileSubstrate_(WinterBoard)
9942 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9943 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9945 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9947 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9948 unlink("/tmp/.cydia.fw");
9950 } else if (access("/User", F_OK) != 0 || version < 2) {
9953 system("/usr/libexec/cydia/firmware.sh");
9957 _assert([[NSFileManager defaultManager]
9958 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9959 withIntermediateDirectories:YES
9964 if (access("/tmp/cydia.chk", F_OK) == 0) {
9965 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9966 _assert(errno == ENOENT);
9967 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9968 _assert(errno == ENOENT);
9971 /* APT Initialization {{{ */
9972 _assert(pkgInitConfig(*_config));
9973 _assert(pkgInitSystem(*_config, _system));
9976 _config->Set("APT::Acquire::Translation", lang);
9978 // XXX: this timeout might be important :(
9979 //_config->Set("Acquire::http::Timeout", 15);
9981 _config->Set("Acquire::http::MaxParallel", 3);
9983 /* Color Choices {{{ */
9984 space_ = CGColorSpaceCreateDeviceRGB();
9986 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9987 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9988 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9989 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9990 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9991 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9992 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9993 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9994 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9996 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9997 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9999 /* UIKit Configuration {{{ */
10000 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10001 if ($GSFontSetUseLegacyFontMetrics != NULL)
10002 $GSFontSetUseLegacyFontMetrics(YES);
10004 // XXX: I have a feeling this was important
10005 //UIKeyboardDisableAutomaticAppearance();
10008 Colon_ = UCLocalize("COLON_DELIMITED");
10009 Elision_ = UCLocalize("ELISION");
10010 Error_ = UCLocalize("ERROR");
10011 Warning_ = UCLocalize("WARNING");
10014 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10016 CGColorSpaceRelease(space_);
10017 CFRelease(Locale_);