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(setToken:))
3938 else if (selector == @selector(setViewportWidth:))
3939 return @"setViewportWidth";
3940 else if (selector == @selector(statfs:))
3942 else if (selector == @selector(supports:))
3948 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3949 return [self webScriptNameForSelector:selector] == nil;
3952 - (BOOL) supports:(NSString *)feature {
3953 return [feature isEqualToString:@"window.open"];
3956 - (NSNumber *) getKernelNumber:(NSString *)name {
3957 const char *string([name UTF8String]);
3960 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3961 return (id) [NSNull null];
3963 if (size != sizeof(int))
3964 return (id) [NSNull null];
3967 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3968 return (id) [NSNull null];
3970 return [NSNumber numberWithInt:value];
3973 - (NSString *) getKernelString:(NSString *)name {
3974 const char *string([name UTF8String]);
3977 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3978 return (id) [NSNull null];
3980 char value[size + 1];
3981 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3982 return (id) [NSNull null];
3984 // XXX: just in case you request something ludicrous
3987 return [NSString stringWithCString:value];
3990 - (void) addTrivialSource:(NSString *)href {
3991 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
3994 - (void) refreshSources {
3995 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
3998 - (NSArray *) getAllSources {
3999 return [[Database sharedInstance] sources];
4002 - (NSArray *) getInstalledPackages {
4003 NSArray *packages([[Database sharedInstance] packages]);
4004 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4005 for (Package *package in packages)
4006 if ([package installed] != nil)
4007 [installed addObject:package];
4011 - (Package *) getPackageById:(NSString *)id {
4012 Package *package([[Database sharedInstance] packageWithName:id]);
4017 - (NSArray *) statfs:(NSString *)path {
4020 if (path == nil || statfs([path UTF8String], &stat) == -1)
4023 return [NSArray arrayWithObjects:
4024 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4025 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4026 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4030 - (NSNumber *) du:(NSString *)path {
4031 NSNumber *value(nil);
4034 _assert(pipe(fds) != -1);
4036 pid_t pid(ExecFork());
4038 _assert(dup2(fds[1], 1) != -1);
4039 _assert(close(fds[0]) != -1);
4040 _assert(close(fds[1]) != -1);
4041 /* XXX: this should probably not use du */
4042 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4047 _assert(close(fds[1]) != -1);
4049 if (FILE *du = fdopen(fds[0], "r")) {
4051 while (fgets(line, sizeof(line), du) != NULL) {
4052 size_t length(strlen(line));
4053 while (length != 0 && line[length - 1] == '\n')
4054 line[--length] = '\0';
4055 if (char *tab = strchr(line, '\t')) {
4057 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4062 } else _assert(close(fds[0]));
4066 if (waitpid(pid, &status, 0) == -1)
4069 else _assert(false);
4078 - (void) installPackages:(NSArray *)packages {
4079 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4082 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4083 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4086 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4087 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4090 - (void) setToken:(NSString *)token {
4093 Token_ = [token retain];
4095 [Metadata_ setObject:Token_ forKey:@"Token"];
4099 - (void) setPopupHook:(id)function {
4100 [indirect_ setPopupHook:function];
4103 - (void) setViewportWidth:(float)width {
4104 [indirect_ setViewportWidth:width];
4107 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4108 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4109 unsigned count([arguments count]);
4111 for (unsigned i(0); i != count; ++i)
4112 values[i] = [arguments objectAtIndex:i];
4113 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4116 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4117 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4119 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4121 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4127 /* @ Loading... Indicator {{{ */
4128 @interface CYLoadingIndicator : UIView {
4129 UIActivityIndicatorView *spinner_;
4134 @property (readonly, nonatomic) UILabel *label;
4135 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4139 @implementation CYLoadingIndicator
4141 - (id) initWithFrame:(CGRect)frame {
4142 if ((self = [super initWithFrame:frame]) != nil) {
4143 container_ = [[[UIView alloc] init] autorelease];
4144 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4146 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4147 [spinner_ startAnimating];
4148 [container_ addSubview:spinner_];
4150 label_ = [[[UILabel alloc] init] autorelease];
4151 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4152 [label_ setBackgroundColor:[UIColor clearColor]];
4153 [label_ setTextColor:[UIColor blackColor]];
4154 [label_ setShadowColor:[UIColor whiteColor]];
4155 [label_ setShadowOffset:CGSizeMake(0, 1)];
4156 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4157 [container_ addSubview:label_];
4159 CGSize viewsize = frame.size;
4160 CGSize spinnersize = [spinner_ bounds].size;
4161 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4162 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4164 CGRect containrect = {
4165 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4166 CGSizeMake(bothwidth, spinnersize.height)
4169 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4177 [container_ setFrame:containrect];
4178 [spinner_ setFrame:spinrect];
4179 [label_ setFrame:textrect];
4180 [self addSubview:container_];
4184 - (UILabel *) label {
4188 - (UIActivityIndicatorView *) activityIndicatorView {
4194 /* Emulated Loading Controller {{{ */
4195 @interface CYEmulatedLoadingController : CYViewController <
4197 ConfigurationDelegate
4199 _transient Database *database_;
4200 CYLoadingIndicator *indicator_;
4202 UINavigationBar *navbar_;
4207 @implementation CYEmulatedLoadingController
4210 [self releaseSubviews];
4211 [database_ setDelegate:nil];
4216 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4217 CYAlertView *sheet([[[CYAlertView alloc]
4219 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4220 defaultButtonIndex:0
4223 [sheet setMessage:error];
4224 [sheet yieldToPopupAlertAnimated:YES];
4228 - (void) setProgressTitle:(NSString *)title { }
4229 - (void) setProgressPercent:(float)percent { }
4230 - (void) startProgress { }
4231 - (void) addProgressOutput:(NSString *)output { }
4232 - (bool) isCancelling:(size_t)received { return NO; }
4233 - (void) setConfigurationData:(NSString *)data { }
4235 - (void) repairWithSelector:(SEL)selector {
4236 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("REPAIRING"), nil] waitUntilDone:YES];
4237 [database_ performSelector:selector];
4239 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil] waitUntilDone:YES];
4242 - (id) initWithDatabase:(Database *)database {
4243 if ((self = [super init]) != nil) {
4244 database_ = database;
4245 [database_ setDelegate:self];
4250 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4251 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4253 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4254 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4255 [[self view] addSubview:indicator_];
4257 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4258 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4259 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4260 [[self view] addSubview:tabbar_];
4262 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4263 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4264 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4265 [[self view] addSubview:navbar_];
4268 - (void) releaseSubviews {
4269 [indicator_ release];
4282 /* Cydia Browser Controller {{{ */
4283 @interface CYBrowserController : BrowserController {
4284 CydiaObject *cydia_;
4289 @implementation CYBrowserController
4296 - (NSURL *) navigationURL {
4297 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4300 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4303 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4304 [super webView:view didClearWindowObject:window forFrame:frame];
4306 WebDataSource *source([frame dataSource]);
4307 NSURLResponse *response([source response]);
4309 NSURL *url([response URL]);
4310 NSString *scheme([url scheme]);
4311 NSString *host([url host]);
4313 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4314 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4315 NSDictionary *headers([http allHeaderFields]);
4316 [self setHeaders:headers forHost:host];
4320 [host isEqualToString:@"cydia.saurik.com"] ||
4321 [host hasSuffix:@".cydia.saurik.com"] ||
4322 [scheme isEqualToString:@"file"]
4324 [window setValue:cydia_ forKey:@"cydia"];
4327 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4328 if (System_ != NULL)
4329 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4330 if (Machine_ != NULL)
4331 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4333 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4335 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4338 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4339 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4340 [self _setMoreHeaders:copy];
4344 - (void) setDelegate:(id)delegate {
4345 [super setDelegate:delegate];
4346 [cydia_ setDelegate:delegate];
4350 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4351 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4353 WebView *webview([[webview_ _documentView] webView]);
4355 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4357 NSString *application = package == nil ? @"Cydia" : [NSString
4358 stringWithFormat:@"Cydia/%@",
4363 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4365 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4366 if (Product_ != nil)
4367 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4369 [webview setApplicationNameForUserAgent:application];
4377 @interface NSObject (CydiaScript)
4378 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4381 @implementation NSObject (CydiaScript)
4383 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4389 @implementation NSArray (CydiaScript)
4391 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4392 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4393 for (size_t i(0), e([self count]); i != e; ++i)
4394 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4400 @implementation NSDictionary (CydiaScript)
4402 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4403 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4405 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4412 /* Confirmation Controller {{{ */
4413 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4414 if (!iterator.end())
4415 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4416 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4418 pkgCache::PkgIterator package(dep.TargetPkg());
4421 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4428 @protocol ConfirmationControllerDelegate
4429 - (void) cancelAndClear:(bool)clear;
4430 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4434 @interface ConfirmationController : CYBrowserController {
4435 _transient Database *database_;
4437 UIAlertView *essential_;
4439 NSDictionary *changes_;
4440 NSMutableArray *issues_;
4441 NSDictionary *sizes_;
4446 - (id) initWithDatabase:(Database *)database;
4450 @implementation ConfirmationController
4457 if (essential_ != nil)
4458 [essential_ release];
4463 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4464 NSString *context([alert context]);
4466 if ([context isEqualToString:@"remove"]) {
4467 if (button == [alert cancelButtonIndex]) {
4468 [self dismissModalViewControllerAnimated:YES];
4469 } else if (button == [alert firstOtherButtonIndex]) {
4472 [delegate_ confirmWithNavigationController:[self navigationController]];
4475 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4476 } else if ([context isEqualToString:@"unable"]) {
4477 [self dismissModalViewControllerAnimated:YES];
4478 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4480 [super alertView:alert clickedButtonAtIndex:button];
4484 - (void) _doContinue {
4485 [self dismissModalViewControllerAnimated:YES];
4486 [delegate_ cancelAndClear:NO];
4489 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4490 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4494 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4495 [super webView:view didClearWindowObject:window forFrame:frame];
4497 [window setValue:[changes_ Cydia$webScriptObjectInContext:window] forKey:@"changes"];
4498 [window setValue:[issues_ Cydia$webScriptObjectInContext:window] forKey:@"issues"];
4499 [window setValue:[sizes_ Cydia$webScriptObjectInContext:window] forKey:@"sizes"];
4501 [window setValue:self forKey:@"queue"];
4504 - (id) initWithDatabase:(Database *)database {
4505 if ((self = [super init]) != nil) {
4506 database_ = database;
4508 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4509 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4510 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4511 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4512 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4516 pkgCacheFile &cache([database_ cache]);
4517 NSArray *packages([database_ packages]);
4518 pkgDepCache::Policy *policy([database_ policy]);
4520 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4522 for (Package *package in packages) {
4523 pkgCache::PkgIterator iterator([package iterator]);
4524 NSString *name([package id]);
4526 if ([package broken]) {
4527 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4529 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4531 reasons, @"reasons",
4534 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4538 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4539 pkgCache::DepIterator start;
4540 pkgCache::DepIterator end;
4541 dep.GlobOr(start, end); // ++dep
4543 if (!cache->IsImportantDep(end))
4545 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4548 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4550 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4551 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4552 clauses, @"clauses",
4556 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4558 pkgCache::PkgIterator target(start.TargetPkg());
4559 if (target->ProvidesList != 0)
4560 reason = @"missing";
4562 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4564 reason = @"installed";
4565 installed = [NSString stringWithUTF8String:ver.VerStr()];
4566 } else if (!cache[target].CandidateVerIter(cache).end())
4567 reason = @"uninstalled";
4568 else if (target->ProvidesList == 0)
4569 reason = @"uninstallable";
4571 reason = @"virtual";
4574 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4575 [NSString stringWithUTF8String:start.CompType()], @"operator",
4576 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4579 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4580 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4581 version, @"version",
4583 installed, @"installed",
4586 // yes, seriously. (wtf?)
4594 pkgDepCache::StateCache &state(cache[iterator]);
4596 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4598 if (state.NewInstall())
4599 [installs addObject:name];
4600 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4601 [reinstalls addObject:name];
4602 else if (state.Upgrade())
4603 [upgrades addObject:name];
4604 else if (state.Downgrade())
4605 [downgrades addObject:name];
4606 else if (!state.Delete())
4608 else if (special_r(name))
4609 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4610 [NSNull null], @"package",
4611 [NSArray arrayWithObjects:
4612 [NSDictionary dictionaryWithObjectsAndKeys:
4613 @"Conflicts", @"relationship",
4614 [NSArray arrayWithObjects:
4615 [NSDictionary dictionaryWithObjectsAndKeys:
4617 [NSNull null], @"version",
4618 @"installed", @"reason",
4625 if ([package essential])
4627 [removes addObject:name];
4630 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4631 substrate_ |= DepSubstrate(iterator.CurrentVer());
4636 else if (Advanced_) {
4637 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4639 essential_ = [[UIAlertView alloc]
4640 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4641 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4643 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4645 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4649 [essential_ setContext:@"remove"];
4651 essential_ = [[UIAlertView alloc]
4652 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4653 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4655 cancelButtonTitle:UCLocalize("OKAY")
4656 otherButtonTitles:nil
4659 [essential_ setContext:@"unable"];
4662 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4663 installs, @"installs",
4664 reinstalls, @"reinstalls",
4665 upgrades, @"upgrades",
4666 downgrades, @"downgrades",
4667 removes, @"removes",
4670 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4671 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4672 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4675 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4677 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4678 initWithTitle:UCLocalize("CANCEL")
4679 style:UIBarButtonItemStylePlain
4681 action:@selector(cancelButtonClicked)
4687 - (void) applyRightButton {
4688 if ([issues_ count] == 0 && ![self isLoading])
4689 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4690 initWithTitle:UCLocalize("CONFIRM")
4691 style:UIBarButtonItemStyleDone
4693 action:@selector(confirmButtonClicked)
4696 [[self navigationItem] setRightBarButtonItem:nil];
4700 - (void) cancelButtonClicked {
4701 [self dismissModalViewControllerAnimated:YES];
4702 [delegate_ cancelAndClear:YES];
4706 - (void) confirmButtonClicked {
4707 if (essential_ != nil)
4712 [delegate_ confirmWithNavigationController:[self navigationController]];
4720 /* Progress Data {{{ */
4721 @interface ProgressData : NSObject {
4723 // XXX: should these really both be _transient?
4724 _transient id target_;
4725 _transient id object_;
4728 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4736 @implementation ProgressData
4738 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4739 if ((self = [super init]) != nil) {
4740 selector_ = selector;
4760 /* Progress Controller {{{ */
4761 @interface ProgressController : CYViewController <
4762 ConfigurationDelegate,
4765 _transient Database *database_;
4766 UIProgressBar *progress_;
4767 UITextView *output_;
4768 UITextLabel *status_;
4769 UIPushButton *close_;
4771 SHA1SumValue springlist_;
4772 SHA1SumValue notifyconf_;
4776 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4778 - (void) _retachThread;
4779 - (void) _detachNewThreadData:(ProgressData *)data;
4780 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4786 @protocol ProgressControllerDelegate
4787 - (void) progressControllerIsComplete:(ProgressController *)sender;
4790 @implementation ProgressController
4793 [database_ setDelegate:nil];
4794 [progress_ release];
4803 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4804 if ((self = [super init]) != nil) {
4805 database_ = database;
4806 [database_ setDelegate:self];
4807 delegate_ = delegate;
4809 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4811 progress_ = [[UIProgressBar alloc] init];
4812 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4813 [progress_ setStyle:0];
4815 status_ = [[UITextLabel alloc] init];
4816 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4817 [status_ setColor:[UIColor whiteColor]];
4818 [status_ setBackgroundColor:[UIColor clearColor]];
4819 [status_ setCentersHorizontally:YES];
4820 //[status_ setFont:font];
4822 output_ = [[UITextView alloc] init];
4823 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4824 //[output_ setTextFont:@"Courier New"];
4825 [output_ setFont:[[output_ font] fontWithSize:12]];
4826 [output_ setTextColor:[UIColor whiteColor]];
4827 [output_ setBackgroundColor:[UIColor clearColor]];
4828 [output_ setMarginTop:0];
4829 [output_ setAllowsRubberBanding:YES];
4830 [output_ setEditable:NO];
4831 [[self view] addSubview:output_];
4833 close_ = [[UIPushButton alloc] init];
4834 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4835 [close_ setAutosizesToFit:NO];
4836 [close_ setDrawsShadow:YES];
4837 [close_ setStretchBackground:YES];
4838 [close_ setEnabled:YES];
4839 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4840 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4841 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4842 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4846 - (void) positionViews {
4847 CGRect bounds = [[self view] bounds];
4848 CGSize prgsize = [UIProgressBar defaultSize];
4851 (bounds.size.width - prgsize.width) / 2,
4852 bounds.size.height - prgsize.height - 20
4855 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4857 [progress_ setFrame:prgrect];
4858 [status_ setFrame:CGRectMake(
4860 bounds.size.height - prgsize.height - 50,
4861 bounds.size.width - 20,
4864 [output_ setFrame:CGRectMake(
4867 bounds.size.width - 20,
4868 bounds.size.height - 96
4870 [close_ setFrame:CGRectMake(
4871 (bounds.size.width - closewidth) / 2,
4872 bounds.size.height - prgsize.height - 50,
4878 - (void) viewWillAppear:(BOOL)animated {
4879 [super viewDidAppear:animated];
4880 [[self navigationItem] setHidesBackButton:YES];
4881 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4883 [self positionViews];
4886 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4887 [self positionViews];
4890 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4891 NSString *context([alert context]);
4893 if ([context isEqualToString:@"conffile"]) {
4894 FILE *input = [database_ input];
4895 if (button == [alert cancelButtonIndex])
4896 fprintf(input, "N\n");
4897 else if (button == [alert firstOtherButtonIndex])
4898 fprintf(input, "Y\n");
4903 - (void) closeButtonPushed {
4906 UpdateExternalStatus(0);
4910 [self dismissModalViewControllerAnimated:YES];
4914 [delegate_ terminateWithSuccess];
4915 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4916 [delegate_ suspendWithAnimation:YES];
4918 [delegate_ suspend];*/
4930 system("/usr/bin/sbreload");
4936 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4937 SBReboot(SBSSpringBoardServerPort());
4939 reboot2(RB_AUTOBOOT);
4944 - (void) _retachThread {
4945 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4947 [[self view] addSubview:close_];
4948 [progress_ removeFromSuperview];
4949 [status_ removeFromSuperview];
4951 [database_ popErrorWithTitle:title_];
4952 [delegate_ progressControllerIsComplete:self];
4956 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4959 MMap mmap(file, MMap::ReadOnly);
4961 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4962 if (!(notifyconf_ == sha1.Result()))
4969 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4972 MMap mmap(file, MMap::ReadOnly);
4974 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4975 if (!(springlist_ == sha1.Result()))
4981 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4982 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4983 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4984 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4985 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4989 system("su -c /usr/bin/uicache mobile");
4992 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4994 [delegate_ setStatusBarShowsProgress:NO];
4997 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4998 [[data target] performSelector:[data selector] withObject:[data object]];
4999 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
5002 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
5003 UpdateExternalStatus(1);
5010 title_ = [title retain];
5012 [[self navigationItem] setTitle:title_];
5014 [status_ setText:nil];
5015 [output_ setText:@""];
5016 [progress_ setProgress:0];
5018 [close_ removeFromSuperview];
5019 [[self view] addSubview:progress_];
5020 [[self view] addSubview:status_];
5022 [delegate_ setStatusBarShowsProgress:YES];
5027 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5030 MMap mmap(file, MMap::ReadOnly);
5032 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5033 notifyconf_ = sha1.Result();
5039 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5042 MMap mmap(file, MMap::ReadOnly);
5044 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5045 springlist_ = sha1.Result();
5050 detachNewThreadSelector:@selector(_detachNewThreadData:)
5052 withObject:[[[ProgressData alloc]
5053 initWithSelector:selector
5060 - (void) repairWithSelector:(SEL)selector {
5062 detachNewThreadSelector:selector
5065 title:UCLocalize("REPAIRING")
5069 - (void) setConfigurationData:(NSString *)data {
5071 performSelectorOnMainThread:@selector(_setConfigurationData:)
5077 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
5078 CYAlertView *sheet([[[CYAlertView alloc]
5080 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
5081 defaultButtonIndex:0
5084 [sheet setMessage:error];
5085 [sheet yieldToPopupAlertAnimated:YES];
5089 - (void) setProgressTitle:(NSString *)title {
5091 performSelectorOnMainThread:@selector(_setProgressTitle:)
5097 - (void) setProgressPercent:(float)percent {
5099 performSelectorOnMainThread:@selector(_setProgressPercent:)
5100 withObject:[NSNumber numberWithFloat:percent]
5105 - (void) startProgress {
5108 - (void) addProgressOutput:(NSString *)output {
5110 performSelectorOnMainThread:@selector(_addProgressOutput:)
5116 - (bool) isCancelling:(size_t)received {
5120 - (void) _setConfigurationData:(NSString *)data {
5121 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
5123 if (!conffile_r(data)) {
5124 lprintf("E:invalid conffile\n");
5128 NSString *ofile = conffile_r[1];
5129 //NSString *nfile = conffile_r[2];
5131 UIAlertView *alert = [[[UIAlertView alloc]
5132 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
5133 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
5135 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
5137 UCLocalize("ACCEPT_NEW_COPY"),
5138 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
5142 [alert setContext:@"conffile"];
5146 - (void) _setProgressTitle:(NSString *)title {
5147 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
5148 for (size_t i(0), e([words count]); i != e; ++i) {
5149 NSString *word([words objectAtIndex:i]);
5150 if (Package *package = [database_ packageWithName:word])
5151 [words replaceObjectAtIndex:i withObject:[package name]];
5154 [status_ setText:[words componentsJoinedByString:@" "]];
5157 - (void) _setProgressPercent:(NSNumber *)percent {
5158 [progress_ setProgress:[percent floatValue]];
5161 - (void) _addProgressOutput:(NSString *)output {
5162 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
5163 CGSize size = [output_ contentSize];
5164 CGPoint offset = [output_ contentOffset];
5165 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
5166 CGRect rect = {{0, size.height-1}, {size.width, 1}};
5167 [output_ scrollRectToVisible:rect animated:YES];
5171 - (BOOL) isRunning {
5178 /* Cell Content View {{{ */
5179 @protocol ContentDelegate
5180 - (void) drawContentRect:(CGRect)rect;
5183 @interface ContentView : UIView {
5184 _transient id<ContentDelegate> delegate_;
5189 @implementation ContentView
5191 - (id) initWithFrame:(CGRect)frame {
5192 if ((self = [super initWithFrame:frame]) != nil) {
5193 [self setNeedsDisplayOnBoundsChange:YES];
5197 - (void) setDelegate:(id<ContentDelegate>)delegate {
5198 delegate_ = delegate;
5201 - (void) drawRect:(CGRect)rect {
5202 [super drawRect:rect];
5203 [delegate_ drawContentRect:rect];
5208 /* Cydia TableView Cell {{{ */
5209 @interface CYTableViewCell : UITableViewCell {
5210 ContentView *content_;
5216 @implementation CYTableViewCell
5223 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5224 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5226 if (view == content_) {
5227 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5228 highlighted_ = highlighted;
5231 [super _updateHighlightColorsForView:view highlighted:highlighted];
5234 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5235 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5236 highlighted_ = selected;
5238 [super setSelected:selected animated:animated];
5239 [content_ setNeedsDisplay];
5245 /* Package Cell {{{ */
5246 @interface PackageCell : CYTableViewCell <
5251 NSString *description_;
5259 - (PackageCell *) init;
5260 - (void) setPackage:(Package *)package;
5262 - (void) drawContentRect:(CGRect)rect;
5266 @implementation PackageCell
5268 - (void) clearPackage {
5279 if (description_ != nil) {
5280 [description_ release];
5284 if (source_ != nil) {
5289 if (badge_ != nil) {
5294 if (placard_ != nil) {
5304 [self clearPackage];
5308 - (PackageCell *) init {
5309 CGRect frame(CGRectMake(0, 0, 320, 74));
5310 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5311 UIView *content([self contentView]);
5312 CGRect bounds([content bounds]);
5314 content_ = [[ContentView alloc] initWithFrame:bounds];
5315 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5316 [content addSubview:content_];
5318 [content_ setDelegate:self];
5319 [content_ setOpaque:YES];
5323 - (NSString *) accessibilityLabel {
5324 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5327 - (void) setPackage:(Package *)package {
5328 [self clearPackage];
5331 Source *source = [package source];
5333 icon_ = [[package icon] retain];
5334 name_ = [[package name] retain];
5337 description_ = [package longDescription];
5338 if (description_ == nil)
5339 description_ = [package shortDescription];
5340 if (description_ != nil)
5341 description_ = [description_ retain];
5343 commercial_ = [package isCommercial];
5345 package_ = [package retain];
5347 NSString *label = nil;
5348 bool trusted = false;
5350 if (source != nil) {
5351 label = [source label];
5352 trusted = [source trusted];
5353 } else if ([[package id] isEqualToString:@"firmware"])
5354 label = UCLocalize("APPLE");
5356 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5358 NSString *from(label);
5360 NSString *section = [package simpleSection];
5361 if (section != nil && ![section isEqualToString:label]) {
5362 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5363 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5366 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5367 source_ = [from retain];
5369 if (NSString *purpose = [package primaryPurpose])
5370 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5371 badge_ = [badge_ retain];
5376 if (NSString *mode = [package_ mode]) {
5377 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5378 color = RemovingColor_;
5379 //placard = @"removing";
5381 color = InstallingColor_;
5382 //placard = @"installing";
5385 // XXX: the removing/installing placards are not @2x
5388 color = [UIColor whiteColor];
5390 if ([package installed] != nil)
5391 placard = @"installed";
5396 [content_ setBackgroundColor:color];
5399 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5400 placard_ = [placard_ retain];
5402 [self setNeedsDisplay];
5403 [content_ setNeedsDisplay];
5406 - (void) drawContentRect:(CGRect)rect {
5407 bool highlighted(highlighted_);
5408 float width([self bounds].size.width);
5411 CGContextRef context(UIGraphicsGetCurrentContext());
5412 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5413 CGContextFillRect(context, rect);
5418 rect.size = [icon_ size];
5420 rect.size.width /= 2;
5421 rect.size.height /= 2;
5423 rect.origin.x = 25 - rect.size.width / 2;
5424 rect.origin.y = 25 - rect.size.height / 2;
5426 [icon_ drawInRect:rect];
5429 if (badge_ != nil) {
5431 rect.size = [badge_ size];
5433 rect.size.width /= 2;
5434 rect.size.height /= 2;
5436 rect.origin.x = 36 - rect.size.width / 2;
5437 rect.origin.y = 36 - rect.size.height / 2;
5439 [badge_ drawInRect:rect];
5446 UISetColor(commercial_ ? Purple_ : Black_);
5447 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5448 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5451 UISetColor(commercial_ ? Purplish_ : Gray_);
5452 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5454 if (placard_ != nil)
5455 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5460 /* Section Cell {{{ */
5461 @interface SectionCell : CYTableViewCell <
5473 - (void) setSection:(Section *)section editing:(BOOL)editing;
5477 @implementation SectionCell
5479 - (void) clearSection {
5480 if (basic_ != nil) {
5485 if (section_ != nil) {
5495 if (count_ != nil) {
5502 [self clearSection];
5508 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5509 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5510 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5511 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5512 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5514 UIView *content([self contentView]);
5515 CGRect bounds([content bounds]);
5517 content_ = [[ContentView alloc] initWithFrame:bounds];
5518 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5519 [content addSubview:content_];
5520 [content_ setBackgroundColor:[UIColor whiteColor]];
5522 [content_ setDelegate:self];
5526 - (void) onSwitch:(id)sender {
5527 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5528 if (metadata == nil) {
5529 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5530 [Sections_ setObject:metadata forKey:basic_];
5533 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5537 - (void) setSection:(Section *)section editing:(BOOL)editing {
5538 if (editing != editing_) {
5540 [switch_ removeFromSuperview];
5542 [self addSubview:switch_];
5546 [self clearSection];
5548 if (section == nil) {
5549 name_ = [UCLocalize("ALL_PACKAGES") retain];
5552 basic_ = [section name];
5554 basic_ = [basic_ retain];
5556 section_ = [section localized];
5557 if (section_ != nil)
5558 section_ = [section_ retain];
5560 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5561 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5564 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5567 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5568 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5570 [content_ setNeedsDisplay];
5573 - (void) setFrame:(CGRect)frame {
5574 [super setFrame:frame];
5576 CGRect rect([switch_ frame]);
5577 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5580 - (NSString *) accessibilityLabel {
5584 - (void) drawContentRect:(CGRect)rect {
5585 bool highlighted(highlighted_ && !editing_);
5587 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5592 float width(rect.size.width);
5598 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5600 CGSize size = [count_ sizeWithFont:Font14_];
5604 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5610 /* File Table {{{ */
5611 @interface FileTable : CYViewController <
5612 UITableViewDataSource,
5615 _transient Database *database_;
5618 NSMutableArray *files_;
5622 - (id) initWithDatabase:(Database *)database;
5623 - (void) setPackage:(Package *)package;
5627 @implementation FileTable
5630 [self releaseSubviews];
5639 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5640 return files_ == nil ? 0 : [files_ count];
5643 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5647 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5648 static NSString *reuseIdentifier = @"Cell";
5650 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5652 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5653 [cell setFont:[UIFont systemFontOfSize:16]];
5655 [cell setText:[files_ objectAtIndex:indexPath.row]];
5656 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5661 - (NSURL *) navigationURL {
5662 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5666 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5668 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5669 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5670 [list_ setRowHeight:24.0f];
5671 [list_ setDataSource:self];
5672 [list_ setDelegate:self];
5673 [[self view] addSubview:list_];
5676 - (void) viewDidLoad {
5677 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5680 - (void) releaseSubviews {
5685 - (id) initWithDatabase:(Database *)database {
5686 if ((self = [super init]) != nil) {
5687 database_ = database;
5689 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5693 - (void) setPackage:(Package *)package {
5694 if (package_ != nil) {
5695 [package_ autorelease];
5704 [files_ removeAllObjects];
5706 if (package != nil) {
5707 package_ = [package retain];
5708 name_ = [[package id] retain];
5710 if (NSArray *files = [package files])
5711 [files_ addObjectsFromArray:files];
5713 if ([files_ count] != 0) {
5714 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5715 [files_ removeObjectAtIndex:0];
5716 [files_ sortUsingSelector:@selector(compareByPath:)];
5718 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5719 [stack addObject:@"/"];
5721 for (int i(0), e([files_ count]); i != e; ++i) {
5722 NSString *file = [files_ objectAtIndex:i];
5723 while (![file hasPrefix:[stack lastObject]])
5724 [stack removeLastObject];
5725 NSString *directory = [stack lastObject];
5726 [stack addObject:[file stringByAppendingString:@"/"]];
5727 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5728 ([stack count] - 2) * 3, "",
5729 [file substringFromIndex:[directory length]]
5738 - (void) reloadData {
5741 [self setPackage:[database_ packageWithName:name_]];
5746 /* Package Controller {{{ */
5747 @interface CYPackageController : CYBrowserController <
5748 UIActionSheetDelegate
5750 _transient Database *database_;
5754 NSMutableArray *buttons_;
5755 UIBarButtonItem *button_;
5758 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5762 @implementation CYPackageController
5765 if (package_ != nil)
5778 - (NSURL *) navigationURL {
5779 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5782 /* XXX: this is not safe at all... localization of /fail/ */
5783 - (void) _clickButtonWithName:(NSString *)name {
5784 if ([name isEqualToString:UCLocalize("CLEAR")])
5785 [delegate_ clearPackage:package_];
5786 else if ([name isEqualToString:UCLocalize("INSTALL")])
5787 [delegate_ installPackage:package_];
5788 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5789 [delegate_ installPackage:package_];
5790 else if ([name isEqualToString:UCLocalize("REMOVE")])
5791 [delegate_ removePackage:package_];
5792 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5793 [delegate_ installPackage:package_];
5794 else _assert(false);
5797 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5798 NSString *context([sheet context]);
5800 if ([context isEqualToString:@"modify"]) {
5801 if (button != [sheet cancelButtonIndex]) {
5802 NSString *buttonName = [buttons_ objectAtIndex:button];
5803 [self _clickButtonWithName:buttonName];
5806 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5810 - (bool) _allowJavaScriptPanel {
5815 - (void) _customButtonClicked {
5816 int count([buttons_ count]);
5821 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5823 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5824 [buttons addObjectsFromArray:buttons_];
5826 UIActionSheet *sheet = [[[UIActionSheet alloc]
5829 cancelButtonTitle:nil
5830 destructiveButtonTitle:nil
5831 otherButtonTitles:nil
5834 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5836 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5837 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5839 [sheet setContext:@"modify"];
5841 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5845 // We don't want to allow non-commercial packages to do custom things to the install button,
5846 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5847 - (void) customButtonClicked {
5849 [super customButtonClicked];
5851 [self _customButtonClicked];
5854 - (void) reloadButtonClicked {
5855 // Don't reload a commerical package by tapping the loading button,
5856 // but if it's not an Install button, we should forward it on.
5857 if (![package_ uninstalled])
5858 [self _customButtonClicked];
5861 - (void) applyLoadingTitle {
5862 // Don't show "Loading" as the title. Ever.
5865 - (UIBarButtonItem *) rightButton {
5870 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5871 if ((self = [super init]) != nil) {
5872 database_ = database;
5873 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5874 name_ = [[NSString alloc] initWithString:name];
5875 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5879 - (void) reloadData {
5880 if (package_ != nil)
5881 [package_ autorelease];
5882 package_ = [database_ packageWithName:name_];
5884 [buttons_ removeAllObjects];
5886 if (package_ != nil) {
5889 package_ = [package_ retain];
5890 commercial_ = [package_ isCommercial];
5892 if ([package_ mode] != nil)
5893 [buttons_ addObject:UCLocalize("CLEAR")];
5894 if ([package_ source] == nil);
5895 else if ([package_ upgradableAndEssential:NO])
5896 [buttons_ addObject:UCLocalize("UPGRADE")];
5897 else if ([package_ uninstalled])
5898 [buttons_ addObject:UCLocalize("INSTALL")];
5900 [buttons_ addObject:UCLocalize("REINSTALL")];
5901 if (![package_ uninstalled])
5902 [buttons_ addObject:UCLocalize("REMOVE")];
5909 switch ([buttons_ count]) {
5910 case 0: title = nil; break;
5911 case 1: title = [buttons_ objectAtIndex:0]; break;
5912 default: title = UCLocalize("MODIFY"); break;
5915 button_ = [[UIBarButtonItem alloc]
5917 style:UIBarButtonItemStylePlain
5919 action:@selector(customButtonClicked)
5925 - (bool) isLoading {
5926 return commercial_ ? [super isLoading] : false;
5932 /* Package List Controller {{{ */
5933 @interface PackageListController : CYViewController <
5934 UITableViewDataSource,
5937 _transient Database *database_;
5939 NSMutableArray *packages_;
5940 NSMutableArray *sections_;
5942 NSMutableArray *index_;
5943 NSMutableDictionary *indices_;
5947 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5948 - (void) setDelegate:(id)delegate;
5949 - (void) resetCursor;
5953 @implementation PackageListController
5956 [packages_ release];
5957 [sections_ release];
5966 - (void) deselectWithAnimation:(BOOL)animated {
5967 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5970 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5971 CGRect base = [[self view] bounds];
5972 base.size.height -= bounds.size.height;
5973 base.origin = [list_ frame].origin;
5975 [UIView beginAnimations:nil context:NULL];
5976 [UIView setAnimationBeginsFromCurrentState:YES];
5977 [UIView setAnimationCurve:curve];
5978 [UIView setAnimationDuration:duration];
5979 [list_ setFrame:base];
5980 [UIView commitAnimations];
5983 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5984 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5987 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5988 [self resizeForKeyboardBounds:bounds duration:0];
5991 - (void) keyboardWillShow:(NSNotification *)notification {
5994 NSTimeInterval duration;
5995 UIViewAnimationCurve curve;
5996 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5997 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5998 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5999 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6001 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);
6002 UIViewController *base = self;
6003 while ([base parentViewController] != nil)
6004 base = [base parentViewController];
6005 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6006 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6008 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6011 - (void) keyboardWillHide:(NSNotification *)notification {
6012 NSTimeInterval duration;
6013 UIViewAnimationCurve curve;
6014 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6015 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6017 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6020 - (void) viewWillAppear:(BOOL)animated {
6021 [super viewWillAppear:animated];
6023 [self resizeForKeyboardBounds:CGRectZero];
6024 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6025 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6028 - (void) viewWillDisappear:(BOOL)animated {
6029 [super viewWillDisappear:animated];
6031 [self resizeForKeyboardBounds:CGRectZero];
6032 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6033 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6036 - (void) viewDidAppear:(BOOL)animated {
6037 [super viewDidAppear:animated];
6038 [self deselectWithAnimation:animated];
6041 - (void) didSelectPackage:(Package *)package {
6042 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6043 [view setDelegate:delegate_];
6044 [[self navigationController] pushViewController:view animated:YES];
6047 #if TryIndexedCollation
6048 + (BOOL) hasIndexedCollation {
6049 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6053 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6054 NSInteger count([sections_ count]);
6055 return count == 0 ? 1 : count;
6058 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6059 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6061 return [[sections_ objectAtIndex:section] name];
6064 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6065 if ([sections_ count] == 0)
6067 return [[sections_ objectAtIndex:section] count];
6070 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6071 @synchronized (database_) {
6072 if ([database_ era] != era_)
6075 Section *section([sections_ objectAtIndex:[path section]]);
6076 NSInteger row([path row]);
6077 Package *package([packages_ objectAtIndex:([section row] + row)]);
6078 return [[package retain] autorelease];
6081 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6082 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6084 cell = [[[PackageCell alloc] init] autorelease];
6085 [cell setPackage:[self packageAtIndexPath:path]];
6089 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6090 Package *package([self packageAtIndexPath:path]);
6091 package = [database_ packageWithName:[package id]];
6092 [self didSelectPackage:package];
6095 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6096 // XXX: is 20 the most optimal number here?
6097 return [packages_ count] > 20 ? index_ : nil;
6100 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6101 #if TryIndexedCollation
6102 if ([[self class] hasIndexedCollation]) {
6103 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6110 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6111 if ((self = [super init]) != nil) {
6112 database_ = database;
6113 title_ = [title copy];
6114 [[self navigationItem] setTitle:title_];
6116 #if TryIndexedCollation
6117 if ([[self class] hasIndexedCollation])
6118 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6121 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6123 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6125 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6126 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6128 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6129 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6130 [list_ setRowHeight:73];
6131 [[self view] addSubview:list_];
6133 [list_ setDataSource:self];
6134 [list_ setDelegate:self];
6138 - (void) setDelegate:(id)delegate {
6139 delegate_ = delegate;
6142 - (bool) hasPackage:(Package *)package {
6146 - (void) reloadData {
6149 era_ = [database_ era];
6150 NSArray *packages = [database_ packages];
6152 [packages_ removeAllObjects];
6153 [sections_ removeAllObjects];
6155 _profile(PackageTable$reloadData$Filter)
6156 for (Package *package in packages)
6157 if ([self hasPackage:package])
6158 [packages_ addObject:package];
6161 [indices_ removeAllObjects];
6163 Section *section = nil;
6165 #if TryIndexedCollation
6166 if ([[self class] hasIndexedCollation]) {
6167 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6168 NSArray *titles = [collation sectionIndexTitles];
6171 _profile(PackageTable$reloadData$Section)
6172 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6176 _profile(PackageTable$reloadData$Section$Package)
6177 package = [packages_ objectAtIndex:offset];
6178 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6181 while (secidx < index) {
6184 _profile(PackageTable$reloadData$Section$Allocate)
6185 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6188 _profile(PackageTable$reloadData$Section$Add)
6189 [sections_ addObject:section];
6193 [section addToCount];
6199 [index_ removeAllObjects];
6201 _profile(PackageTable$reloadData$Section)
6202 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6206 _profile(PackageTable$reloadData$Section$Package)
6207 package = [packages_ objectAtIndex:offset];
6208 index = [package index];
6211 if (section == nil || [section index] != index) {
6212 _profile(PackageTable$reloadData$Section$Allocate)
6213 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6216 [index_ addObject:[section name]];
6217 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6219 _profile(PackageTable$reloadData$Section$Add)
6220 [sections_ addObject:section];
6224 [section addToCount];
6229 _profile(PackageTable$reloadData$List)
6234 - (void) resetCursor {
6235 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6240 /* Filtered Package List Controller {{{ */
6241 @interface FilteredPackageListController : PackageListController {
6247 - (void) setObject:(id)object;
6248 - (void) setObject:(id)object forFilter:(SEL)filter;
6250 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6254 @implementation FilteredPackageListController
6262 - (void) setFilter:(SEL)filter {
6265 /* XXX: this is an unsafe optimization of doomy hell */
6266 Method method(class_getInstanceMethod([Package class], filter));
6267 _assert(method != NULL);
6268 imp_ = method_getImplementation(method);
6269 _assert(imp_ != NULL);
6272 - (void) setObject:(id)object {
6278 object_ = [object retain];
6281 - (void) setObject:(id)object forFilter:(SEL)filter {
6282 [self setFilter:filter];
6283 [self setObject:object];
6286 - (bool) hasPackage:(Package *)package {
6287 _profile(FilteredPackageTable$hasPackage)
6288 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6292 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6293 if ((self = [super initWithDatabase:database title:title]) != nil) {
6294 [self setFilter:filter];
6295 [self setObject:object];
6302 /* Home Controller {{{ */
6303 @interface HomeController : CYBrowserController {
6308 @implementation HomeController
6310 + (BOOL) shouldHideNavigationBar {
6314 - (NSURL *) navigationURL {
6315 return [NSURL URLWithString:@"cydia://home"];
6318 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6319 [super _setMoreHeaders:request];
6322 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6323 if (UniqueID_ != nil)
6324 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6326 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6329 - (void) aboutButtonClicked {
6330 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6332 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6333 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6334 [alert setCancelButtonIndex:0];
6337 @"Copyright (C) 2008-2011\n"
6338 "Jay Freeman (saurik)\n"
6339 "saurik@saurik.com\n"
6340 "http://www.saurik.com/"
6346 - (void) viewWillDisappear:(BOOL)animated {
6347 [super viewWillDisappear:animated];
6349 if ([[self class] shouldHideNavigationBar])
6350 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6353 - (void) viewWillAppear:(BOOL)animated {
6354 if (![self hasLoaded])
6355 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6357 [super viewWillAppear:animated];
6359 if ([[self class] shouldHideNavigationBar])
6360 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6363 - (void) viewDidLoad {
6364 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6365 initWithTitle:UCLocalize("ABOUT")
6366 style:UIBarButtonItemStylePlain
6368 action:@selector(aboutButtonClicked)
6374 /* Manage Controller {{{ */
6375 @interface ManageController : CYBrowserController {
6378 - (void) queueStatusDidChange;
6382 @implementation ManageController
6384 - (NSURL *) navigationURL {
6385 return [NSURL URLWithString:@"cydia://manage"];
6388 - (void) viewWillAppear:(BOOL)animated {
6389 if (![self hasLoaded])
6390 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6392 [super viewWillAppear:animated];
6395 - (void) viewDidLoad {
6396 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6397 initWithTitle:UCLocalize("SETTINGS")
6398 style:UIBarButtonItemStylePlain
6400 action:@selector(settingsButtonClicked)
6403 [self queueStatusDidChange];
6406 - (void) settingsButtonClicked {
6407 [delegate_ showSettings];
6411 - (void) queueButtonClicked {
6415 - (void) applyLoadingTitle {
6416 // Disable "Loading" title.
6419 - (void) applyRightButton {
6420 // Disable right button.
6424 - (void) queueStatusDidChange {
6426 if (!IsWildcat_ && Queuing_) {
6427 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6428 initWithTitle:UCLocalize("QUEUE")
6429 style:UIBarButtonItemStyleDone
6431 action:@selector(queueButtonClicked)
6434 [[self navigationItem] setRightBarButtonItem:nil];
6439 - (bool) isLoading {
6440 // Never show as loading.
6447 /* Refresh Bar {{{ */
6448 @interface RefreshBar : UINavigationBar {
6449 UIProgressIndicator *indicator_;
6450 UITextLabel *prompt_;
6451 UIProgressBar *progress_;
6452 UINavigationButton *cancel_;
6457 @implementation RefreshBar
6460 [indicator_ release];
6462 [progress_ release];
6467 - (void) positionViews {
6468 CGRect frame = [cancel_ frame];
6469 frame.size = [cancel_ sizeThatFits:frame.size];
6470 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6471 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6472 [cancel_ setFrame:frame];
6474 CGSize prgsize = {75, 100};
6476 [self frame].size.width - prgsize.width - 10,
6477 ([self frame].size.height - prgsize.height) / 2
6479 [progress_ setFrame:prgrect];
6481 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6482 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6483 CGRect indrect = {{indoffset, indoffset}, indsize};
6484 [indicator_ setFrame:indrect];
6486 CGSize prmsize = {215, indsize.height + 4};
6488 indoffset * 2 + indsize.width,
6489 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6491 [prompt_ setFrame:prmrect];
6494 - (void) setFrame:(CGRect)frame {
6495 [super setFrame:frame];
6496 [self positionViews];
6499 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6500 if ((self = [super initWithFrame:frame]) != nil) {
6501 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6503 [self setBarStyle:UIBarStyleBlack];
6505 UIBarStyle barstyle([self _barStyle:NO]);
6506 bool ugly(barstyle == UIBarStyleDefault);
6508 UIProgressIndicatorStyle style = ugly ?
6509 UIProgressIndicatorStyleMediumBrown :
6510 UIProgressIndicatorStyleMediumWhite;
6512 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6513 [indicator_ setStyle:style];
6514 [indicator_ startAnimation];
6515 [self addSubview:indicator_];
6517 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6518 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6519 [prompt_ setBackgroundColor:[UIColor clearColor]];
6520 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6521 [self addSubview:prompt_];
6523 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6524 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6525 [progress_ setStyle:0];
6526 [self addSubview:progress_];
6528 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6529 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6530 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6531 [cancel_ setBarStyle:barstyle];
6533 [self positionViews];
6538 [cancel_ removeFromSuperview];
6542 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6543 [progress_ setProgress:0];
6544 [self addSubview:cancel_];
6548 [cancel_ removeFromSuperview];
6551 - (void) setPrompt:(NSString *)prompt {
6552 [prompt_ setText:prompt];
6555 - (void) setProgress:(float)progress {
6556 [progress_ setProgress:progress];
6562 @class CYNavigationController;
6564 /* Cydia Tab Bar Controller {{{ */
6565 @interface CYTabBarController : UITabBarController <
6566 UITabBarControllerDelegate,
6569 _transient Database *database_;
6570 RefreshBar *refreshbar_;
6574 // XXX: ok, "updatedelegate_"?...
6575 _transient NSObject<CydiaDelegate> *updatedelegate_;
6578 UIViewController *remembered_;
6579 _transient UIViewController *transient_;
6582 - (NSArray *) navigationURLCollection;
6583 - (void) dropBar:(BOOL)animated;
6584 - (void) beginUpdate;
6585 - (void) raiseBar:(BOOL)animated;
6590 @implementation CYTabBarController
6592 - (void) setUnselectedViewController:(UIViewController *)transient {
6593 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6594 if (transient != nil) {
6595 if (transient_ == nil)
6596 remembered_ = [[controllers objectAtIndex:0] retain];
6597 transient_ = transient;
6598 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6599 [controllers replaceObjectAtIndex:0 withObject:transient_];
6600 [self setSelectedIndex:0];
6601 [self setViewControllers:controllers];
6602 [self concealTabBarSelection];
6603 } else if (remembered_ != nil) {
6604 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6605 transient_ = transient;
6606 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6607 [remembered_ release];
6609 [self setViewControllers:controllers];
6610 [self revealTabBarSelection];
6614 - (UIViewController *) unselectedViewController {
6618 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6619 if ([self unselectedViewController])
6620 [self setUnselectedViewController:nil];
6623 - (NSArray *) navigationURLCollection {
6624 NSMutableArray *items([NSMutableArray array]);
6626 // XXX: Should this deal with transient view controllers?
6627 for (id navigation in [self viewControllers]) {
6628 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6630 [items addObject:stack];
6636 - (void) reloadData {
6637 for (CYViewController *controller in [self viewControllers])
6638 [controller reloadData];
6640 [(CYNavigationController *)[self unselectedViewController] reloadData];
6644 [refreshbar_ release];
6645 [[NSNotificationCenter defaultCenter] removeObserver:self];
6650 - (id) initWithDatabase:(Database *)database {
6651 if ((self = [super init]) != nil) {
6652 database_ = database;
6653 [self setDelegate:self];
6655 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6656 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6658 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6662 - (void) setUpdate:(NSDate *)date {
6666 - (void) beginUpdate {
6667 [refreshbar_ start];
6670 [updatedelegate_ retainNetworkActivityIndicator];
6674 detachNewThreadSelector:@selector(performUpdate)
6680 - (void) performUpdate { _pooled
6682 status.setDelegate(self);
6683 [database_ updateWithStatus:status];
6686 performSelectorOnMainThread:@selector(completeUpdate)
6692 - (void) stopUpdateWithSelector:(SEL)selector {
6694 [updatedelegate_ releaseNetworkActivityIndicator];
6696 [self raiseBar:YES];
6699 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6702 - (void) completeUpdate {
6705 [self stopUpdateWithSelector:@selector(reloadData)];
6708 - (void) cancelUpdate {
6709 [self stopUpdateWithSelector:@selector(updateData)];
6712 - (void) cancelPressed {
6713 [self cancelUpdate];
6720 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6721 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6724 - (void) startProgress {
6727 - (void) setProgressTitle:(NSString *)title {
6729 performSelectorOnMainThread:@selector(_setProgressTitle:)
6735 - (bool) isCancelling:(size_t)received {
6739 - (void) setProgressPercent:(float)percent {
6741 performSelectorOnMainThread:@selector(_setProgressPercent:)
6742 withObject:[NSNumber numberWithFloat:percent]
6747 - (void) addProgressOutput:(NSString *)output {
6749 performSelectorOnMainThread:@selector(_addProgressOutput:)
6755 - (void) _setProgressTitle:(NSString *)title {
6756 [refreshbar_ setPrompt:title];
6759 - (void) _setProgressPercent:(NSNumber *)percent {
6760 [refreshbar_ setProgress:[percent floatValue]];
6763 - (void) _addProgressOutput:(NSString *)output {
6766 - (void) setUpdateDelegate:(id)delegate {
6767 updatedelegate_ = delegate;
6770 - (CGFloat) statusBarHeight {
6771 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6772 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6774 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6778 - (UIView *) transitionView {
6779 if ([self respondsToSelector:@selector(_transitionView)])
6780 return [self _transitionView];
6782 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6785 - (void) dropBar:(BOOL)animated {
6790 UIView *transition([self transitionView]);
6791 [[self view] addSubview:refreshbar_];
6793 CGRect barframe([refreshbar_ frame]);
6795 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6796 barframe.origin.y = [self statusBarHeight];
6798 barframe.origin.y = 0;
6800 [refreshbar_ setFrame:barframe];
6803 [UIView beginAnimations:nil context:NULL];
6805 CGRect viewframe = [transition frame];
6806 viewframe.origin.y += barframe.size.height;
6807 viewframe.size.height -= barframe.size.height;
6808 [transition setFrame:viewframe];
6811 [UIView commitAnimations];
6813 // Ensure bar has the proper width for our view, it might have changed
6814 barframe.size.width = viewframe.size.width;
6815 [refreshbar_ setFrame:barframe];
6817 // XXX: fix Apple's layout bug
6818 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6821 - (void) raiseBar:(BOOL)animated {
6826 UIView *transition([self transitionView]);
6827 [refreshbar_ removeFromSuperview];
6829 CGRect barframe([refreshbar_ frame]);
6832 [UIView beginAnimations:nil context:NULL];
6834 CGRect viewframe = [transition frame];
6835 viewframe.origin.y -= barframe.size.height;
6836 viewframe.size.height += barframe.size.height;
6837 [transition setFrame:viewframe];
6840 [UIView commitAnimations];
6842 // XXX: fix Apple's layout bug
6843 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6847 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6848 // XXX: fix Apple's layout bug
6849 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6853 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6854 bool dropped(dropped_);
6859 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6864 // XXX: fix Apple's layout bug
6865 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6868 - (void) statusBarFrameChanged:(NSNotification *)notification {
6877 /* Cydia Navigation Controller {{{ */
6878 @interface CYNavigationController : UINavigationController {
6879 _transient Database *database_;
6880 _transient id<UINavigationControllerDelegate> delegate_;
6883 - (NSArray *) navigationURLCollection;
6884 - (id) initWithDatabase:(Database *)database;
6885 - (void) reloadData;
6890 @implementation CYNavigationController
6892 - (NSArray *) navigationURLCollection {
6893 NSMutableArray *stack([NSMutableArray array]);
6895 for (CYViewController *controller in [self viewControllers]) {
6896 NSString *url = [[controller navigationURL] absoluteString];
6898 [stack addObject:url];
6904 - (void) reloadData {
6905 for (CYViewController *page in [self viewControllers]) {
6906 // Only reload controllers that have already loaded.
6907 // This prevents a page from accidentally loading too
6908 // early if it hasn't been shown on the screen yet.
6909 if ([page hasLoaded])
6914 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6915 delegate_ = delegate;
6918 - (id) initWithDatabase:(Database *)database {
6919 if ((self = [super init]) != nil) {
6920 database_ = database;
6927 /* Cydia:// Protocol {{{ */
6928 @interface CydiaURLProtocol : NSURLProtocol {
6933 @implementation CydiaURLProtocol
6935 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6936 NSURL *url([request URL]);
6939 NSString *scheme([[url scheme] lowercaseString]);
6940 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6945 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6949 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6950 id<NSURLProtocolClient> client([self client]);
6952 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6954 NSData *data(UIImagePNGRepresentation(icon));
6956 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6957 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6958 [client URLProtocol:self didLoadData:data];
6959 [client URLProtocolDidFinishLoading:self];
6963 - (void) startLoading {
6964 id<NSURLProtocolClient> client([self client]);
6965 NSURLRequest *request([self request]);
6967 NSURL *url([request URL]);
6968 NSString *href([url absoluteString]);
6970 NSString *path([href substringFromIndex:8]);
6971 NSRange slash([path rangeOfString:@"/"]);
6974 if (slash.location == NSNotFound) {
6978 command = [path substringToIndex:slash.location];
6979 path = [path substringFromIndex:(slash.location + 1)];
6982 Database *database([Database sharedInstance]);
6984 if ([command isEqualToString:@"package-icon"]) {
6987 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6988 Package *package([database packageWithName:path]);
6991 UIImage *icon([package icon]);
6992 [self _returnPNGWithImage:icon forRequest:request];
6993 } else if ([command isEqualToString:@"source-icon"]) {
6996 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6997 NSString *source(Simplify(path));
6998 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7000 icon = [UIImage applicationImageNamed:@"unknown.png"];
7001 [self _returnPNGWithImage:icon forRequest:request];
7002 } else if ([command isEqualToString:@"uikit-image"]) {
7005 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7006 UIImage *icon(_UIImageWithName(path));
7007 [self _returnPNGWithImage:icon forRequest:request];
7008 } else if ([command isEqualToString:@"section-icon"]) {
7011 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7012 NSString *section(Simplify(path));
7013 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7015 icon = [UIImage applicationImageNamed:@"unknown.png"];
7016 [self _returnPNGWithImage:icon forRequest:request];
7018 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7022 - (void) stopLoading {
7028 /* Section Controller {{{ */
7029 @interface SectionController : FilteredPackageListController {
7033 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7037 @implementation SectionController
7039 - (NSURL *) navigationURL {
7040 NSString *name = section_;
7044 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7047 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7050 title = UCLocalize("ALL_PACKAGES");
7051 else if (![name isEqual:@""])
7052 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7054 title = UCLocalize("NO_SECTION");
7056 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7063 /* Sections Controller {{{ */
7064 @interface SectionsController : CYViewController <
7065 UITableViewDataSource,
7068 _transient Database *database_;
7069 NSMutableArray *sections_;
7070 NSMutableArray *filtered_;
7075 - (id) initWithDatabase:(Database *)database;
7076 - (void) editButtonClicked;
7080 @implementation SectionsController
7083 [self releaseSubviews];
7084 [sections_ release];
7085 [filtered_ release];
7090 - (NSURL *) navigationURL {
7091 return [NSURL URLWithString:@"cydia://sections"];
7094 - (void) updateNavigationItem {
7095 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7096 if ([sections_ count] == 0) {
7097 [[self navigationItem] setRightBarButtonItem:nil];
7099 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7100 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7102 action:@selector(editButtonClicked)
7103 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7107 - (BOOL) isEditing {
7111 - (void) setEditing:(BOOL)editing {
7112 if ((editing_ = editing))
7115 [delegate_ updateData];
7117 [self updateNavigationItem];
7120 - (void) viewDidAppear:(BOOL)animated {
7121 [super viewDidAppear:animated];
7122 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7125 - (void) viewWillDisappear:(BOOL)animated {
7126 [super viewWillDisappear:animated];
7127 if (editing_) [self setEditing:NO];
7130 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7131 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7135 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7136 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7139 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7143 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7144 static NSString *reuseIdentifier = @"SectionCell";
7146 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7148 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7150 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7155 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7159 Section *section = [self sectionAtIndexPath:indexPath];
7161 SectionController *controller = [[[SectionController alloc]
7162 initWithDatabase:database_
7163 section:[section name]
7165 [controller setDelegate:delegate_];
7167 [[self navigationController] pushViewController:controller animated:YES];
7171 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7173 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7174 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7175 [list_ setRowHeight:45.0f];
7176 [list_ setDataSource:self];
7177 [list_ setDelegate:self];
7178 [[self view] addSubview:list_];
7181 - (void) viewDidLoad {
7182 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7185 - (void) releaseSubviews {
7190 - (id) initWithDatabase:(Database *)database {
7191 if ((self = [super init]) != nil) {
7192 database_ = database;
7194 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7195 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7199 - (void) reloadData {
7202 NSArray *packages = [database_ packages];
7204 [sections_ removeAllObjects];
7205 [filtered_ removeAllObjects];
7207 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7210 for (Package *package in packages) {
7211 NSString *name([package section]);
7212 NSString *key(name == nil ? @"" : name);
7216 _profile(SectionsView$reloadData$Section)
7217 section = [sections objectForKey:key];
7218 if (section == nil) {
7219 _profile(SectionsView$reloadData$Section$Allocate)
7220 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7221 [sections setObject:section forKey:key];
7226 [section addToCount];
7228 _profile(SectionsView$reloadData$Filter)
7229 if (![package valid] || ![package visible])
7237 [sections_ addObjectsFromArray:[sections allValues]];
7239 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7241 for (Section *section in sections_) {
7242 size_t count([section row]);
7246 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7247 [section setCount:count];
7248 [filtered_ addObject:section];
7251 [self updateNavigationItem];
7256 - (void) editButtonClicked {
7257 [self setEditing:(!editing_)];
7263 /* Changes Controller {{{ */
7264 @interface ChangesController : CYViewController <
7265 UITableViewDataSource,
7268 _transient Database *database_;
7270 CFMutableArrayRef packages_;
7271 NSMutableArray *sections_;
7274 BOOL hasSentFirstLoad_;
7277 - (id) initWithDatabase:(Database *)database;
7281 @implementation ChangesController
7284 [self releaseSubviews];
7285 CFRelease(packages_);
7286 [sections_ release];
7291 - (NSURL *) navigationURL {
7292 return [NSURL URLWithString:@"cydia://changes"];
7295 - (void) viewWillAppear:(BOOL)animated {
7296 // Loads after it appears, so don't load beforehand.
7298 [super viewWillAppear:animated];
7301 - (void) viewDidAppear:(BOOL)animated {
7302 [super viewDidAppear:animated];
7304 if (!hasSentFirstLoad_) {
7305 hasSentFirstLoad_ = YES;
7306 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7308 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7312 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7313 NSInteger count([sections_ count]);
7314 return count == 0 ? 1 : count;
7317 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7318 if ([sections_ count] == 0)
7320 return [[sections_ objectAtIndex:section] name];
7323 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7324 if ([sections_ count] == 0)
7326 return [[sections_ objectAtIndex:section] count];
7329 - (Package *) packageAtIndex:(NSUInteger)index {
7330 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7333 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7334 @synchronized (database_) {
7335 if ([database_ era] != era_)
7338 NSUInteger sectionIndex([path section]);
7339 if (sectionIndex >= [sections_ count])
7341 Section *section([sections_ objectAtIndex:sectionIndex]);
7342 NSInteger row([path row]);
7343 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7346 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7347 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7349 cell = [[[PackageCell alloc] init] autorelease];
7350 [cell setPackage:[self packageAtIndexPath:path]];
7354 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7355 Package *package([self packageAtIndexPath:path]);
7356 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7357 [view setDelegate:delegate_];
7358 [[self navigationController] pushViewController:view animated:YES];
7362 - (void) refreshButtonClicked {
7363 [delegate_ beginUpdate];
7364 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7367 - (void) upgradeButtonClicked {
7368 [delegate_ distUpgrade];
7372 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7374 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7375 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7376 [list_ setRowHeight:73];
7377 [list_ setDataSource:self];
7378 [list_ setDelegate:self];
7379 [[self view] addSubview:list_];
7382 - (void) viewDidLoad {
7383 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7386 - (void) releaseSubviews {
7391 - (id) initWithDatabase:(Database *)database {
7392 if ((self = [super init]) != nil) {
7393 database_ = database;
7395 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7396 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7400 - (void) _reloadPackages:(NSArray *)packages {
7401 CFRelease(packages_);
7402 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7405 _profile(ChangesController$_reloadPackages$Filter)
7406 for (Package *package in packages)
7407 if ([package upgradableAndEssential:YES] || [package visible])
7408 CFArrayAppendValue(packages_, package);
7411 _profile(ChangesController$_reloadPackages$radixSort)
7412 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7417 - (void) reloadData {
7418 @synchronized (database_) {
7419 era_ = [database_ era];
7420 NSArray *packages = [database_ packages];
7422 [sections_ removeAllObjects];
7425 UIProgressHUD *hud([delegate_ addProgressHUD]);
7426 [hud setText:UCLocalize("LOADING")];
7427 //NSLog(@"HUD:%@::%@", delegate_, hud);
7428 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7429 [delegate_ removeProgressHUD:hud];
7431 [self _reloadPackages:packages];
7434 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7435 Section *ignored = nil;
7436 Section *section = nil;
7440 bool unseens = false;
7442 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7444 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7445 Package *package = [self packageAtIndex:offset];
7447 BOOL uae = [package upgradableAndEssential:YES];
7451 time_t seen([package seen]);
7453 if (section == nil || last != seen) {
7457 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7460 _profile(ChangesController$reloadData$Allocate)
7461 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7462 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7463 [sections_ addObject:section];
7467 [section addToCount];
7468 } else if ([package ignored]) {
7469 if (ignored == nil) {
7470 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7472 [ignored addToCount];
7475 [upgradable addToCount];
7480 CFRelease(formatter);
7483 Section *last = [sections_ lastObject];
7484 size_t count = [last count];
7485 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7486 [sections_ removeLastObject];
7489 if ([ignored count] != 0)
7490 [sections_ insertObject:ignored atIndex:0];
7492 [sections_ insertObject:upgradable atIndex:0];
7497 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7498 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7499 style:UIBarButtonItemStylePlain
7501 action:@selector(upgradeButtonClicked)
7504 if (![delegate_ updating])
7505 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7506 initWithTitle:UCLocalize("REFRESH")
7507 style:UIBarButtonItemStylePlain
7509 action:@selector(refreshButtonClicked)
7517 /* Search Controller {{{ */
7518 @interface SearchController : FilteredPackageListController <
7521 UISearchBar *search_;
7525 - (id) initWithDatabase:(Database *)database;
7526 - (void) setSearchTerm:(NSString *)term;
7527 - (void) reloadData;
7531 @implementation SearchController
7538 - (NSURL *) navigationURL {
7539 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7540 return [NSURL URLWithString:@"cydia://search"];
7542 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7545 - (void) setSearchTerm:(NSString *)searchTerm {
7546 [search_ setText:searchTerm];
7550 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7551 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7552 [search_ resignFirstResponder];
7556 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7557 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7561 - (id) initWithDatabase:(Database *)database {
7562 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7563 search_ = [[UISearchBar alloc] init];
7567 - (void) viewDidAppear:(BOOL)animated {
7568 [super viewDidAppear:animated];
7570 if (!searchloaded_) {
7571 searchloaded_ = YES;
7572 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7573 [search_ layoutSubviews];
7574 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7576 UITextField *textField;
7577 if ([search_ respondsToSelector:@selector(searchField)])
7578 textField = [search_ searchField];
7580 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7582 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7583 [search_ setDelegate:self];
7584 [textField setEnablesReturnKeyAutomatically:NO];
7585 [[self navigationItem] setTitleView:textField];
7589 - (void) reloadData {
7590 [self setObject:[search_ text]];
7595 - (void) didSelectPackage:(Package *)package {
7596 [search_ resignFirstResponder];
7597 [super didSelectPackage:package];
7602 /* Package Settings Controller {{{ */
7603 @interface PackageSettingsController : CYViewController <
7604 UITableViewDataSource,
7607 _transient Database *database_;
7610 UITableView *table_;
7611 UISwitch *subscribedSwitch_;
7612 UISwitch *ignoredSwitch_;
7613 UITableViewCell *subscribedCell_;
7614 UITableViewCell *ignoredCell_;
7617 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7621 @implementation PackageSettingsController
7624 [self releaseSubviews];
7631 - (NSURL *) navigationURL {
7632 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7635 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7636 if (package_ == nil)
7639 if ([package_ installed] == nil)
7645 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7646 if (package_ == nil)
7649 // both sections contain just one item right now.
7653 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7657 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7659 return UCLocalize("SHOW_ALL_CHANGES_EX");
7661 return UCLocalize("IGNORE_UPGRADES_EX");
7664 - (void) onSubscribed:(id)control {
7665 bool value([control isOn]);
7666 if (package_ == nil)
7668 if ([package_ setSubscribed:value])
7669 [delegate_ updateData];
7672 - (void) _updateIgnored {
7673 const char *package([name_ UTF8String]);
7674 bool on([ignoredSwitch_ isOn]);
7676 pid_t pid(ExecFork());
7678 FILE *dpkg(popen("dpkg --set-selections", "w"));
7679 fwrite(package, strlen(package), 1, dpkg);
7682 fwrite(" hold\n", 6, 1, dpkg);
7684 fwrite(" install\n", 9, 1, dpkg);
7694 int result(waitpid(pid, &status, 0));
7697 _assert(result == pid);
7703 - (void) onIgnored:(id)control {
7704 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7705 [invocation setTarget:self];
7706 [invocation setSelector:@selector(_updateIgnored)];
7708 [delegate_ reloadDataWithInvocation:invocation];
7711 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7712 if (package_ == nil)
7715 switch ([indexPath section]) {
7716 case 0: return subscribedCell_;
7717 case 1: return ignoredCell_;
7726 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7728 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7729 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7730 [table_ setDataSource:self];
7731 [table_ setDelegate:self];
7732 [[self view] addSubview:table_];
7734 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7735 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7736 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7738 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7739 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7740 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7742 subscribedCell_ = [[UITableViewCell alloc] init];
7743 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7744 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7745 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7747 ignoredCell_ = [[UITableViewCell alloc] init];
7748 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7749 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7750 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7753 - (void) viewDidLoad {
7754 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7757 - (void) releaseSubviews {
7758 [ignoredCell_ release];
7761 [subscribedCell_ release];
7762 subscribedCell_ = nil;
7767 [ignoredSwitch_ release];
7768 ignoredSwitch_ = nil;
7770 [subscribedSwitch_ release];
7771 subscribedSwitch_ = nil;
7774 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7775 if ((self = [super init]) != nil) {
7776 database_ = database;
7777 name_ = [package retain];
7781 - (void) reloadData {
7784 if (package_ != nil)
7785 [package_ autorelease];
7786 package_ = [database_ packageWithName:name_];
7788 if (package_ != nil) {
7789 package_ = [package_ retain];
7790 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7791 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7792 } // XXX: what now, G?
7794 [table_ reloadData];
7800 /* Installed Controller {{{ */
7801 @interface InstalledController : FilteredPackageListController {
7805 - (id) initWithDatabase:(Database *)database;
7807 - (void) updateRoleButton;
7808 - (void) queueStatusDidChange;
7812 @implementation InstalledController
7818 - (NSURL *) navigationURL {
7819 return [NSURL URLWithString:@"cydia://installed"];
7822 - (id) initWithDatabase:(Database *)database {
7823 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7824 [self updateRoleButton];
7825 [self queueStatusDidChange];
7830 - (void) queueButtonClicked {
7835 - (void) queueStatusDidChange {
7839 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7840 initWithTitle:UCLocalize("QUEUE")
7841 style:UIBarButtonItemStyleDone
7843 action:@selector(queueButtonClicked)
7846 [[self navigationItem] setLeftBarButtonItem:nil];
7852 - (void) updateRoleButton {
7853 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7854 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7855 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7856 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7858 action:@selector(roleButtonClicked)
7862 - (void) roleButtonClicked {
7863 [self setObject:[NSNumber numberWithBool:expert_]];
7867 [self updateRoleButton];
7873 /* Source Cell {{{ */
7874 @interface SourceCell : CYTableViewCell <
7882 - (void) setSource:(Source *)source;
7886 @implementation SourceCell
7888 - (void) clearSource {
7898 - (void) setSource:(Source *)source {
7902 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7904 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7905 icon_ = [icon_ retain];
7907 origin_ = [[source name] retain];
7908 label_ = [[source uri] retain];
7910 [content_ setNeedsDisplay];
7918 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7919 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7920 UIView *content([self contentView]);
7921 CGRect bounds([content bounds]);
7923 content_ = [[ContentView alloc] initWithFrame:bounds];
7924 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7925 [content_ setBackgroundColor:[UIColor whiteColor]];
7926 [content addSubview:content_];
7928 [content_ setDelegate:self];
7929 [content_ setOpaque:YES];
7933 - (NSString *) accessibilityLabel {
7937 - (void) drawContentRect:(CGRect)rect {
7938 bool highlighted(highlighted_);
7939 float width(rect.size.width);
7942 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7949 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7953 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7958 /* Source Controller {{{ */
7959 @interface SourceController : FilteredPackageListController {
7960 _transient Source *source_;
7964 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7968 @implementation SourceController
7970 - (NSURL *) navigationURL {
7971 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7974 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7975 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7977 key_ = [[source key] retain];
7981 - (void) reloadData {
7982 source_ = [database_ sourceWithKey:key_];
7984 key_ = [[source_ key] retain];
7985 [self setObject:source_];
7986 [[self navigationItem] setTitle:[source_ label]];
7993 /* Sources Controller {{{ */
7994 @interface SourcesController : CYViewController <
7995 UITableViewDataSource,
7998 _transient Database *database_;
8000 NSMutableArray *sources_;
8004 UIProgressHUD *hud_;
8007 //NSURLConnection *installer_;
8008 NSURLConnection *trivial_;
8009 NSURLConnection *trivial_bz2_;
8010 NSURLConnection *trivial_gz_;
8011 //NSURLConnection *automatic_;
8016 - (id) initWithDatabase:(Database *)database;
8017 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8021 @implementation SourcesController
8023 - (void) _releaseConnection:(NSURLConnection *)connection {
8024 if (connection != nil) {
8025 [connection cancel];
8026 //[connection setDelegate:nil];
8027 [connection release];
8032 [self releaseSubviews];
8038 //[self _releaseConnection:installer_];
8039 [self _releaseConnection:trivial_];
8040 [self _releaseConnection:trivial_gz_];
8041 [self _releaseConnection:trivial_bz2_];
8042 //[self _releaseConnection:automatic_];
8048 - (NSURL *) navigationURL {
8049 return [NSURL URLWithString:@"cydia://sources"];
8052 - (void) viewDidAppear:(BOOL)animated {
8053 [super viewDidAppear:animated];
8054 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8057 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8058 return offset_ == 0 ? 1 : 2;
8061 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8062 switch (section + (offset_ == 0 ? 1 : 0)) {
8063 case 0: return UCLocalize("ENTERED_BY_USER");
8064 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8070 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8071 int count = [sources_ count];
8073 case 0: return (offset_ == 0 ? count : offset_);
8074 case 1: return count - offset_;
8080 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8082 switch (indexPath.section) {
8083 case 0: idx = indexPath.row; break;
8084 case 1: idx = indexPath.row + offset_; break;
8088 return [sources_ objectAtIndex:idx];
8091 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8092 static NSString *cellIdentifier = @"SourceCell";
8094 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8095 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8096 [cell setSource:[self sourceAtIndexPath:indexPath]];
8097 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8102 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8103 Source *source = [self sourceAtIndexPath:indexPath];
8105 SourceController *controller = [[[SourceController alloc]
8106 initWithDatabase:database_
8110 [controller setDelegate:delegate_];
8112 [[self navigationController] pushViewController:controller animated:YES];
8115 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8116 Source *source = [self sourceAtIndexPath:indexPath];
8117 return [source record] != nil;
8120 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8121 Source *source = [self sourceAtIndexPath:indexPath];
8122 [Sources_ removeObjectForKey:[source key]];
8123 [delegate_ syncData];
8127 [delegate_ addTrivialSource:href_];
8128 [delegate_ syncData];
8131 - (NSString *) getWarning {
8132 NSString *href(href_);
8133 NSRange colon([href rangeOfString:@"://"]);
8134 if (colon.location != NSNotFound)
8135 href = [href substringFromIndex:(colon.location + 3)];
8136 href = [href stringByAddingPercentEscapes];
8137 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8138 href = [href stringByCachingURLWithCurrentCDN];
8140 NSURL *url([NSURL URLWithString:href]);
8142 NSStringEncoding encoding;
8143 NSError *error(nil);
8145 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8146 return [warning length] == 0 ? nil : warning;
8150 - (void) _endConnection:(NSURLConnection *)connection {
8151 // XXX: the memory management in this method is horribly awkward
8153 NSURLConnection **field = NULL;
8154 if (connection == trivial_)
8156 else if (connection == trivial_bz2_)
8157 field = &trivial_bz2_;
8158 else if (connection == trivial_gz_)
8159 field = &trivial_gz_;
8160 _assert(field != NULL);
8161 [connection release];
8166 trivial_bz2_ == nil &&
8172 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8175 UIAlertView *alert = [[[UIAlertView alloc]
8176 initWithTitle:UCLocalize("SOURCE_WARNING")
8179 cancelButtonTitle:UCLocalize("CANCEL")
8181 UCLocalize("ADD_ANYWAY"),
8185 [alert setContext:@"warning"];
8186 [alert setNumberOfRows:1];
8190 } else if (error_ != nil) {
8191 UIAlertView *alert = [[[UIAlertView alloc]
8192 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8193 message:[error_ localizedDescription]
8195 cancelButtonTitle:UCLocalize("OK")
8196 otherButtonTitles:nil
8199 [alert setContext:@"urlerror"];
8202 UIAlertView *alert = [[[UIAlertView alloc]
8203 initWithTitle:UCLocalize("NOT_REPOSITORY")
8204 message:UCLocalize("NOT_REPOSITORY_EX")
8206 cancelButtonTitle:UCLocalize("OK")
8207 otherButtonTitles:nil
8210 [alert setContext:@"trivial"];
8214 [delegate_ setStatusBarShowsProgress:NO];
8215 [delegate_ removeProgressHUD:hud_];
8225 if (error_ != nil) {
8232 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8233 switch ([response statusCode]) {
8239 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8240 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8242 error_ = [error retain];
8243 [self _endConnection:connection];
8246 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8247 [self _endConnection:connection];
8250 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8251 NSMutableURLRequest *request = [NSMutableURLRequest
8252 requestWithURL:[NSURL URLWithString:href]
8253 cachePolicy:NSURLRequestUseProtocolCachePolicy
8254 timeoutInterval:120.0
8257 [request setHTTPMethod:method];
8259 if (Machine_ != NULL)
8260 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8261 if (UniqueID_ != nil)
8262 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8264 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8266 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8269 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8270 NSString *context([alert context]);
8272 if ([context isEqualToString:@"source"]) {
8275 NSString *href = [[alert textField] text];
8277 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8279 if (![href hasSuffix:@"/"])
8280 href_ = [href stringByAppendingString:@"/"];
8283 href_ = [href_ retain];
8285 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8286 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8287 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8288 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8292 // XXX: this is stupid
8293 hud_ = [[delegate_ addProgressHUD] retain];
8294 [hud_ setText:UCLocalize("VERIFYING_URL")];
8303 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8304 } else if ([context isEqualToString:@"trivial"])
8305 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8306 else if ([context isEqualToString:@"urlerror"])
8307 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8308 else if ([context isEqualToString:@"warning"]) {
8323 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8328 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8330 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8331 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8332 [list_ setRowHeight:56];
8333 [list_ setDataSource:self];
8334 [list_ setDelegate:self];
8335 [[self view] addSubview:list_];
8338 - (void) viewDidLoad {
8339 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8340 [self updateButtonsForEditingStatus:NO animated:NO];
8343 - (void) releaseSubviews {
8348 - (id) initWithDatabase:(Database *)database {
8349 if ((self = [super init]) != nil) {
8350 database_ = database;
8351 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8355 - (void) reloadData {
8359 if (!list.ReadMainList())
8362 [sources_ removeAllObjects];
8363 [sources_ addObjectsFromArray:[database_ sources]];
8365 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8368 int count([sources_ count]);
8370 for (int i = 0; i != count; i++) {
8371 if ([[sources_ objectAtIndex:i] record] == nil)
8376 [list_ setEditing:NO];
8377 [self updateButtonsForEditingStatus:NO animated:NO];
8381 - (void) showAddSourcePrompt {
8382 UIAlertView *alert = [[[UIAlertView alloc]
8383 initWithTitle:UCLocalize("ENTER_APT_URL")
8386 cancelButtonTitle:UCLocalize("CANCEL")
8388 UCLocalize("ADD_SOURCE"),
8392 [alert setContext:@"source"];
8393 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8395 [alert setNumberOfRows:1];
8396 [alert addTextFieldWithValue:@"http://" label:@""];
8398 UITextInputTraits *traits = [[alert textField] textInputTraits];
8399 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8400 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8401 [traits setKeyboardType:UIKeyboardTypeURL];
8402 // XXX: UIReturnKeyDone
8403 [traits setReturnKeyType:UIReturnKeyNext];
8408 - (void) addButtonClicked {
8409 [self showAddSourcePrompt];
8412 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8413 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8414 initWithTitle:UCLocalize("ADD")
8415 style:UIBarButtonItemStylePlain
8417 action:@selector(addButtonClicked)
8418 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8420 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8421 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8422 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8424 action:@selector(editButtonClicked)
8425 ] autorelease] animated:animated];
8427 if (IsWildcat_ && !editing)
8428 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8429 initWithTitle:UCLocalize("SETTINGS")
8430 style:UIBarButtonItemStylePlain
8432 action:@selector(settingsButtonClicked)
8436 - (void) settingsButtonClicked {
8437 [delegate_ showSettings];
8440 - (void) editButtonClicked {
8441 [list_ setEditing:![list_ isEditing] animated:YES];
8443 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8449 /* Settings Controller {{{ */
8450 @interface SettingsController : CYViewController <
8451 UITableViewDataSource,
8454 _transient Database *database_;
8455 // XXX: ok, "roledelegate_"?...
8456 _transient id roledelegate_;
8457 UITableView *table_;
8458 UISegmentedControl *segment_;
8462 - (void) showDoneButton;
8463 - (void) resizeSegmentedControl;
8467 @implementation SettingsController
8470 [self releaseSubviews];
8476 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8478 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8479 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8480 [table_ setDelegate:self];
8481 [table_ setDataSource:self];
8482 [[self view] addSubview:table_];
8484 NSArray *items = [NSArray arrayWithObjects:
8486 UCLocalize("HACKER"),
8487 UCLocalize("DEVELOPER"),
8489 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8490 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8491 [container_ addSubview:segment_];
8494 - (void) viewDidLoad {
8495 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8498 if ([Role_ isEqualToString:@"User"]) index = 0;
8499 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8500 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8502 [segment_ setSelectedSegmentIndex:index];
8503 [self showDoneButton];
8506 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8507 [self resizeSegmentedControl];
8510 - (void) releaseSubviews {
8517 [container_ release];
8521 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8522 if ((self = [super init]) != nil) {
8523 database_ = database;
8524 roledelegate_ = delegate;
8528 - (void) resizeSegmentedControl {
8529 CGFloat width = [[self view] frame].size.width;
8530 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8533 - (void) viewWillAppear:(BOOL)animated {
8534 [super viewWillAppear:animated];
8536 [self resizeSegmentedControl];
8539 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8540 [self resizeSegmentedControl];
8543 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8544 [self resizeSegmentedControl];
8548 NSString *role(nil);
8550 switch ([segment_ selectedSegmentIndex]) {
8551 case 0: role = @"User"; break;
8552 case 1: role = @"Hacker"; break;
8553 case 2: role = @"Developer"; break;
8558 if (![role isEqualToString:Role_]) {
8559 bool rolling(Role_ == nil);
8562 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8566 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8570 [roledelegate_ loadData];
8572 [roledelegate_ updateData];
8576 - (void) segmentChanged:(UISegmentedControl *)control {
8577 [self showDoneButton];
8580 - (void) saveAndClose {
8583 [[self navigationItem] setRightBarButtonItem:nil];
8584 [[self navigationController] dismissModalViewControllerAnimated:YES];
8587 - (void) doneButtonClicked {
8588 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8589 [spinner startAnimating];
8590 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8591 [[self navigationItem] setRightBarButtonItem:spinItem];
8593 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8596 - (void) showDoneButton {
8597 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8598 initWithTitle:UCLocalize("DONE")
8599 style:UIBarButtonItemStyleDone
8601 action:@selector(doneButtonClicked)
8602 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8605 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8606 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8610 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8614 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8615 return nil; // This method is required by the protocol.
8618 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8620 return UCLocalize("ROLE_EX");
8622 return [NSString stringWithFormat:
8623 @"%@: %@\n%@: %@\n%@: %@",
8624 UCLocalize("USER"), UCLocalize("USER_EX"),
8625 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8626 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8631 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8632 return section == 3 ? 44.0f : 0;
8635 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8636 return section == 3 ? container_ : nil;
8639 - (void) reloadData {
8641 [table_ reloadData];
8646 /* Stash Controller {{{ */
8647 @interface StashController : CYViewController {
8648 UIActivityIndicatorView *spinner_;
8655 @implementation StashController
8658 [self releaseSubviews];
8664 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8665 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8667 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8668 CGRect spinrect = [spinner_ frame];
8669 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8670 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8671 [spinner_ setFrame:spinrect];
8672 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8673 [[self view] addSubview:spinner_];
8674 [spinner_ startAnimating];
8677 captrect.size.width = [[self view] frame].size.width;
8678 captrect.size.height = 40.0f;
8679 captrect.origin.x = 0;
8680 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8681 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8682 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8683 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8684 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8685 [caption_ setTextColor:[UIColor whiteColor]];
8686 [caption_ setBackgroundColor:[UIColor clearColor]];
8687 [caption_ setShadowColor:[UIColor blackColor]];
8688 [caption_ setTextAlignment:UITextAlignmentCenter];
8689 [[self view] addSubview:caption_];
8692 statusrect.size.width = [[self view] frame].size.width;
8693 statusrect.size.height = 30.0f;
8694 statusrect.origin.x = 0;
8695 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8696 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8697 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8698 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8699 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8700 [status_ setTextColor:[UIColor whiteColor]];
8701 [status_ setBackgroundColor:[UIColor clearColor]];
8702 [status_ setShadowColor:[UIColor blackColor]];
8703 [status_ setTextAlignment:UITextAlignmentCenter];
8704 [[self view] addSubview:status_];
8707 - (void) releaseSubviews {
8721 @interface Cydia : UIApplication <
8722 ConfirmationControllerDelegate,
8723 ProgressControllerDelegate,
8725 UINavigationControllerDelegate,
8726 UITabBarControllerDelegate
8728 // XXX: evaluate all fields for _transient
8731 CYTabBarController *tabbar_;
8733 NSMutableArray *essential_;
8734 NSMutableArray *broken_;
8736 Database *database_;
8743 StashController *stash_;
8752 @implementation Cydia
8754 - (void) beginUpdate {
8755 [tabbar_ beginUpdate];
8759 return [tabbar_ updating];
8763 if ([broken_ count] != 0) {
8764 int count = [broken_ count];
8766 UIAlertView *alert = [[[UIAlertView alloc]
8767 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8768 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8770 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8772 UCLocalize("TEMPORARY_IGNORE"),
8776 [alert setContext:@"fixhalf"];
8778 } else if (!Ignored_ && [essential_ count] != 0) {
8779 int count = [essential_ count];
8781 UIAlertView *alert = [[[UIAlertView alloc]
8782 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8783 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8785 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8787 UCLocalize("UPGRADE_ESSENTIAL"),
8788 UCLocalize("COMPLETE_UPGRADE"),
8792 [alert setContext:@"upgrade"];
8797 - (void) _saveConfig {
8803 NSString *error(nil);
8805 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8807 NSError *error(nil);
8808 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8809 NSLog(@"failure to save metadata data: %@", error);
8814 NSLog(@"failure to serialize metadata: %@", error);
8819 // Navigation controller for the queuing badge.
8820 - (CYNavigationController *) queueNavigationController {
8821 NSArray *controllers = [tabbar_ viewControllers];
8822 return [controllers objectAtIndex:3];
8825 - (void) _updateData {
8828 [tabbar_ reloadData];
8830 CYNavigationController *navigation = [self queueNavigationController];
8832 id queuedelegate = nil;
8833 if ([[navigation viewControllers] count] > 0)
8834 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8836 [queuedelegate queueStatusDidChange];
8837 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8840 - (void) _refreshIfPossible {
8841 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8843 bool recently = false;
8844 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8845 if (update != nil) {
8846 NSTimeInterval interval([update timeIntervalSinceNow]);
8847 if (interval <= 0 && interval > -(15*60))
8851 // Don't automatic refresh if:
8852 // - We already refreshed recently.
8853 // - We already auto-refreshed this launch.
8854 // - Auto-refresh is disabled.
8855 if (recently || loaded_ || ManualRefresh) {
8856 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8858 // If we are cancelling, we need to make sure it knows it's already loaded.
8862 // We are going to load, so remember that.
8866 SCNetworkReachabilityFlags flags; {
8867 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8868 SCNetworkReachabilityGetFlags(reachability, &flags);
8869 CFRelease(reachability);
8872 // XXX: this elaborate mess is what Apple is using to determine this? :(
8873 // XXX: do we care if the user has to intervene? maybe that's ok?
8875 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8876 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8877 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8878 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8879 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8880 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8884 // If we can reach the server, auto-refresh!
8886 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8891 - (void) refreshIfPossible {
8892 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8895 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8896 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8897 [hud setText:UCLocalize("RELOADING_DATA")];
8899 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8902 [self removeProgressHUD:hud];
8906 [essential_ removeAllObjects];
8907 [broken_ removeAllObjects];
8909 NSArray *packages([database_ packages]);
8910 for (Package *package in packages) {
8912 [broken_ addObject:package];
8913 if ([package upgradableAndEssential:NO]) {
8914 if ([package essential])
8915 [essential_ addObject:package];
8920 NSLog(@"changes:#%u", changes);
8922 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8925 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8926 [changesItem setBadgeValue:badge];
8927 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8928 [self setApplicationIconBadgeNumber:changes];
8931 [changesItem setBadgeValue:nil];
8932 [changesItem setAnimatedBadge:NO];
8933 [self setApplicationIconBadgeNumber:0];
8938 [self refreshIfPossible];
8941 - (void) updateData {
8952 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8953 _assert(file != NULL);
8955 for (NSString *key in [Sources_ allKeys]) {
8956 NSDictionary *source([Sources_ objectForKey:key]);
8958 fprintf(file, "%s %s %s\n",
8959 [[source objectForKey:@"Type"] UTF8String],
8960 [[source objectForKey:@"URI"] UTF8String],
8961 [[source objectForKey:@"Distribution"] UTF8String]
8967 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8968 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8970 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8971 [tabbar_ presentModalViewController:navigation animated:YES];
8974 detachNewThreadSelector:@selector(update_)
8977 title:UCLocalize("UPDATING_SOURCES")
8981 - (void) addTrivialSource:(NSString *)href {
8982 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8985 @"./", @"Distribution",
8986 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8991 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8992 @synchronized (self) {
8993 [self _reloadDataWithInvocation:invocation];
8997 - (void) reloadData {
8998 [self reloadDataWithInvocation:nil];
9002 pkgProblemResolver *resolver = [database_ resolver];
9004 resolver->InstallProtect();
9005 if (!resolver->Resolve(true))
9010 // XXX: this is a really crappy way of doing this.
9011 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9012 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9013 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9014 if ([tabbar_ updating])
9015 [tabbar_ cancelUpdate];
9017 if (![database_ prepare])
9020 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9021 [page setDelegate:self];
9022 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9023 [confirm_ setDelegate:self];
9026 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9027 [tabbar_ presentModalViewController:confirm_ animated:YES];
9033 @synchronized (self) {
9038 - (void) clearPackage:(Package *)package {
9039 @synchronized (self) {
9046 - (void) installPackages:(NSArray *)packages {
9047 @synchronized (self) {
9048 for (Package *package in packages)
9055 - (void) installPackage:(Package *)package {
9056 @synchronized (self) {
9063 - (void) removePackage:(Package *)package {
9064 @synchronized (self) {
9071 - (void) distUpgrade {
9072 @synchronized (self) {
9073 if (![database_ upgrade])
9080 @synchronized (self) {
9081 [self _reloadDataWithInvocation:nil];
9085 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9088 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
9090 if (navigation != nil) {
9091 [navigation pushViewController:progress animated:YES];
9093 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
9095 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9096 [tabbar_ presentModalViewController:navigation animated:YES];
9100 detachNewThreadSelector:@selector(perform)
9103 title:UCLocalize("RUNNING")
9109 - (void) progressControllerIsComplete:(ProgressController *)progress {
9114 - (void) showSettings {
9115 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9116 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9118 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9119 [tabbar_ presentModalViewController:nav animated:YES];
9122 - (void) retainNetworkActivityIndicator {
9123 if (activity_++ == 0)
9124 [self setNetworkActivityIndicatorVisible:YES];
9127 - (void) releaseNetworkActivityIndicator {
9128 if (--activity_ == 0)
9129 [self setNetworkActivityIndicatorVisible:NO];
9132 - (void) cancelAndClear:(bool)clear {
9133 @synchronized (self) {
9145 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9146 NSString *context([alert context]);
9148 if ([context isEqualToString:@"fixhalf"]) {
9149 if (button == [alert cancelButtonIndex]) {
9150 @synchronized (self) {
9151 for (Package *broken in broken_) {
9154 NSString *id = [broken id];
9155 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9156 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9157 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9158 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9164 } else if (button == [alert firstOtherButtonIndex]) {
9165 [broken_ removeAllObjects];
9169 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9170 } else if ([context isEqualToString:@"upgrade"]) {
9171 if (button == [alert firstOtherButtonIndex]) {
9172 @synchronized (self) {
9173 for (Package *essential in essential_)
9174 [essential install];
9179 } else if (button == [alert firstOtherButtonIndex] + 1) {
9181 } else if (button == [alert cancelButtonIndex]) {
9185 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9189 - (void) system:(NSString *)command { _pooled
9191 system([command UTF8String]);
9195 - (void) applicationWillSuspend {
9197 [super applicationWillSuspend];
9200 - (BOOL) isSafeToSuspend {
9201 // Use external process status API internally.
9202 // This is probably a really bad idea.
9203 // XXX: what is the point of this? does this solve anything at all?
9204 uint64_t status = 0;
9206 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9207 notify_get_state(notify_token, &status);
9208 notify_cancel(notify_token);
9211 return locked_ == 0 && status == 0;
9214 - (void) applicationSuspend:(__GSEvent *)event {
9215 if ([self isSafeToSuspend])
9216 [super applicationSuspend:event];
9219 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9220 if ([self isSafeToSuspend])
9221 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9224 - (void) _setSuspended:(BOOL)value {
9225 if ([self isSafeToSuspend])
9226 [super _setSuspended:value];
9229 - (UIProgressHUD *) addProgressHUD {
9230 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9231 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9233 [window_ setUserInteractionEnabled:NO];
9236 UIViewController *target = tabbar_;
9237 while ([target modalViewController] != nil) target = [target modalViewController];
9238 [[target view] addSubview:hud];
9244 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9246 [hud removeFromSuperview];
9247 [window_ setUserInteractionEnabled:YES];
9251 - (CYViewController *) pageForPackage:(NSString *)name {
9252 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9255 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9256 NSString *scheme([[url scheme] lowercaseString]);
9257 if ([[url absoluteString] length] <= [scheme length] + 3)
9259 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9260 NSArray *components([path pathComponents]);
9262 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9263 return [self pageForPackage:[components objectAtIndex:1]];
9265 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9268 NSString *base([components objectAtIndex:0]);
9270 CYViewController *controller = nil;
9272 if ([base isEqualToString:@"url"]) {
9273 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9274 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9275 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9276 } else if (!external && [components count] == 1) {
9277 if ([base isEqualToString:@"manage"]) {
9278 controller = [[[ManageController alloc] init] autorelease];
9281 if ([base isEqualToString:@"sources"]) {
9282 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9285 if ([base isEqualToString:@"home"]) {
9286 controller = [[[HomeController alloc] init] autorelease];
9289 if ([base isEqualToString:@"sections"]) {
9290 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9293 if ([base isEqualToString:@"search"]) {
9294 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9297 if ([base isEqualToString:@"changes"]) {
9298 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9301 if ([base isEqualToString:@"installed"]) {
9302 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9304 } else if ([components count] == 2) {
9305 NSString *argument = [components objectAtIndex:1];
9307 if ([base isEqualToString:@"package"]) {
9308 controller = [self pageForPackage:argument];
9311 if (!external && [base isEqualToString:@"search"]) {
9312 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9313 [(SearchController *)controller setSearchTerm:argument];
9316 if (!external && [base isEqualToString:@"sections"]) {
9317 if ([argument isEqualToString:@"all"])
9319 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9322 if (!external && [base isEqualToString:@"sources"]) {
9323 if ([argument isEqualToString:@"add"]) {
9324 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9325 [(SourcesController *)controller showAddSourcePrompt];
9327 Source *source = [database_ sourceWithKey:argument];
9328 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9332 if (!external && [base isEqualToString:@"launch"]) {
9333 [self launchApplicationWithIdentifier:argument suspended:NO];
9336 } else if (!external && [components count] == 3) {
9337 NSString *arg1 = [components objectAtIndex:1];
9338 NSString *arg2 = [components objectAtIndex:2];
9340 if ([base isEqualToString:@"package"]) {
9341 if ([arg2 isEqualToString:@"settings"]) {
9342 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9343 } else if ([arg2 isEqualToString:@"files"]) {
9344 if (Package *package = [database_ packageWithName:arg1]) {
9345 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9346 [(FileTable *)controller setPackage:package];
9352 [controller setDelegate:self];
9356 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9357 CYViewController *page([self pageForURL:url forExternal:external]);
9360 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9361 [nav setViewControllers:[NSArray arrayWithObject:page]];
9362 [tabbar_ setUnselectedViewController:nav];
9368 - (void) applicationOpenURL:(NSURL *)url {
9369 [super applicationOpenURL:url];
9371 if (!loaded_) starturl_ = [url retain];
9372 else [self openCydiaURL:url forExternal:YES];
9375 - (void) applicationWillResignActive:(UIApplication *)application {
9376 // Stop refreshing if you get a phone call or lock the device.
9377 if ([tabbar_ updating])
9378 [tabbar_ cancelUpdate];
9380 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9381 [super applicationWillResignActive:application];
9384 - (void) applicationWillTerminate:(UIApplication *)application {
9386 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9387 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9388 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9393 - (void) addStashController {
9395 stash_ = [[StashController alloc] init];
9396 [window_ addSubview:[stash_ view]];
9399 - (void) removeStashController {
9400 [[stash_ view] removeFromSuperview];
9406 [self setIdleTimerDisabled:YES];
9408 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9409 [self setStatusBarShowsProgress:YES];
9410 UpdateExternalStatus(1);
9412 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9414 UpdateExternalStatus(0);
9415 [self setStatusBarShowsProgress:NO];
9417 [self removeStashController];
9419 if (ExecFork() == 0) {
9420 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9421 perror("launchctl stop");
9425 - (void) setupViewControllers {
9426 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9428 NSMutableArray *items([NSMutableArray arrayWithObjects:
9429 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9430 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9431 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9432 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9436 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9437 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9439 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9442 NSMutableArray *controllers([NSMutableArray array]);
9443 for (UITabBarItem *item in items) {
9444 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9445 [controller setTabBarItem:item];
9446 [controllers addObject:controller];
9448 [tabbar_ setViewControllers:controllers];
9450 [tabbar_ setUpdateDelegate:self];
9453 - (CYEmulatedLoadingController *) showEmulatedLoadingControllerInView:(UIView *)view {
9454 static CYEmulatedLoadingController *fake = nil;
9458 fake = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9459 [view addSubview:[fake view]];
9461 [[fake view] removeFromSuperview];
9469 - (void) applicationDidFinishLaunching:(id)unused {
9473 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9474 [self setApplicationSupportsShakeToEdit:NO];
9476 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9477 initWithMemoryCapacity:524288
9478 diskCapacity:10485760
9479 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9482 [CYBrowserController _initialize];
9484 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9486 Font12_ = [[UIFont systemFontOfSize:12] retain];
9487 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9488 Font14_ = [[UIFont systemFontOfSize:14] retain];
9489 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9490 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9492 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9493 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9495 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9496 [window_ orderFront:self];
9497 [window_ makeKey:self];
9498 [window_ setHidden:NO];
9501 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9502 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9503 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9504 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9505 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9506 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9507 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9508 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9509 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9512 [self addStashController];
9513 // XXX: this would be much cleaner as a yieldToSelector:
9514 // that way the removeStashController could happen right here inline
9515 // we also could no longer require the useless stash_ field anymore
9516 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9520 database_ = [Database sharedInstance];
9522 [window_ setUserInteractionEnabled:NO];
9523 [self setupViewControllers];
9524 [self showEmulatedLoadingControllerInView:window_];
9526 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9533 [window_ setUserInteractionEnabled:YES];
9535 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9536 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9538 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9539 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9543 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9544 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9545 [window_ setUserInteractionEnabled:NO];
9551 [window_ addSubview:[tabbar_ view]];
9552 [self showEmulatedLoadingControllerInView:nil];
9553 [window_ setUserInteractionEnabled:YES];
9555 int selectedIndex = 0;
9556 NSMutableArray *items = nil;
9558 bool recently = false;
9559 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9560 if (closed != nil) {
9561 NSTimeInterval interval([closed timeIntervalSinceNow]);
9562 // XXX: Is 15 minutes the optimal time here?
9563 if (interval <= 0 && interval > -(15*60))
9567 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9568 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9571 for (NSArray *entry in items)
9572 if ([entry count] <= 0)
9575 if (!recently || !items || !enough) {
9577 items = [NSMutableArray array];
9578 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9579 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9580 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9582 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9584 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9585 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9587 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9590 [tabbar_ setSelectedIndex:selectedIndex];
9591 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9592 NSArray *stack = [items objectAtIndex:tab];
9593 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9594 NSMutableArray *current = [NSMutableArray array];
9596 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9597 NSString *addr = [stack objectAtIndex:nav];
9598 NSURL *url = [NSURL URLWithString:addr];
9599 CYViewController *page = [self pageForURL:url forExternal:NO];
9601 [current addObject:page];
9604 [navigation setViewControllers:current];
9607 // (Try to) show the startup URL.
9608 if (starturl_ != nil) {
9609 [self openCydiaURL:starturl_ forExternal:NO];
9610 [starturl_ release];
9615 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9616 if (item != nil && IsWildcat_) {
9617 [sheet showFromBarButtonItem:item animated:YES];
9619 [sheet showInView:window_];
9626 id Alloc_(id self, SEL selector) {
9627 id object = alloc_(self, selector);
9628 lprintf("[%s]A-%p\n", self->isa->name, object);
9633 id Dealloc_(id self, SEL selector) {
9634 id object = dealloc_(self, selector);
9635 lprintf("[%s]D-%p\n", self->isa->name, object);
9639 Class $WebDefaultUIKitDelegate;
9641 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9642 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9643 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9644 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9647 static NSNumber *shouldPlayKeyboardSounds;
9651 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9653 case 1104: // Keyboard Button Clicked
9654 case 1105: // Keyboard Delete Repeated
9655 if (shouldPlayKeyboardSounds == nil) {
9656 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9657 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9660 if (![shouldPlayKeyboardSounds boolValue])
9664 _UIHardware$_playSystemSound$(self, _cmd, sound);
9668 Class $UIApplication;
9670 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9671 static BOOL initialized = NO;
9672 static BOOL started = NO;
9674 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9675 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9677 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9678 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9679 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9680 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9682 if (initialized && !enabled) {
9684 [bundle performSelector:@selector(_accessibilityStopServer)];
9685 } else if (enabled) {
9689 [bundle performSelector:@selector(_accessibilityStartServer)];
9695 int main(int argc, char *argv[]) { _pooled
9698 if (Class $UIDevice = objc_getClass("UIDevice")) {
9699 UIDevice *device([$UIDevice currentDevice]);
9700 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9704 UIScreen *screen([UIScreen mainScreen]);
9705 if ([screen respondsToSelector:@selector(scale)])
9706 ScreenScale_ = [screen scale];
9710 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9711 if (ScreenScale_ > 1)
9712 [parts addObject:@"@2x"];
9713 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9714 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9716 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9718 /* Library Hacks {{{ */
9719 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9721 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9722 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9723 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9724 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9725 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9728 $UIHardware = objc_getClass("UIHardware");
9729 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9730 if (UIHardware$_playSystemSound$ != NULL) {
9731 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9732 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9735 $UIApplication = objc_getClass("UIApplication");
9736 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9737 if (UIApplication$_updateApplicationAccessibility != NULL) {
9738 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9739 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9742 /* Set Locale {{{ */
9743 Locale_ = CFLocaleCopyCurrent();
9744 Languages_ = [NSLocale preferredLanguages];
9745 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9746 //NSLog(@"%@", [Languages_ description]);
9749 if (Languages_ == nil || [Languages_ count] == 0)
9750 // XXX: consider just setting to C and then falling through?
9753 lang = [[Languages_ objectAtIndex:0] UTF8String];
9754 setenv("LANG", lang, true);
9757 //std::setlocale(LC_ALL, lang);
9758 NSLog(@"Setting Language: %s", lang);
9761 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9763 /* Parse Arguments {{{ */
9764 bool substrate(false);
9770 for (int argi(1); argi != argc; ++argi)
9771 if (strcmp(argv[argi], "--") == 0) {
9773 argv[argi] = argv[0];
9779 for (int argi(1); argi != arge; ++argi)
9780 if (strcmp(args[argi], "--substrate") == 0)
9783 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9787 App_ = [[NSBundle mainBundle] bundlePath];
9788 Home_ = NSHomeDirectory();
9794 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9795 alloc_ = alloc->method_imp;
9796 alloc->method_imp = (IMP) &Alloc_;*/
9798 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9799 dealloc_ = dealloc->method_imp;
9800 dealloc->method_imp = (IMP) &Dealloc_;*/
9802 /* System Information {{{ */
9806 size = sizeof(maxproc);
9807 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9808 perror("sysctlbyname(\"kern.maxproc\", ?)");
9809 else if (maxproc < 64) {
9811 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9812 perror("sysctlbyname(\"kern.maxproc\", #)");
9815 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9816 char *osversion = new char[size];
9817 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9818 perror("sysctlbyname(\"kern.osversion\", ?)");
9820 System_ = [NSString stringWithUTF8String:osversion];
9822 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9823 char *machine = new char[size];
9824 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9825 perror("sysctlbyname(\"hw.machine\", ?)");
9829 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9830 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9831 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9832 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9836 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9837 NSData *data((NSData *) ecid);
9838 size_t length([data length]);
9839 uint8_t bytes[length];
9840 [data getBytes:bytes];
9841 char string[length * 2 + 1];
9842 for (size_t i(0); i != length; ++i)
9843 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9844 ChipID_ = [NSString stringWithUTF8String:string];
9848 IOObjectRelease(service);
9852 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9854 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9855 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9856 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9858 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9859 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9860 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9862 if (mcc != NULL && mnc != NULL)
9863 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9870 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9871 Build_ = [system objectForKey:@"ProductBuildVersion"];
9872 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9873 Product_ = [info objectForKey:@"SafariProductVersion"];
9874 Safari_ = [info objectForKey:@"CFBundleVersion"];
9877 /* Load Database {{{ */
9879 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9881 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9883 if (Metadata_ == NULL)
9884 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9886 Settings_ = [Metadata_ objectForKey:@"Settings"];
9888 Packages_ = [Metadata_ objectForKey:@"Packages"];
9889 Sections_ = [Metadata_ objectForKey:@"Sections"];
9890 Sources_ = [Metadata_ objectForKey:@"Sources"];
9892 Token_ = [Metadata_ objectForKey:@"Token"];
9895 if (Settings_ != nil)
9896 Role_ = [Settings_ objectForKey:@"Role"];
9898 if (Sections_ == nil) {
9899 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9900 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9903 if (Sources_ == nil) {
9904 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9905 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9910 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9913 if (Packages_ != nil) {
9915 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9919 [Metadata_ removeObjectForKey:@"Packages"];
9925 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9927 #define MobileSubstrate_(name) \
9928 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) \
9929 dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL);
9931 MobileSubstrate_(Activator)
9932 MobileSubstrate_(libstatusbar)
9933 MobileSubstrate_(SimulatedKeyEvents)
9934 MobileSubstrate_(WinterBoard)
9936 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9937 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9939 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9941 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9942 unlink("/tmp/.cydia.fw");
9944 } else if (access("/User", F_OK) != 0 || version < 2) {
9947 system("/usr/libexec/cydia/firmware.sh");
9951 _assert([[NSFileManager defaultManager]
9952 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9953 withIntermediateDirectories:YES
9958 if (access("/tmp/cydia.chk", F_OK) == 0) {
9959 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9960 _assert(errno == ENOENT);
9961 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9962 _assert(errno == ENOENT);
9965 /* APT Initialization {{{ */
9966 _assert(pkgInitConfig(*_config));
9967 _assert(pkgInitSystem(*_config, _system));
9970 _config->Set("APT::Acquire::Translation", lang);
9972 // XXX: this timeout might be important :(
9973 //_config->Set("Acquire::http::Timeout", 15);
9975 _config->Set("Acquire::http::MaxParallel", 3);
9977 /* Color Choices {{{ */
9978 space_ = CGColorSpaceCreateDeviceRGB();
9980 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9981 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9982 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9983 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9984 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9985 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9986 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9987 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9988 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9990 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9991 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9993 /* UIKit Configuration {{{ */
9994 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9995 if ($GSFontSetUseLegacyFontMetrics != NULL)
9996 $GSFontSetUseLegacyFontMetrics(YES);
9998 // XXX: I have a feeling this was important
9999 //UIKeyboardDisableAutomaticAppearance();
10002 Colon_ = UCLocalize("COLON_DELIMITED");
10003 Elision_ = UCLocalize("ELISION");
10004 Error_ = UCLocalize("ERROR");
10005 Warning_ = UCLocalize("WARNING");
10008 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10010 CGColorSpaceRelease(space_);
10011 CFRelease(Locale_);