1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
122 #include <Cytore.hpp>
124 #include "UICaboodle/BrowserView.h"
125 #include "SDURLCache/SDURLCache.h"
127 #include "substrate.h"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
202 #define CYPoolStart() \
203 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
205 #define CYPoolEnd() \
209 // Hash Functions/Structures {{{
210 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
218 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
220 static _finline NSString *CydiaURL(NSString *path) {
222 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
223 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
224 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
225 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
226 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
227 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
230 static _finline void UpdateExternalStatus(uint64_t newStatus) {
232 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
233 notify_set_state(notify_token, newStatus);
234 notify_cancel(notify_token);
236 notify_post("com.saurik.Cydia.status");
239 /* [NSObject yieldToSelector:(withObject:)] {{{*/
240 @interface NSObject (Cydia)
241 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
242 - (id) yieldToSelector:(SEL)selector;
245 @implementation NSObject (Cydia)
250 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
251 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
252 id object([[context objectAtIndex:1] nonretainedObjectValue]);
253 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
255 /* XXX: deal with exceptions */
256 id value([self performSelector:selector withObject:object]);
258 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
259 [context removeAllObjects];
260 if ([signature methodReturnLength] != 0 && value != nil)
261 [context addObject:value];
266 performSelectorOnMainThread:@selector(doNothing)
272 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
273 volatile bool stopped(false);
275 NSMutableArray *context([NSMutableArray arrayWithObjects:
276 [NSValue valueWithPointer:selector],
277 [NSValue valueWithNonretainedObject:object],
278 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
281 NSThread *thread([[[NSThread alloc]
283 selector:@selector(_yieldToContext:)
289 NSRunLoop *loop([NSRunLoop currentRunLoop]);
290 NSDate *future([NSDate distantFuture]);
292 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
294 return [context count] == 0 ? nil : [context objectAtIndex:0];
297 - (id) yieldToSelector:(SEL)selector {
298 return [self yieldToSelector:selector withObject:nil];
304 /* Cydia Alert View {{{ */
305 @interface CYAlertView : UIAlertView {
309 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
313 @implementation CYAlertView
315 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
316 if ((self = [super init]) != nil) {
317 [self setTitle:title];
318 [self setDelegate:self];
319 for (NSString *button in buttons) [self addButtonWithTitle:button];
320 [self setCancelButtonIndex:index];
324 - (void) _updateFrameForDisplay {
325 [super _updateFrameForDisplay];
326 if ([self cancelButtonIndex] == -1) {
327 NSArray *buttons = [self buttons];
328 if ([buttons count]) {
329 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
330 for (UIThreePartButton *button in buttons)
331 [button setBackground:background forState:0];
336 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
337 button_ = buttonIndex + 1;
341 [self dismissWithClickedButtonIndex:-1 animated:YES];
344 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
345 [self setRunsModal:YES];
354 /* NSForcedOrderingSearch doesn't work on the iPhone */
355 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
356 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
357 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
359 #define lprintf(args...) fprintf(stderr, args)
362 #define TraceLogging (1 && !ForRelease)
363 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
364 #define ProfileTimes (0 && !ForRelease)
365 #define ForSaurik (0 && !ForRelease)
366 #define LogBrowser (0 && !ForRelease)
367 #define TrackResize (0 && !ForRelease)
368 #define ManualRefresh (1 && !ForRelease)
369 #define ShowInternals (0 && !ForRelease)
370 #define AlwaysReload (0 && !ForRelease)
371 #define TryIndexedCollation (0 && !ForRelease)
375 #define _trace(args...)
380 #define _profile(name) {
383 #define PrintTimes() do {} while (false)
387 typedef uint32_t (*SKRadixFunction)(id, void *);
389 @interface NSMutableArray (Radix)
390 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
398 @implementation NSMutableArray (Radix)
400 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
401 size_t count([self count]);
402 struct RadixItem_ *swap(new RadixItem_[count * 2]);
404 for (size_t i(0); i != count; ++i) {
405 RadixItem_ &item(swap[i]);
408 id object([self objectAtIndex:i]);
409 item.key = function(object, argument);
412 struct RadixItem_ *lhs(swap), *rhs(swap + count);
414 static const size_t width = 32;
415 static const size_t bits = 11;
416 static const size_t slots = 1 << bits;
417 static const size_t passes = (width + (bits - 1)) / bits;
419 size_t *hist(new size_t[slots]);
421 for (size_t pass(0); pass != passes; ++pass) {
422 memset(hist, 0, sizeof(size_t) * slots);
424 for (size_t i(0); i != count; ++i) {
425 uint32_t key(lhs[i].key);
427 key &= _not(uint32_t) >> width - bits;
432 for (size_t i(0); i != slots; ++i) {
433 size_t local(offset);
438 for (size_t i(0); i != count; ++i) {
439 uint32_t key(lhs[i].key);
441 key &= _not(uint32_t) >> width - bits;
442 rhs[hist[key]++] = lhs[i];
445 RadixItem_ *tmp(lhs);
452 const void **values(new const void *[count]);
453 for (size_t i(0); i != count; ++i)
454 values[i] = [self objectAtIndex:lhs[i].index];
455 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
463 /* Insertion Sort {{{ */
465 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
466 const char *ptr = (const char *)list;
468 CFIndex half = count / 2;
469 const char *probe = ptr + elementSize * half;
470 CFComparisonResult cr = comparator(element, probe, context);
471 if (0 == cr) return (probe - (const char *)list) / elementSize;
472 ptr = (cr < 0) ? ptr : probe + elementSize;
473 count = (cr < 0) ? half : (half + (count & 1) - 1);
475 return (ptr - (const char *)list) / elementSize;
478 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
479 const char *ptr = (const char *)list;
481 CFIndex half = count / 2;
482 const char *probe = ptr + elementSize * half;
483 CFComparisonResult cr = comparator(element, probe, context);
484 if (0 == cr) return (probe - (const char *)list) / elementSize;
485 ptr = (cr < 0) ? ptr : probe + elementSize;
486 count = (cr < 0) ? half : (half + (count & 1) - 1);
488 return (ptr - (const char *)list) / elementSize;
491 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
492 if (range.length == 0)
494 const void **values(new const void *[range.length]);
495 CFArrayGetValues(array, range, values);
497 #if HistogramInsertionSort > 0
498 uint32_t total(0), *offsets(new uint32_t[range.length]);
501 for (CFIndex index(1); index != range.length; ++index) {
502 const void *value(values[index]);
503 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
504 CFIndex correct(index);
505 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
506 #if HistogramInsertionSort > 1
507 NSLog(@"%@ < %@", value, values[correct - 1]);
512 if (correct != index) {
513 size_t offset(index - correct);
514 #if HistogramInsertionSort
518 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
520 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
521 values[correct] = value;
525 CFArrayReplaceValues(array, range, values, range.length);
528 #if HistogramInsertionSort > 0
529 for (CFIndex index(0); index != range.length; ++index)
530 if (offsets[index] != 0)
531 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
532 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
539 /* Apple Bug Fixes {{{ */
540 @implementation UIWebDocumentView (Cydia)
542 - (void) _setScrollerOffset:(CGPoint)offset {
543 UIScroller *scroller([self _scroller]);
545 CGSize size([scroller contentSize]);
546 CGSize bounds([scroller bounds].size);
549 max.x = size.width - bounds.width;
550 max.y = size.height - bounds.height;
558 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
559 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
561 [scroller setOffset:offset];
567 @implementation WebScriptObject (NSFastEnumeration)
569 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
570 size_t length([self count] - state->state);
573 else if (length > count)
575 for (size_t i(0); i != length; ++i)
576 objects[i] = [self objectAtIndex:state->state++];
577 state->itemsPtr = objects;
578 state->mutationsPtr = (unsigned long *) self;
584 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
585 size_t length([self length] - state->state);
588 else if (length > count)
590 for (size_t i(0); i != length; ++i)
591 objects[i] = [self item:state->state++];
592 state->itemsPtr = objects;
593 state->mutationsPtr = (unsigned long *) self;
597 /* Cydia NSString Additions {{{ */
598 @interface NSString (Cydia)
599 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
600 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
601 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
602 - (NSComparisonResult) compareByPath:(NSString *)other;
603 - (NSString *) stringByCachingURLWithCurrentCDN;
604 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
607 @implementation NSString (Cydia)
609 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
610 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
613 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
614 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
615 memcpy(data, bytes, length);
616 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
619 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
620 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
623 - (NSComparisonResult) compareByPath:(NSString *)other {
624 NSString *prefix = [self commonPrefixWithString:other options:0];
625 size_t length = [prefix length];
627 NSRange lrange = NSMakeRange(length, [self length] - length);
628 NSRange rrange = NSMakeRange(length, [other length] - length);
630 lrange = [self rangeOfString:@"/" options:0 range:lrange];
631 rrange = [other rangeOfString:@"/" options:0 range:rrange];
633 NSComparisonResult value;
635 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
636 value = NSOrderedSame;
637 else if (lrange.location == NSNotFound)
638 value = NSOrderedAscending;
639 else if (rrange.location == NSNotFound)
640 value = NSOrderedDescending;
642 value = NSOrderedSame;
644 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
645 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
646 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
647 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
649 NSComparisonResult result = [lpath compare:rpath];
650 return result == NSOrderedSame ? value : result;
653 - (NSString *) stringByCachingURLWithCurrentCDN {
655 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
656 withString:@"://cache.cydia.saurik.com/"
660 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
661 return [(id)CFURLCreateStringByAddingPercentEscapes(
666 kCFStringEncodingUTF8
673 /* C++ NSString Wrapper Cache {{{ */
674 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
675 return size == 0 ? NULL :
676 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
677 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
680 static _finline CFStringRef CYStringCreate(const char *data) {
681 return CYStringCreate(data, strlen(data));
690 _finline void clear_() {
691 if (cache_ != NULL) {
698 _finline bool empty() const {
702 _finline size_t size() const {
706 _finline char *data() const {
710 _finline void clear() {
715 _finline CYString() :
722 _finline ~CYString() {
726 void operator =(const CYString &rhs) {
730 if (rhs.cache_ == nil)
733 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
736 void copy(apr_pool_t *pool) {
737 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
738 memcpy(temp, data_, size_);
743 void set(apr_pool_t *pool, const char *data, size_t size) {
749 data_ = const_cast<char *>(data);
757 _finline void set(apr_pool_t *pool, const char *data) {
758 set(pool, data, data == NULL ? 0 : strlen(data));
761 _finline void set(apr_pool_t *pool, const std::string &rhs) {
762 set(pool, rhs.data(), rhs.size());
765 bool operator ==(const CYString &rhs) const {
766 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
769 _finline operator CFStringRef() {
771 cache_ = CYStringCreate(data_, size_);
775 _finline operator id() {
776 return (NSString *) static_cast<CFStringRef>(*this);
779 _finline operator const char *() {
780 return reinterpret_cast<const char *>(data_);
784 /* C++ NSString Algorithm Adapters {{{ */
786 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
789 struct NSStringMapHash :
790 std::unary_function<NSString *, size_t>
792 _finline size_t operator ()(NSString *value) const {
793 return CFStringHashNSString((CFStringRef) value);
797 struct NSStringMapLess :
798 std::binary_function<NSString *, NSString *, bool>
800 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
801 return [lhs compare:rhs] == NSOrderedAscending;
805 struct NSStringMapEqual :
806 std::binary_function<NSString *, NSString *, bool>
808 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
809 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
810 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
811 //[lhs isEqualToString:rhs];
816 /* Perl-Compatible RegEx {{{ */
826 Pcre(const char *regex) :
831 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
834 lprintf("%d:%s\n", offset, error);
838 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
839 matches_ = new int[(capture_ + 1) * 3];
847 NSString *operator [](size_t match) {
848 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
851 bool operator ()(NSString *data) {
852 // XXX: length is for characters, not for bytes
853 return operator ()([data UTF8String], [data length]);
856 bool operator ()(const char *data, size_t size) {
858 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
862 /* Mime Addresses {{{ */
863 @interface Address : NSObject {
869 - (NSString *) address;
871 - (void) setAddress:(NSString *)address;
873 + (Address *) addressWithString:(NSString *)string;
874 - (Address *) initWithString:(NSString *)string;
878 @implementation Address
887 - (NSString *) name {
891 - (NSString *) address {
895 - (void) setAddress:(NSString *)address {
897 [address_ autorelease];
901 address_ = [address retain];
904 + (Address *) addressWithString:(NSString *)string {
905 return [[[Address alloc] initWithString:string] autorelease];
908 + (NSArray *) _attributeKeys {
909 return [NSArray arrayWithObjects:
915 - (NSArray *) attributeKeys {
916 return [[self class] _attributeKeys];
919 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
920 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
923 - (Address *) initWithString:(NSString *)string {
924 if ((self = [super init]) != nil) {
925 const char *data = [string UTF8String];
926 size_t size = [string length];
928 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
930 if (address_r(data, size)) {
931 name_ = [address_r[1] retain];
932 address_ = [address_r[2] retain];
934 name_ = [string retain];
942 /* CoreGraphics Primitives {{{ */
947 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
948 CGFloat color[] = {red, green, blue, alpha};
949 return CGColorCreate(space, color);
958 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
959 color_(Create_(space, red, green, blue, alpha))
961 Set(space, red, green, blue, alpha);
966 CGColorRelease(color_);
973 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
975 color_ = Create_(space, red, green, blue, alpha);
978 operator CGColorRef() {
984 /* Random Global Variables {{{ */
985 static const int PulseInterval_ = 50000;
987 static const NSString *UI_;
990 static bool RestartSubstrate_;
991 static NSArray *Finishes_;
993 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
994 #define NotifyConfig_ "/etc/notify.conf"
996 static bool Queuing_;
998 static CYColor Blue_;
999 static CYColor Blueish_;
1000 static CYColor Black_;
1001 static CYColor Off_;
1002 static CYColor White_;
1003 static CYColor Gray_;
1004 static CYColor Green_;
1005 static CYColor Purple_;
1006 static CYColor Purplish_;
1008 static UIColor *InstallingColor_;
1009 static UIColor *RemovingColor_;
1011 static NSString *App_;
1012 static NSString *Home_;
1014 static BOOL Advanced_;
1015 static BOOL Ignored_;
1017 static UIFont *Font12_;
1018 static UIFont *Font12Bold_;
1019 static UIFont *Font14_;
1020 static UIFont *Font18Bold_;
1021 static UIFont *Font22Bold_;
1023 static const char *Machine_ = NULL;
1024 static NSString *System_ = nil;
1025 static NSString *SerialNumber_ = nil;
1026 static NSString *ChipID_ = nil;
1027 static NSString *Token_ = nil;
1028 static NSString *UniqueID_ = nil;
1029 static NSString *PLMN_ = nil;
1030 static NSString *Build_ = nil;
1031 static NSString *Product_ = nil;
1032 static NSString *Safari_ = nil;
1034 static CFLocaleRef Locale_;
1035 static NSArray *Languages_;
1036 static CGColorSpaceRef space_;
1038 static NSDictionary *SectionMap_;
1039 static NSMutableDictionary *Metadata_;
1040 static _transient NSMutableDictionary *Settings_;
1041 static _transient NSString *Role_;
1042 static _transient NSMutableDictionary *Packages_;
1043 static _transient NSMutableDictionary *Sections_;
1044 static _transient NSMutableDictionary *Sources_;
1045 static bool Changed_;
1049 static CGFloat ScreenScale_;
1052 /* Display Helpers {{{ */
1053 inline float Interpolate(float begin, float end, float fraction) {
1054 return (end - begin) * fraction + begin;
1057 static _finline const char *StripVersion_(const char *version) {
1058 const char *colon(strchr(version, ':'));
1059 return colon == NULL ? version : colon + 1;
1062 NSString *LocalizeSection(NSString *section) {
1063 static Pcre title_r("^(.*?) \\((.*)\\)$");
1064 if (title_r(section)) {
1065 NSString *parent(title_r[1]);
1066 NSString *child(title_r[2]);
1068 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1069 LocalizeSection(parent),
1070 LocalizeSection(child)
1074 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1077 NSString *Simplify(NSString *title) {
1078 const char *data = [title UTF8String];
1079 size_t size = [title length];
1081 static Pcre square_r("^\\[(.*)\\]$");
1082 if (square_r(data, size))
1083 return Simplify(square_r[1]);
1085 static Pcre paren_r("^\\((.*)\\)$");
1086 if (paren_r(data, size))
1087 return Simplify(paren_r[1]);
1089 static Pcre title_r("^(.*?) \\((.*)\\)$");
1090 if (title_r(data, size))
1091 return Simplify(title_r[1]);
1097 NSString *GetLastUpdate() {
1098 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1101 return UCLocalize("NEVER_OR_UNKNOWN");
1103 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1104 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1106 CFRelease(formatter);
1108 return [(NSString *) formatted autorelease];
1111 bool isSectionVisible(NSString *section) {
1112 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1113 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1114 return hidden == nil || ![hidden boolValue];
1119 /* Delegate Prototypes {{{ */
1123 @interface NSObject (ProgressDelegate)
1126 @protocol ProgressDelegate
1127 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1128 - (void) setProgressTitle:(NSString *)title;
1129 - (void) setProgressPercent:(NSNumber *)percent;
1130 - (void) startProgress;
1131 - (void) addProgressOutput:(NSString *)output;
1132 - (bool) isCancelling:(size_t)received;
1135 @protocol ConfigurationDelegate
1136 - (void) repairWithSelector:(SEL)selector;
1137 - (void) setConfigurationData:(NSString *)data;
1140 @class CYPackageController;
1142 @protocol CydiaDelegate
1143 - (void) retainNetworkActivityIndicator;
1144 - (void) releaseNetworkActivityIndicator;
1145 - (void) clearPackage:(Package *)package;
1146 - (void) installPackage:(Package *)package;
1147 - (void) installPackages:(NSArray *)packages;
1148 - (void) removePackage:(Package *)package;
1149 - (void) beginUpdate;
1151 - (void) distUpgrade;
1153 - (void) updateData;
1155 - (void) addTrivialSource:(NSString *)href;
1156 - (void) showSettings;
1157 - (UIProgressHUD *) addProgressHUD;
1158 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1159 - (CYViewController *) pageForPackage:(NSString *)name;
1160 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1161 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1164 static NSObject<CydiaDelegate> *CydiaApp;
1167 /* Status Delegation {{{ */
1169 public pkgAcquireStatus
1172 _transient NSObject<ProgressDelegate> *delegate_;
1180 void setDelegate(id delegate) {
1181 delegate_ = delegate;
1184 NSObject<ProgressDelegate> *getDelegate() const {
1188 virtual bool MediaChange(std::string media, std::string drive) {
1192 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1195 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1196 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1198 performSelectorOnMainThread:@selector(setProgressTitle:)
1199 withObject:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]
1204 virtual void Done(pkgAcquire::ItemDesc &item) {
1207 virtual void Fail(pkgAcquire::ItemDesc &item) {
1209 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1210 item.Owner->Status == pkgAcquire::Item::StatDone
1214 std::string &error(item.Owner->ErrorText);
1218 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1219 NSArray *fields([description componentsSeparatedByString:@" "]);
1220 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1222 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1223 withObject:[NSArray arrayWithObjects:
1224 [NSString stringWithUTF8String:error.c_str()],
1231 virtual bool Pulse(pkgAcquire *Owner) {
1232 bool value = pkgAcquireStatus::Pulse(Owner);
1235 double(CurrentBytes + CurrentItems) /
1236 double(TotalBytes + TotalItems)
1239 [delegate_ setProgressPercent:[NSNumber numberWithFloat:percent]];
1240 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1243 virtual void Start() {
1244 [delegate_ startProgress];
1247 virtual void Stop() {
1252 /* Database Interface {{{ */
1253 typedef std::map< unsigned long, _H<Source> > SourceMap;
1255 @interface Database : NSObject {
1261 pkgCacheFile cache_;
1262 pkgDepCache::Policy *policy_;
1263 pkgRecords *records_;
1264 pkgProblemResolver *resolver_;
1265 pkgAcquire *fetcher_;
1267 SPtr<pkgPackageManager> manager_;
1268 pkgSourceList *list_;
1270 SourceMap sourceMap_;
1271 NSMutableArray *sourceList_;
1273 CFMutableArrayRef packages_;
1275 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1282 std::map<const char *, _H<NSString> > sections_;
1285 + (Database *) sharedInstance;
1288 - (void) _readCydia:(NSNumber *)fd;
1289 - (void) _readStatus:(NSNumber *)fd;
1290 - (void) _readOutput:(NSNumber *)fd;
1294 - (Package *) packageWithName:(NSString *)name;
1296 - (pkgCacheFile &) cache;
1297 - (pkgDepCache::Policy *) policy;
1298 - (pkgRecords *) records;
1299 - (pkgProblemResolver *) resolver;
1300 - (pkgAcquire &) fetcher;
1301 - (pkgSourceList &) list;
1302 - (NSArray *) packages;
1303 - (NSArray *) sources;
1304 - (Source *) sourceWithKey:(NSString *)key;
1305 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1313 - (void) updateWithStatus:(Status &)status;
1315 - (void) setDelegate:(id)delegate;
1316 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1318 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1322 /* Delegate Helpers {{{ */
1323 @implementation NSObject (ProgressDelegate)
1325 - (void) _setProgressErrorPackage:(NSArray *)args {
1326 [self performSelector:@selector(setProgressError:forPackage:)
1327 withObject:[args objectAtIndex:0]
1328 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1332 - (void) _setProgressErrorTitle:(NSArray *)args {
1333 [self performSelector:@selector(setProgressError:withTitle:)
1334 withObject:[args objectAtIndex:0]
1335 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1339 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1340 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1341 withObject:[NSArray arrayWithObjects:error, title, nil]
1346 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1347 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1349 [self performSelector:@selector(setProgressError:withTitle:)
1351 withObject:(package == nil ? id : [package name])
1358 // Cytore Definitions {{{
1359 struct PackageValue :
1362 Cytore::Offset<PackageValue> next_;
1364 uint32_t index_ : 23;
1365 uint32_t subscribed_ : 1;
1382 Cytore::Offset<PackageValue> packages_[1 << 16];
1385 static Cytore::File<MetaValue> MetaFile_;
1387 // Cytore Helper Functions {{{
1388 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1389 SplitHash nhash = { hashlittle(name, length) };
1391 PackageValue *metadata;
1393 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1394 offset: if (offset->IsNull()) {
1395 *offset = MetaFile_.New<PackageValue>(length + 1);
1396 metadata = &MetaFile_.Get(*offset);
1398 if (metadata == NULL) {
1402 metadata = new PackageValue();
1403 memset(metadata, 0, sizeof(*metadata));
1406 memcpy(metadata->name_, name, length + 1);
1407 metadata->nhash_ = nhash.u16[1];
1409 metadata = &MetaFile_.Get(*offset);
1411 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1412 offset = &metadata->next_;
1420 static void PackageImport(const void *key, const void *value, void *context) {
1421 bool &fail(*reinterpret_cast<bool *>(context));
1424 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1425 NSLog(@"failed to import package %@", key);
1429 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1430 NSDictionary *package((NSDictionary *) value);
1432 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1433 if ([subscribed boolValue] && !metadata->subscribed_)
1434 metadata->subscribed_ = true;
1436 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1437 time_t time([date timeIntervalSince1970]);
1438 if (metadata->first_ > time || metadata->first_ == 0)
1439 metadata->first_ = time;
1442 NSDate *date([package objectForKey:@"LastSeen"]);
1443 NSString *version([package objectForKey:@"LastVersion"]);
1445 if (date != nil && version != nil) {
1446 time_t time([date timeIntervalSince1970]);
1447 if (metadata->last_ < time || metadata->last_ == 0)
1448 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1449 size_t length(strlen(buffer));
1450 uint16_t vhash(hashlittle(buffer, length));
1452 size_t capped(std::min<size_t>(8, length));
1453 char *latest(buffer + length - capped);
1455 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1456 metadata->vhash_ = vhash;
1458 metadata->last_ = time;
1464 /* Source Class {{{ */
1465 @interface Source : NSObject {
1466 CYString depiction_;
1467 CYString description_;
1473 CYString distribution_;
1478 NSString *authority_;
1480 CYString defaultIcon_;
1482 NSDictionary *record_;
1486 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1488 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1490 - (NSString *) depictionForPackage:(NSString *)package;
1491 - (NSString *) supportForPackage:(NSString *)package;
1493 - (NSDictionary *) record;
1497 - (NSString *) distribution;
1498 - (NSString *) type;
1500 - (NSString *) host;
1502 - (NSString *) name;
1503 - (NSString *) description;
1504 - (NSString *) label;
1505 - (NSString *) origin;
1506 - (NSString *) version;
1508 - (NSString *) defaultIcon;
1512 @implementation Source
1516 distribution_.clear();
1519 description_.clear();
1525 defaultIcon_.clear();
1527 if (record_ != nil) {
1537 if (authority_ != nil) {
1538 [authority_ release];
1544 // XXX: this is a very inefficient way to call these deconstructors
1549 + (NSArray *) _attributeKeys {
1550 return [NSArray arrayWithObjects:
1565 - (NSArray *) attributeKeys {
1566 return [[self class] _attributeKeys];
1569 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1570 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1573 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1576 trusted_ = index->IsTrusted();
1578 uri_.set(pool, index->GetURI());
1579 distribution_.set(pool, index->GetDist());
1580 type_.set(pool, index->GetType());
1582 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1583 if (dindex != NULL) {
1585 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1588 pkgTagFile tags(&fd);
1590 pkgTagSection section;
1597 {"default-icon", &defaultIcon_},
1598 {"depiction", &depiction_},
1599 {"description", &description_},
1601 {"origin", &origin_},
1602 {"support", &support_},
1603 {"version", &version_},
1606 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1607 const char *start, *end;
1609 if (section.Find(names[i].name_, start, end)) {
1610 CYString &value(*names[i].value_);
1611 value.set(pool, start, end - start);
1617 record_ = [Sources_ objectForKey:[self key]];
1619 record_ = [record_ retain];
1621 NSURL *url([NSURL URLWithString:uri_]);
1625 host_ = [[host_ lowercaseString] retain];
1630 authority_ = [url path];
1632 if (authority_ != nil)
1633 authority_ = [authority_ retain];
1636 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1637 if ((self = [super init]) != nil) {
1638 [self setMetaIndex:index inPool:pool];
1642 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1643 NSDictionary *lhr = [self record];
1644 NSDictionary *rhr = [source record];
1647 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1649 NSString *lhs = [self name];
1650 NSString *rhs = [source name];
1652 if ([lhs length] != 0 && [rhs length] != 0) {
1653 unichar lhc = [lhs characterAtIndex:0];
1654 unichar rhc = [rhs characterAtIndex:0];
1656 if (isalpha(lhc) && !isalpha(rhc))
1657 return NSOrderedAscending;
1658 else if (!isalpha(lhc) && isalpha(rhc))
1659 return NSOrderedDescending;
1662 return [lhs compare:rhs options:LaxCompareOptions_];
1665 - (NSString *) depictionForPackage:(NSString *)package {
1666 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1669 - (NSString *) supportForPackage:(NSString *)package {
1670 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1673 - (NSDictionary *) record {
1681 - (NSString *) uri {
1685 - (NSString *) distribution {
1686 return distribution_;
1689 - (NSString *) type {
1693 - (NSString *) key {
1694 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1697 - (NSString *) host {
1701 - (NSString *) name {
1702 return origin_.empty() ? authority_ : origin_;
1705 - (NSString *) description {
1706 return description_;
1709 - (NSString *) label {
1710 return label_.empty() ? authority_ : label_;
1713 - (NSString *) origin {
1717 - (NSString *) version {
1721 - (NSString *) defaultIcon {
1722 return defaultIcon_;
1727 /* CydiaOperation Class {{{ */
1728 @interface CydiaOperation : NSObject {
1729 NSString *operator_;
1733 - (NSString *) operator;
1734 - (NSString *) value;
1738 @implementation CydiaOperation
1741 [operator_ release];
1746 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1747 if ((self = [super init]) != nil) {
1748 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1749 value_ = [[NSString alloc] initWithUTF8String:value];
1753 + (NSArray *) _attributeKeys {
1754 return [NSArray arrayWithObjects:
1760 - (NSArray *) attributeKeys {
1761 return [[self class] _attributeKeys];
1764 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1765 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1768 - (NSString *) operator {
1772 - (NSString *) value {
1778 /* CydiaClause Class {{{ */
1779 @interface CydiaClause : NSObject {
1781 CydiaOperation *version_;
1784 - (NSString *) package;
1785 - (CydiaOperation *) version;
1789 @implementation CydiaClause
1797 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1798 if ((self = [super init]) != nil) {
1799 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1801 if (const char *version = dep.TargetVer())
1802 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1804 version_ = [[NSNull null] retain];
1808 + (NSArray *) _attributeKeys {
1809 return [NSArray arrayWithObjects:
1815 - (NSArray *) attributeKeys {
1816 return [[self class] _attributeKeys];
1819 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1820 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1823 - (NSString *) package {
1827 - (CydiaOperation *) version {
1833 /* CydiaRelation Class {{{ */
1834 @interface CydiaRelation : NSObject {
1835 NSString *relationship_;
1836 NSMutableArray *clauses_;
1839 - (NSString *) relationship;
1840 - (NSArray *) clauses;
1844 @implementation CydiaRelation
1847 [relationship_ release];
1852 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1853 if ((self = [super init]) != nil) {
1854 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1855 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1857 pkgCache::DepIterator start;
1858 pkgCache::DepIterator end;
1859 dep.GlobOr(start, end); // ++dep
1862 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1864 // yes, seriously. (wtf?)
1872 + (NSArray *) _attributeKeys {
1873 return [NSArray arrayWithObjects:
1879 - (NSArray *) attributeKeys {
1880 return [[self class] _attributeKeys];
1883 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1884 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1887 - (NSString *) relationship {
1888 return relationship_;
1891 - (NSArray *) clauses {
1895 - (void) addClause:(CydiaClause *)clause {
1896 [clauses_ addObject:clause];
1901 /* Package Class {{{ */
1902 struct ParsedPackage {
1907 CYString depiction_;
1917 @interface Package : NSObject {
1920 uint32_t essential_ : 1;
1921 uint32_t obsolete_ : 1;
1922 uint32_t ignored_ : 1;
1926 _transient Database *database_;
1928 pkgCache::VerIterator version_;
1929 pkgCache::PkgIterator iterator_;
1930 pkgCache::VerFileIterator file_;
1936 CYString installed_;
1938 const char *section_;
1939 _transient NSString *section$_;
1943 PackageValue *metadata_;
1944 ParsedPackage *parsed_;
1946 NSMutableArray *tags_;
1949 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1950 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1952 - (pkgCache::PkgIterator) iterator;
1955 - (NSString *) section;
1956 - (NSString *) simpleSection;
1958 - (NSString *) longSection;
1959 - (NSString *) shortSection;
1963 - (Address *) maintainer;
1965 - (NSString *) longDescription;
1966 - (NSString *) shortDescription;
1969 - (PackageValue *) metadata;
1972 - (bool) subscribed;
1973 - (bool) setSubscribed:(bool)subscribed;
1977 - (NSString *) latest;
1978 - (NSString *) installed;
1979 - (BOOL) uninstalled;
1982 - (BOOL) upgradableAndEssential:(BOOL)essential;
1985 - (BOOL) unfiltered;
1989 - (BOOL) halfConfigured;
1990 - (BOOL) halfInstalled;
1992 - (NSString *) mode;
1995 - (NSString *) name;
1997 - (NSString *) homepage;
1998 - (NSString *) depiction;
1999 - (Address *) author;
2001 - (NSString *) support;
2003 - (NSArray *) files;
2004 - (NSArray *) warnings;
2005 - (NSArray *) applications;
2007 - (Source *) source;
2009 - (BOOL) matches:(NSString *)text;
2011 - (bool) hasSupportingRole;
2012 - (BOOL) hasTag:(NSString *)tag;
2013 - (NSString *) primaryPurpose;
2014 - (NSArray *) purposes;
2015 - (bool) isCommercial;
2017 - (void) setIndex:(size_t)index;
2019 - (CYString &) cyname;
2021 - (uint32_t) compareBySection:(NSArray *)sections;
2026 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2027 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2028 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2029 - (bool) isVisibleInSection:(NSString *)section;
2030 - (bool) isVisibleInSource:(Source *)source;
2034 uint32_t PackageChangesRadix(Package *self, void *) {
2039 uint32_t timestamp : 30;
2040 uint32_t ignored : 1;
2041 uint32_t upgradable : 1;
2045 bool upgradable([self upgradableAndEssential:YES]);
2046 value.bits.upgradable = upgradable ? 1 : 0;
2049 value.bits.timestamp = 0;
2050 value.bits.ignored = [self ignored] ? 0 : 1;
2051 value.bits.upgradable = 1;
2053 value.bits.timestamp = [self seen] >> 2;
2054 value.bits.ignored = 0;
2055 value.bits.upgradable = 0;
2058 return _not(uint32_t) - value.key;
2061 uint32_t PackagePrefixRadix(Package *self, void *context) {
2062 size_t offset(reinterpret_cast<size_t>(context));
2063 CYString &name([self cyname]);
2065 size_t size(name.size());
2068 char *text(name.data());
2071 if (!isdigit(text[0]))
2075 while (size != digits && isdigit(text[digits]))
2083 if (offset == 0 && zeros != 0) {
2084 memset(data, '0', zeros);
2085 memcpy(data + zeros, text, 4 - zeros);
2087 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2088 if (size <= offset - zeros)
2091 text += offset - zeros;
2092 size -= offset - zeros;
2095 memcpy(data, text, 4);
2097 memcpy(data, text, size);
2098 memset(data + size, 0, 4 - size);
2101 for (size_t i(0); i != 4; ++i)
2102 if (isalpha(data[i]))
2110 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2112 /* XXX: ntohl may be more honest */
2113 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2116 CYString &(*PackageName)(Package *self, SEL sel);
2118 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2119 _profile(PackageNameCompare)
2120 CYString &lhi(PackageName(lhs, @selector(cyname)));
2121 CYString &rhi(PackageName(rhs, @selector(cyname)));
2122 CFStringRef lhn(lhi), rhn(rhi);
2125 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2126 else if (rhn == NULL)
2127 return NSOrderedDescending;
2129 _profile(PackageNameCompare$NumbersLast)
2130 if (!lhi.empty() && !rhi.empty()) {
2131 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2132 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2133 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2134 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2135 return lha ? NSOrderedAscending : NSOrderedDescending;
2139 CFIndex length = CFStringGetLength(lhn);
2141 _profile(PackageNameCompare$Compare)
2142 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2147 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2148 return PackageNameCompare(*lhs, *rhs, context);
2151 struct PackageNameOrdering :
2152 std::binary_function<Package *, Package *, bool>
2154 _finline bool operator ()(Package *lhs, Package *rhs) const {
2155 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2159 @implementation Package
2161 - (NSString *) description {
2162 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2166 if (parsed_ != NULL)
2175 + (NSString *) webScriptNameForSelector:(SEL)selector {
2177 else if (selector == @selector(clear))
2179 else if (selector == @selector(getField:))
2181 else if (selector == @selector(hasTag:))
2183 else if (selector == @selector(install))
2185 else if (selector == @selector(remove))
2191 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2192 return [self webScriptNameForSelector:selector] == nil;
2195 + (NSArray *) _attributeKeys {
2196 return [NSArray arrayWithObjects:
2214 @"shortDescription",
2225 - (NSArray *) attributeKeys {
2226 return [[self class] _attributeKeys];
2229 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2230 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2233 - (NSArray *) relations {
2234 @synchronized (database_) {
2235 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2236 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2237 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2241 - (NSString *) getField:(NSString *)name {
2242 @synchronized (database_) {
2243 if ([database_ era] != era_ || file_.end())
2246 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2248 const char *start, *end;
2249 if (!parser.Find([name UTF8String], start, end))
2250 return (NSString *) [NSNull null];
2252 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2256 if (parsed_ != NULL)
2258 @synchronized (database_) {
2259 if ([database_ era] != era_ || file_.end())
2262 ParsedPackage *parsed(new ParsedPackage);
2265 _profile(Package$parse)
2266 pkgRecords::Parser *parser;
2268 _profile(Package$parse$Lookup)
2269 parser = &[database_ records]->Lookup(file_);
2274 _profile(Package$parse$Find)
2279 {"icon", &parsed->icon_},
2280 {"depiction", &parsed->depiction_},
2281 {"homepage", &parsed->homepage_},
2282 {"website", &website},
2283 {"bugs", &parsed->bugs_},
2284 {"support", &parsed->support_},
2285 {"sponsor", &parsed->sponsor_},
2286 {"author", &parsed->author_},
2289 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2290 const char *start, *end;
2292 if (parser->Find(names[i].name_, start, end)) {
2293 CYString &value(*names[i].value_);
2294 _profile(Package$parse$Value)
2295 value.set(pool_, start, end - start);
2301 _profile(Package$parse$Tagline)
2302 const char *start, *end;
2303 if (parser->ShortDesc(start, end)) {
2304 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2307 while (stop != start && stop[-1] == '\r')
2309 parsed->tagline_.set(pool_, start, stop - start);
2313 _profile(Package$parse$Retain)
2314 if (parsed->homepage_.empty())
2315 parsed->homepage_ = website;
2316 if (parsed->homepage_ == parsed->depiction_)
2317 parsed->homepage_.clear();
2322 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2323 if ((self = [super init]) != nil) {
2324 _profile(Package$initWithVersion)
2327 database_ = database;
2328 era_ = [database era];
2332 pkgCache::PkgIterator iterator(version.ParentPkg());
2333 iterator_ = iterator;
2335 _profile(Package$initWithVersion$Version)
2336 if (!version_.end())
2337 file_ = version_.FileList();
2339 pkgCache &cache([database_ cache]);
2340 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2344 _profile(Package$initWithVersion$Cache)
2345 name_.set(NULL, iterator.Display());
2347 latest_.set(NULL, StripVersion_(version_.VerStr()));
2349 pkgCache::VerIterator current(iterator.CurrentVer());
2351 installed_.set(NULL, StripVersion_(current.VerStr()));
2354 _profile(Package$initWithVersion$Tags)
2355 pkgCache::TagIterator tag(iterator.TagList());
2357 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2359 const char *name(tag.Name());
2360 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2362 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2363 if (strcmp(name + 6, "enduser") == 0)
2365 else if (strcmp(name + 6, "hacker") == 0)
2367 else if (strcmp(name + 6, "developer") == 0)
2369 else if (strcmp(name + 6, "cydia") == 0)
2375 if (strncmp(name, "cydia::", 7) == 0) {
2376 if (strcmp(name + 7, "essential") == 0)
2378 else if (strcmp(name + 7, "obsolete") == 0)
2383 } while (!tag.end());
2387 _profile(Package$initWithVersion$Metadata)
2388 const char *mixed(iterator.Name());
2389 size_t size(strlen(mixed));
2390 char lower[size + 1];
2392 for (size_t i(0); i != size; ++i)
2393 lower[i] = mixed[i] | 0x20;
2396 PackageValue *metadata(PackageFind(lower, size));
2397 metadata_ = metadata;
2399 id_.set(NULL, metadata->name_, size);
2401 const char *latest(version_.VerStr());
2402 size_t length(strlen(latest));
2404 uint16_t vhash(hashlittle(latest, length));
2406 size_t capped(std::min<size_t>(8, length));
2407 latest = latest + length - capped;
2409 if (metadata->first_ == 0)
2410 metadata->first_ = now_;
2412 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2413 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2414 metadata->vhash_ = vhash;
2415 metadata->last_ = now_;
2416 } else if (metadata->last_ == 0)
2417 metadata->last_ = metadata->first_;
2420 _profile(Package$initWithVersion$Section)
2421 section_ = iterator.Section();
2424 _profile(Package$initWithVersion$Flags)
2425 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2426 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2431 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2432 pkgCache::VerIterator version;
2434 _profile(Package$packageWithIterator$GetCandidateVer)
2435 version = [database policy]->GetCandidateVer(iterator);
2443 _profile(Package$packageWithIterator$Allocate)
2444 package = [Package allocWithZone:zone];
2447 _profile(Package$packageWithIterator$Initialize)
2449 initWithVersion:version
2456 _profile(Package$packageWithIterator$Autorelease)
2457 package = [package autorelease];
2463 - (pkgCache::PkgIterator) iterator {
2467 - (NSString *) section {
2468 if (section$_ == nil) {
2469 if (section_ == NULL)
2472 _profile(Package$section$mappedSectionForPointer)
2473 section$_ = [database_ mappedSectionForPointer:section_];
2478 - (NSString *) simpleSection {
2479 if (NSString *section = [self section])
2480 return Simplify(section);
2485 - (NSString *) longSection {
2486 return LocalizeSection([self section]);
2489 - (NSString *) shortSection {
2490 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2493 - (NSString *) uri {
2496 pkgIndexFile *index;
2497 pkgCache::PkgFileIterator file(file_.File());
2498 if (![database_ list].FindIndex(file, index))
2500 return [NSString stringWithUTF8String:iterator_->Path];
2501 //return [NSString stringWithUTF8String:file.Site()];
2502 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2506 - (Address *) maintainer {
2507 @synchronized (database_) {
2508 if ([database_ era] != era_ || file_.end())
2511 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2512 const std::string &maintainer(parser->Maintainer());
2513 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2517 @synchronized (database_) {
2518 if ([database_ era] != era_ || version_.end())
2521 return version_->InstalledSize;
2524 - (NSString *) longDescription {
2525 @synchronized (database_) {
2526 if ([database_ era] != era_ || file_.end())
2529 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2530 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2532 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2533 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2534 if ([lines count] < 2)
2537 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2538 for (size_t i(1), e([lines count]); i != e; ++i) {
2539 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2540 [trimmed addObject:trim];
2543 return [trimmed componentsJoinedByString:@"\n"];
2546 - (NSString *) shortDescription {
2547 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2551 _profile(Package$index)
2552 CFStringRef name((CFStringRef) [self name]);
2553 if (CFStringGetLength(name) == 0)
2555 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2556 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2558 return toupper(character);
2562 - (PackageValue *) metadata {
2567 PackageValue *metadata([self metadata]);
2568 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2571 - (bool) subscribed {
2572 return [self metadata]->subscribed_;
2575 - (bool) setSubscribed:(bool)subscribed {
2576 PackageValue *metadata([self metadata]);
2577 if (metadata->subscribed_ == subscribed)
2579 metadata->subscribed_ = subscribed;
2587 - (NSString *) latest {
2591 - (NSString *) installed {
2595 - (BOOL) uninstalled {
2596 return installed_.empty();
2600 return !version_.end();
2603 - (BOOL) upgradableAndEssential:(BOOL)essential {
2604 _profile(Package$upgradableAndEssential)
2605 pkgCache::VerIterator current(iterator_.CurrentVer());
2607 return essential && essential_;
2609 return !version_.end() && version_ != current;
2613 - (BOOL) essential {
2618 return [database_ cache][iterator_].InstBroken();
2621 - (BOOL) unfiltered {
2622 _profile(Package$unfiltered$obsolete)
2623 if (_unlikely(obsolete_))
2627 _profile(Package$unfiltered$hasSupportingRole)
2628 if (_unlikely(![self hasSupportingRole]))
2636 if (![self unfiltered])
2641 _profile(Package$visible$section)
2642 section = [self section];
2645 _profile(Package$visible$isSectionVisible)
2646 if (!isSectionVisible(section))
2654 unsigned char current(iterator_->CurrentState);
2655 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2658 - (BOOL) halfConfigured {
2659 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2662 - (BOOL) halfInstalled {
2663 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2667 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2668 return state.Mode != pkgDepCache::ModeKeep;
2671 - (NSString *) mode {
2672 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2674 switch (state.Mode) {
2675 case pkgDepCache::ModeDelete:
2676 if ((state.iFlags & pkgDepCache::Purge) != 0)
2680 case pkgDepCache::ModeKeep:
2681 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2682 return @"REINSTALL";
2683 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2687 case pkgDepCache::ModeInstall:
2688 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2689 return @"REINSTALL";
2690 else*/ switch (state.Status) {
2692 return @"DOWNGRADE";
2698 return @"NEW_INSTALL";
2709 - (NSString *) name {
2710 return name_.empty() ? id_ : name_;
2713 - (UIImage *) icon {
2714 NSString *section = [self simpleSection];
2717 if (parsed_ != NULL)
2718 if (NSString *href = parsed_->icon_)
2719 if ([href hasPrefix:@"file:///"])
2720 // XXX: correct escaping
2721 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2722 if (icon == nil) if (section != nil)
2723 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2724 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2725 if ([dicon hasPrefix:@"file:///"])
2726 // XXX: correct escaping
2727 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2729 icon = [UIImage applicationImageNamed:@"unknown.png"];
2733 - (NSString *) homepage {
2734 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2737 - (NSString *) depiction {
2738 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2741 - (Address *) sponsor {
2742 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2745 - (Address *) author {
2746 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2749 - (NSString *) support {
2750 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2753 - (NSArray *) files {
2754 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2755 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2758 fin.open([path UTF8String]);
2763 while (std::getline(fin, line))
2764 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2769 - (NSArray *) warnings {
2770 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2771 const char *name(iterator_.Name());
2773 size_t length(strlen(name));
2774 if (length < 2) invalid:
2775 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2776 else for (size_t i(0); i != length; ++i)
2778 /* XXX: technically this is not allowed */
2779 (name[i] < 'A' || name[i] > 'Z') &&
2780 (name[i] < 'a' || name[i] > 'z') &&
2781 (name[i] < '0' || name[i] > '9') &&
2782 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2785 if (strcmp(name, "cydia") != 0) {
2788 bool _private = false;
2791 bool repository = [[self section] isEqualToString:@"Repositories"];
2793 if (NSArray *files = [self files])
2794 for (NSString *file in files)
2795 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2797 else if (!user && [file isEqualToString:@"/User"])
2799 else if (!_private && [file isEqualToString:@"/private"])
2801 else if (!stash && [file isEqualToString:@"/var/stash"])
2804 /* XXX: this is not sensitive enough. only some folders are valid. */
2805 if (cydia && !repository)
2806 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2808 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2810 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2812 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2815 return [warnings count] == 0 ? nil : warnings;
2818 - (NSArray *) applications {
2819 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2821 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2823 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2824 if (NSArray *files = [self files])
2825 for (NSString *file in files)
2826 if (application_r(file)) {
2827 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2828 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2829 if ([id isEqualToString:me])
2832 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2834 display = application_r[1];
2836 NSString *bundle([file stringByDeletingLastPathComponent]);
2837 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2838 if (icon == nil || [icon length] == 0)
2840 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2842 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2843 [applications addObject:application];
2845 [application addObject:id];
2846 [application addObject:display];
2847 [application addObject:url];
2850 return [applications count] == 0 ? nil : applications;
2853 - (Source *) source {
2854 if (source_ == nil) {
2855 @synchronized (database_) {
2856 if ([database_ era] != era_ || file_.end())
2857 source_ = (Source *) [NSNull null];
2859 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2863 return source_ == (Source *) [NSNull null] ? nil : source_;
2866 - (BOOL) matches:(NSString *)text {
2872 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2873 if (range.location != NSNotFound)
2876 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2877 if (range.location != NSNotFound)
2882 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2883 if (range.location != NSNotFound)
2889 - (bool) hasSupportingRole {
2894 if ([Role_ isEqualToString:@"User"])
2898 if ([Role_ isEqualToString:@"Hacker"])
2902 if ([Role_ isEqualToString:@"Developer"])
2907 - (BOOL) hasTag:(NSString *)tag {
2908 return tags_ == nil ? NO : [tags_ containsObject:tag];
2911 - (NSString *) primaryPurpose {
2912 for (NSString *tag in tags_)
2913 if ([tag hasPrefix:@"purpose::"])
2914 return [tag substringFromIndex:9];
2918 - (NSArray *) purposes {
2919 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2920 for (NSString *tag in tags_)
2921 if ([tag hasPrefix:@"purpose::"])
2922 [purposes addObject:[tag substringFromIndex:9]];
2923 return [purposes count] == 0 ? nil : purposes;
2926 - (bool) isCommercial {
2927 return [self hasTag:@"cydia::commercial"];
2930 - (void) setIndex:(size_t)index {
2931 if (metadata_->index_ != index)
2932 metadata_->index_ = index;
2935 - (CYString &) cyname {
2936 return name_.empty() ? id_ : name_;
2939 - (uint32_t) compareBySection:(NSArray *)sections {
2940 NSString *section([self section]);
2941 for (size_t i(0), e([sections count]); i != e; ++i) {
2942 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2946 return _not(uint32_t);
2950 @synchronized (database_) {
2951 pkgProblemResolver *resolver = [database_ resolver];
2952 resolver->Clear(iterator_);
2954 pkgCacheFile &cache([database_ cache]);
2955 cache->SetReInstall(iterator_, false);
2956 cache->MarkKeep(iterator_, false);
2960 @synchronized (database_) {
2961 pkgProblemResolver *resolver = [database_ resolver];
2962 resolver->Clear(iterator_);
2963 resolver->Protect(iterator_);
2965 pkgCacheFile &cache([database_ cache]);
2966 cache->SetReInstall(iterator_, false);
2967 cache->MarkInstall(iterator_, false);
2969 pkgDepCache::StateCache &state((*cache)[iterator_]);
2970 if (!state.Install())
2971 cache->SetReInstall(iterator_, true);
2975 @synchronized (database_) {
2976 pkgProblemResolver *resolver = [database_ resolver];
2977 resolver->Clear(iterator_);
2978 resolver->Remove(iterator_);
2979 resolver->Protect(iterator_);
2981 pkgCacheFile &cache([database_ cache]);
2982 cache->SetReInstall(iterator_, false);
2983 cache->MarkDelete(iterator_, true);
2986 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2987 _profile(Package$isUnfilteredAndSearchedForBy)
2990 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2991 value &= [self unfiltered];
2994 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2995 value &= [self matches:search];
3002 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3003 if ([search length] == 0)
3006 _profile(Package$isUnfilteredAndSelectedForBy)
3009 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3010 value &= [self unfiltered];
3013 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3014 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3021 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3022 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3025 - (bool) isVisibleInSection:(NSString *)name {
3026 NSString *section([self section]);
3030 section == nil && [name length] == 0 ||
3031 [name isEqualToString:section]
3032 ) && [self visible];
3035 - (bool) isVisibleInSource:(Source *)source {
3036 return [self source] == source && [self visible];
3041 /* Section Class {{{ */
3042 @interface Section : NSObject {
3047 NSString *localized_;
3050 - (NSComparisonResult) compareByLocalized:(Section *)section;
3051 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3052 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3053 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3054 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3055 - (NSString *) name;
3062 - (void) addToCount;
3064 - (void) setCount:(size_t)count;
3065 - (NSString *) localized;
3069 @implementation Section
3073 if (localized_ != nil)
3074 [localized_ release];
3078 - (NSComparisonResult) compareByLocalized:(Section *)section {
3079 NSString *lhs(localized_);
3080 NSString *rhs([section localized]);
3082 /*if ([lhs length] != 0 && [rhs length] != 0) {
3083 unichar lhc = [lhs characterAtIndex:0];
3084 unichar rhc = [rhs characterAtIndex:0];
3086 if (isalpha(lhc) && !isalpha(rhc))
3087 return NSOrderedAscending;
3088 else if (!isalpha(lhc) && isalpha(rhc))
3089 return NSOrderedDescending;
3092 return [lhs compare:rhs options:LaxCompareOptions_];
3095 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3096 if ((self = [self initWithName:name localize:NO]) != nil) {
3097 if (localized != nil)
3098 localized_ = [localized retain];
3102 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3103 return [self initWithName:name row:0 localize:localize];
3106 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3107 if ((self = [super init]) != nil) {
3108 name_ = [name retain];
3112 localized_ = [LocalizeSection(name_) retain];
3116 /* XXX: localize the index thingees */
3117 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3118 if ((self = [super init]) != nil) {
3119 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3125 - (NSString *) name {
3145 - (void) addToCount {
3149 - (void) setCount:(size_t)count {
3153 - (NSString *) localized {
3160 static NSString *Colon_;
3161 static NSString *Elision_;
3162 static NSString *Error_;
3163 static NSString *Warning_;
3165 /* Database Implementation {{{ */
3166 @implementation Database
3168 + (Database *) sharedInstance {
3169 static Database *instance;
3170 if (instance == nil)
3171 instance = [[Database alloc] init];
3179 - (void) releasePackages {
3180 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3181 CFArrayRemoveAllValues(packages_);
3185 // XXX: actually implement this thing
3187 [sourceList_ release];
3188 [self releasePackages];
3189 apr_pool_destroy(pool_);
3190 NSRecycleZone(zone_);
3194 - (void) _readCydia:(NSNumber *)fd { _pooled
3195 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3196 std::istream is(&ib);
3199 static Pcre finish_r("^finish:([^:]*)$");
3201 while (std::getline(is, line)) {
3202 const char *data(line.c_str());
3203 size_t size = line.size();
3204 lprintf("C:%s\n", data);
3206 if (finish_r(data, size)) {
3207 NSString *finish = finish_r[1];
3208 int index = [Finishes_ indexOfObject:finish];
3209 if (index != INT_MAX && index > Finish_)
3217 - (void) _readStatus:(NSNumber *)fd { _pooled
3218 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3219 std::istream is(&ib);
3222 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3223 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3225 while (std::getline(is, line)) {
3226 const char *data(line.c_str());
3227 size_t size(line.size());
3228 lprintf("S:%s\n", data);
3230 if (conffile_r(data, size))
3231 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3232 else if (strncmp(data, "status: ", 8) == 0)
3233 [delegate_ performSelectorOnMainThread:@selector(setProgressTitle:) withObject:[NSString stringWithUTF8String:(data + 8)] waitUntilDone:YES];
3234 else if (pmstatus_r(data, size)) {
3235 std::string type([pmstatus_r[1] UTF8String]);
3236 NSString *id = pmstatus_r[2];
3238 float percent([pmstatus_r[3] floatValue]);
3239 [delegate_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3241 NSString *string = pmstatus_r[4];
3243 if (type == "pmerror")
3244 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3245 withObject:[NSArray arrayWithObjects:string, id, nil]
3248 else if (type == "pmstatus")
3249 [delegate_ performSelectorOnMainThread:@selector(setProgressTitle:) withObject:string waitUntilDone:YES];
3250 else if (type == "pmconffile")
3251 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3253 lprintf("E:unknown pmstatus\n");
3255 lprintf("E:unknown status\n");
3261 - (void) _readOutput:(NSNumber *)fd { _pooled
3262 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3263 std::istream is(&ib);
3266 while (std::getline(is, line)) {
3267 lprintf("O:%s\n", line.c_str());
3269 [delegate_ performSelectorOnMainThread:@selector(addProgressOutput:) withObject:[NSString stringWithUTF8String:line.c_str()] waitUntilDone:YES];
3279 - (Package *) packageWithName:(NSString *)name {
3280 @synchronized (self) {
3281 if (static_cast<pkgDepCache *>(cache_) == NULL)
3283 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3284 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3288 if ((self = [super init]) != nil) {
3295 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3296 apr_pool_create(&pool_, NULL);
3298 size_t capacity(MetaFile_->active_);
3304 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3305 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3309 _assert(pipe(fds) != -1);
3312 _config->Set("APT::Keep-Fds::", cydiafd_);
3313 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3316 detachNewThreadSelector:@selector(_readCydia:)
3318 withObject:[NSNumber numberWithInt:fds[0]]
3321 _assert(pipe(fds) != -1);
3325 detachNewThreadSelector:@selector(_readStatus:)
3327 withObject:[NSNumber numberWithInt:fds[0]]
3330 _assert(pipe(fds) != -1);
3331 _assert(dup2(fds[0], 0) != -1);
3332 _assert(close(fds[0]) != -1);
3334 input_ = fdopen(fds[1], "a");
3336 _assert(pipe(fds) != -1);
3337 _assert(dup2(fds[1], 1) != -1);
3338 _assert(close(fds[1]) != -1);
3341 detachNewThreadSelector:@selector(_readOutput:)
3343 withObject:[NSNumber numberWithInt:fds[0]]
3348 - (pkgCacheFile &) cache {
3352 - (pkgDepCache::Policy *) policy {
3356 - (pkgRecords *) records {
3360 - (pkgProblemResolver *) resolver {
3364 - (pkgAcquire &) fetcher {
3368 - (pkgSourceList &) list {
3372 - (NSArray *) packages {
3373 return (NSArray *) packages_;
3376 - (NSArray *) sources {
3380 - (Source *) sourceWithKey:(NSString *)key {
3381 for (Source *source in [self sources]) {
3382 if ([[source key] isEqualToString:key])
3387 - (bool) popErrorWithTitle:(NSString *)title {
3389 std::string message;
3391 while (!_error->empty()) {
3393 bool warning(!_error->PopMessage(error));
3397 size_t size(error.size());
3398 if (size == 0 || error[size - 1] != '\n')
3400 error.resize(size - 1);
3402 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3404 if (!message.empty())
3409 if (fatal && !message.empty())
3410 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3415 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3416 return [self popErrorWithTitle:title] || !success;
3419 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3420 @synchronized (self) {
3423 [self releasePackages];
3426 [sourceList_ removeAllObjects];
3446 apr_pool_clear(pool_);
3448 NSRecycleZone(zone_);
3449 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3451 int chk(creat("/tmp/cydia.chk", 0644));
3455 if (invocation != nil)
3456 [invocation invoke];
3458 NSString *title(UCLocalize("DATABASE"));
3461 OpProgress progress;
3462 while (!cache_.Open(progress, true)) { pop:
3464 bool warning(!_error->PopMessage(error));
3465 lprintf("cache_.Open():[%s]\n", error.c_str());
3467 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3468 [delegate_ repairWithSelector:@selector(configure)];
3469 else if (error == "The package lists or status file could not be parsed or opened.")
3470 [delegate_ repairWithSelector:@selector(update)];
3471 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3472 else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3473 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, Error_, title]];
3474 // else if (error == "The list of sources could not be read.")
3476 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3486 unlink("/tmp/cydia.chk");
3488 now_ = [[NSDate date] timeIntervalSince1970];
3490 policy_ = new pkgDepCache::Policy();
3491 records_ = new pkgRecords(cache_);
3492 resolver_ = new pkgProblemResolver(cache_);
3493 fetcher_ = new pkgAcquire(&status_);
3496 list_ = new pkgSourceList();
3497 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3500 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3501 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3505 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3508 if (cache_->BrokenCount() != 0) {
3509 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3512 if (cache_->BrokenCount() != 0) {
3513 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3517 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3521 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3522 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3523 [sourceList_ addObject:object];
3525 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3526 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3527 // XXX: this could be more intelligent
3528 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3529 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3531 sourceMap_[cached->ID] = object;
3536 /*std::vector<Package *> packages;
3537 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3538 [packages_ release];
3543 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3544 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3545 //packages.push_back(package);
3546 CFArrayAppendValue(packages_, [package retain]);
3550 /*if (packages.empty())
3551 packages_ = [[NSArray alloc] init];
3553 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3556 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3557 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3558 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3566 /*if (!packages.empty())
3567 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3568 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3570 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3572 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3574 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3578 size_t count(CFArrayGetCount(packages_));
3579 MetaFile_->active_ = count;
3581 for (size_t index(0); index != count; ++index)
3582 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3586 } } CYPoolEnd() _trace(); }
3589 @synchronized (self) {
3591 resolver_ = new pkgProblemResolver(cache_);
3593 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3594 if (!cache_[iterator].Keep())
3595 cache_->MarkKeep(iterator, false);
3596 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3597 cache_->SetReInstall(iterator, false);
3600 - (void) configure {
3601 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3603 system([dpkg UTF8String]);
3608 // XXX: I don't remember this condition
3613 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3615 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3617 if ([self popErrorWithTitle:title])
3621 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3624 public pkgArchiveCleaner
3627 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3632 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3639 fetcher_->Shutdown();
3641 pkgRecords records(cache_);
3643 lock_ = new FileFd();
3644 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3646 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3648 if ([self popErrorWithTitle:title])
3652 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3655 manager_ = (_system->CreatePM(cache_));
3656 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3663 bool substrate(RestartSubstrate_);
3664 RestartSubstrate_ = false;
3666 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3668 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3670 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3672 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3673 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3676 [CydiaApp performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3678 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3680 [self popErrorWithTitle:title];
3684 bool failed = false;
3685 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3686 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3688 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3694 [CydiaApp performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3702 RestartSubstrate_ = true;
3705 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3707 if (_error->PendingError()) {
3712 if (result == pkgPackageManager::Failed) {
3717 if (result != pkgPackageManager::Completed) {
3722 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3724 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3726 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3727 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3730 if (![before isEqualToArray:after])
3735 NSString *title(UCLocalize("UPGRADE"));
3736 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3742 [self updateWithStatus:status_];
3745 - (void) updateWithStatus:(Status &)status {
3746 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3747 NSString *title(UCLocalize("REFRESHING_DATA"));
3750 if (!list.ReadMainList())
3751 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3754 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3755 if ([self popErrorWithTitle:title])
3758 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3759 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3760 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3762 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3766 - (void) setDelegate:(id)delegate {
3767 delegate_ = delegate;
3768 status_.setDelegate(delegate);
3771 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3772 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3773 return i == sourceMap_.end() ? nil : i->second;
3776 - (NSString *) mappedSectionForPointer:(const char *)section {
3777 _H<NSString> *mapped;
3779 _profile(Database$mappedSectionForPointer$Cache)
3780 mapped = §ions_[section];
3783 if (*mapped == NULL) {
3784 size_t length(strlen(section));
3785 char spaced[length + 1];
3787 _profile(Database$mappedSectionForPointer$Replace)
3788 for (size_t index(0); index != length; ++index)
3789 spaced[index] = section[index] == '_' ? ' ' : section[index];
3790 spaced[length] = '\0';
3795 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3796 string = [NSString stringWithUTF8String:spaced];
3799 _profile(Database$mappedSectionForPointer$Map)
3800 string = [SectionMap_ objectForKey:string] ?: string;
3810 /* Web Scripting {{{ */
3811 @interface CydiaObject : NSObject {
3813 _transient id delegate_;
3816 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3820 @implementation CydiaObject
3823 [indirect_ release];
3827 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3828 if ((self = [super init]) != nil) {
3829 indirect_ = [indirect retain];
3833 - (void) setDelegate:(id)delegate {
3834 delegate_ = delegate;
3837 + (NSArray *) _attributeKeys {
3838 return [NSArray arrayWithObjects:
3848 - (NSArray *) attributeKeys {
3849 return [[self class] _attributeKeys];
3852 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3853 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3856 - (NSString *) device {
3857 return [[UIDevice currentDevice] uniqueIdentifier];
3860 - (NSString *) plmn {
3864 - (NSString *) ecid {
3868 - (NSString *) serial {
3869 return SerialNumber_;
3872 - (NSString *) role {
3876 - (NSString *) model {
3877 return [NSString stringWithUTF8String:Machine_];
3880 + (NSString *) webScriptNameForSelector:(SEL)selector {
3882 else if (selector == @selector(addTrivialSource:))
3883 return @"addTrivialSource";
3884 else if (selector == @selector(close))
3886 else if (selector == @selector(du:))
3888 else if (selector == @selector(stringWithFormat:arguments:))
3890 else if (selector == @selector(getAllSources))
3891 return @"getAllSourcs";
3892 else if (selector == @selector(getKernelNumber:))
3893 return @"getKernelNumber";
3894 else if (selector == @selector(getKernelString:))
3895 return @"getKernelString";
3896 else if (selector == @selector(getInstalledPackages))
3897 return @"getInstalledPackages";
3898 else if (selector == @selector(getPackageById:))
3899 return @"getPackageById";
3900 else if (selector == @selector(installPackages:))
3901 return @"installPackages";
3902 else if (selector == @selector(localizedStringForKey:value:table:))
3904 else if (selector == @selector(refreshSources))
3905 return @"refreshSources";
3906 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3907 return @"setButtonImage";
3908 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3909 return @"setButtonTitle";
3910 else if (selector == @selector(setPopupHook:))
3911 return @"setPopupHook";
3912 else if (selector == @selector(setToken:))
3914 else if (selector == @selector(setViewportWidth:))
3915 return @"setViewportWidth";
3916 else if (selector == @selector(statfs:))
3918 else if (selector == @selector(supports:))
3924 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3925 return [self webScriptNameForSelector:selector] == nil;
3928 - (BOOL) supports:(NSString *)feature {
3929 return [feature isEqualToString:@"window.open"];
3932 - (NSNumber *) getKernelNumber:(NSString *)name {
3933 const char *string([name UTF8String]);
3936 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3937 return (id) [NSNull null];
3939 if (size != sizeof(int))
3940 return (id) [NSNull null];
3943 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3944 return (id) [NSNull null];
3946 return [NSNumber numberWithInt:value];
3949 - (NSString *) getKernelString:(NSString *)name {
3950 const char *string([name UTF8String]);
3953 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3954 return (id) [NSNull null];
3956 char value[size + 1];
3957 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3958 return (id) [NSNull null];
3960 // XXX: just in case you request something ludicrous
3963 return [NSString stringWithCString:value];
3966 - (void) addTrivialSource:(NSString *)href {
3967 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
3970 - (void) refreshSources {
3971 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
3974 - (NSArray *) getAllSources {
3975 return [[Database sharedInstance] sources];
3978 - (NSArray *) getInstalledPackages {
3979 Database *database([Database sharedInstance]);
3980 @synchronized (database) {
3981 NSArray *packages([database packages]);
3982 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3983 for (Package *package in packages)
3984 if (![package uninstalled])
3985 [installed addObject:package];
3989 - (Package *) getPackageById:(NSString *)id {
3990 Package *package([[Database sharedInstance] packageWithName:id]);
3995 - (NSArray *) statfs:(NSString *)path {
3998 if (path == nil || statfs([path UTF8String], &stat) == -1)
4001 return [NSArray arrayWithObjects:
4002 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4003 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4004 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4008 - (NSNumber *) du:(NSString *)path {
4009 NSNumber *value(nil);
4012 _assert(pipe(fds) != -1);
4014 pid_t pid(ExecFork());
4016 _assert(dup2(fds[1], 1) != -1);
4017 _assert(close(fds[0]) != -1);
4018 _assert(close(fds[1]) != -1);
4019 /* XXX: this should probably not use du */
4020 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4025 _assert(close(fds[1]) != -1);
4027 if (FILE *du = fdopen(fds[0], "r")) {
4029 while (fgets(line, sizeof(line), du) != NULL) {
4030 size_t length(strlen(line));
4031 while (length != 0 && line[length - 1] == '\n')
4032 line[--length] = '\0';
4033 if (char *tab = strchr(line, '\t')) {
4035 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4040 } else _assert(close(fds[0]));
4044 if (waitpid(pid, &status, 0) == -1)
4047 else _assert(false);
4053 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4056 - (void) installPackages:(NSArray *)packages {
4057 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4060 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4061 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4064 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4065 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4068 - (void) _setToken:(NSString *)token {
4071 Token_ = [token retain];
4073 [Metadata_ setObject:Token_ forKey:@"Token"];
4077 - (void) setToken:(NSString *)token {
4078 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4081 - (void) setPopupHook:(id)function {
4082 [indirect_ setPopupHook:function];
4085 - (void) setViewportWidth:(float)width {
4086 [indirect_ setViewportWidthOnMainThread:width];
4089 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4090 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4091 unsigned count([arguments count]);
4093 for (unsigned i(0); i != count; ++i)
4094 values[i] = [arguments objectAtIndex:i];
4095 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4098 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4099 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4101 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4103 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4109 /* @ Loading... Indicator {{{ */
4110 @interface CYLoadingIndicator : UIView {
4111 UIActivityIndicatorView *spinner_;
4116 @property (readonly, nonatomic) UILabel *label;
4117 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4121 @implementation CYLoadingIndicator
4123 - (id) initWithFrame:(CGRect)frame {
4124 if ((self = [super initWithFrame:frame]) != nil) {
4125 container_ = [[[UIView alloc] init] autorelease];
4126 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4128 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4129 [spinner_ startAnimating];
4130 [container_ addSubview:spinner_];
4132 label_ = [[[UILabel alloc] init] autorelease];
4133 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4134 [label_ setBackgroundColor:[UIColor clearColor]];
4135 [label_ setTextColor:[UIColor blackColor]];
4136 [label_ setShadowColor:[UIColor whiteColor]];
4137 [label_ setShadowOffset:CGSizeMake(0, 1)];
4138 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4139 [container_ addSubview:label_];
4141 CGSize viewsize = frame.size;
4142 CGSize spinnersize = [spinner_ bounds].size;
4143 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4144 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4146 CGRect containrect = {
4147 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4148 CGSizeMake(bothwidth, spinnersize.height)
4151 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4159 [container_ setFrame:containrect];
4160 [spinner_ setFrame:spinrect];
4161 [label_ setFrame:textrect];
4162 [self addSubview:container_];
4166 - (UILabel *) label {
4170 - (UIActivityIndicatorView *) activityIndicatorView {
4176 /* Emulated Loading Controller {{{ */
4177 @interface CYEmulatedLoadingController : CYViewController <
4179 ConfigurationDelegate
4181 _transient Database *database_;
4182 CYLoadingIndicator *indicator_;
4184 UINavigationBar *navbar_;
4189 @implementation CYEmulatedLoadingController
4192 [self releaseSubviews];
4193 [database_ setDelegate:nil];
4198 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4199 CYAlertView *sheet([[[CYAlertView alloc]
4201 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4202 defaultButtonIndex:0
4205 [sheet setMessage:error];
4206 [sheet yieldToPopupAlertAnimated:YES];
4210 - (void) setProgressTitle:(NSString *)title { }
4211 - (void) setProgressPercent:(NSNumber *)percent { }
4212 - (void) startProgress { }
4213 - (void) addProgressOutput:(NSString *)output { }
4214 - (bool) isCancelling:(size_t)received { return NO; }
4215 - (void) setConfigurationData:(NSString *)data { }
4217 - (void) repairWithSelector:(SEL)selector {
4218 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("REPAIRING"), nil] waitUntilDone:YES];
4219 [database_ performSelector:selector];
4221 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil] waitUntilDone:YES];
4224 - (id) initWithDatabase:(Database *)database {
4225 if ((self = [super init]) != nil) {
4226 database_ = database;
4227 [database_ setDelegate:self];
4232 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4233 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4235 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4236 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4237 [[self view] addSubview:indicator_];
4239 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4240 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4241 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4242 [[self view] addSubview:tabbar_];
4244 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4245 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4246 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4247 [[self view] addSubview:navbar_];
4250 - (void) releaseSubviews {
4251 [indicator_ release];
4264 /* Cydia Browser Controller {{{ */
4265 @interface CYBrowserController : BrowserController {
4266 CydiaObject *cydia_;
4271 @implementation CYBrowserController
4278 - (NSURL *) navigationURL {
4279 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4282 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4285 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4286 [super webView:view didClearWindowObject:window forFrame:frame];
4288 WebDataSource *source([frame dataSource]);
4289 NSURLResponse *response([source response]);
4291 NSURL *url([response URL]);
4292 NSString *scheme([url scheme]);
4293 NSString *host([url host]);
4295 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4296 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4297 NSDictionary *headers([http allHeaderFields]);
4298 [self setHeaders:headers forHost:host];
4302 [host isEqualToString:@"cydia.saurik.com"] ||
4303 [host hasSuffix:@".cydia.saurik.com"] ||
4304 [scheme isEqualToString:@"file"]
4306 [window setValue:cydia_ forKey:@"cydia"];
4309 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4310 if (System_ != NULL)
4311 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4312 if (Machine_ != NULL)
4313 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4315 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4317 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4320 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4321 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4322 [self _setMoreHeaders:copy];
4326 - (void) setDelegate:(id)delegate {
4327 [super setDelegate:delegate];
4328 [cydia_ setDelegate:delegate];
4332 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4333 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4335 WebView *webview([[webview_ _documentView] webView]);
4337 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4339 NSString *application = package == nil ? @"Cydia" : [NSString
4340 stringWithFormat:@"Cydia/%@",
4345 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4347 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4348 if (Product_ != nil)
4349 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4351 [webview setApplicationNameForUserAgent:application];
4359 @interface NSObject (CydiaScript)
4360 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4363 @implementation NSObject (CydiaScript)
4365 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4371 @implementation NSArray (CydiaScript)
4373 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4374 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4375 for (size_t i(0), e([self count]); i != e; ++i)
4376 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4382 @implementation NSDictionary (CydiaScript)
4384 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4385 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4387 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4394 /* Confirmation Controller {{{ */
4395 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4396 if (!iterator.end())
4397 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4398 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4400 pkgCache::PkgIterator package(dep.TargetPkg());
4403 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4410 @protocol ConfirmationControllerDelegate
4411 - (void) cancelAndClear:(bool)clear;
4412 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4416 @interface ConfirmationController : CYBrowserController {
4417 _transient Database *database_;
4419 UIAlertView *essential_;
4421 NSDictionary *changes_;
4422 NSMutableArray *issues_;
4423 NSDictionary *sizes_;
4428 - (id) initWithDatabase:(Database *)database;
4432 @implementation ConfirmationController
4439 if (essential_ != nil)
4440 [essential_ release];
4447 RestartSubstrate_ = true;
4448 [delegate_ confirmWithNavigationController:[self navigationController]];
4451 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4452 NSString *context([alert context]);
4454 if ([context isEqualToString:@"remove"]) {
4455 if (button == [alert cancelButtonIndex])
4456 [self dismissModalViewControllerAnimated:YES];
4457 else if (button == [alert firstOtherButtonIndex]) {
4461 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4462 } else if ([context isEqualToString:@"unable"]) {
4463 [self dismissModalViewControllerAnimated:YES];
4464 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4466 [super alertView:alert clickedButtonAtIndex:button];
4470 - (void) _doContinue {
4471 [self dismissModalViewControllerAnimated:YES];
4472 [delegate_ cancelAndClear:NO];
4475 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4476 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4480 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4481 [super webView:view didClearWindowObject:window forFrame:frame];
4483 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4484 changes_, @"changes",
4488 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4491 - (id) initWithDatabase:(Database *)database {
4492 if ((self = [super init]) != nil) {
4493 database_ = database;
4495 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4496 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4497 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4498 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4499 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4503 pkgCacheFile &cache([database_ cache]);
4504 NSArray *packages([database_ packages]);
4505 pkgDepCache::Policy *policy([database_ policy]);
4507 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4509 for (Package *package in packages) {
4510 pkgCache::PkgIterator iterator([package iterator]);
4511 NSString *name([package id]);
4513 if ([package broken]) {
4514 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4516 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4518 reasons, @"reasons",
4521 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4525 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4526 pkgCache::DepIterator start;
4527 pkgCache::DepIterator end;
4528 dep.GlobOr(start, end); // ++dep
4530 if (!cache->IsImportantDep(end))
4532 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4535 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4537 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4538 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4539 clauses, @"clauses",
4543 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4545 pkgCache::PkgIterator target(start.TargetPkg());
4546 if (target->ProvidesList != 0)
4547 reason = @"missing";
4549 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4551 reason = @"installed";
4552 installed = [NSString stringWithUTF8String:ver.VerStr()];
4553 } else if (!cache[target].CandidateVerIter(cache).end())
4554 reason = @"uninstalled";
4555 else if (target->ProvidesList == 0)
4556 reason = @"uninstallable";
4558 reason = @"virtual";
4561 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4562 [NSString stringWithUTF8String:start.CompType()], @"operator",
4563 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4566 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4567 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4568 version, @"version",
4570 installed, @"installed",
4573 // yes, seriously. (wtf?)
4581 pkgDepCache::StateCache &state(cache[iterator]);
4583 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4585 if (state.NewInstall())
4586 [installs addObject:name];
4587 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4588 [reinstalls addObject:name];
4589 else if (state.Upgrade())
4590 [upgrades addObject:name];
4591 else if (state.Downgrade())
4592 [downgrades addObject:name];
4593 else if (!state.Delete())
4595 else if (special_r(name))
4596 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4597 [NSNull null], @"package",
4598 [NSArray arrayWithObjects:
4599 [NSDictionary dictionaryWithObjectsAndKeys:
4600 @"Conflicts", @"relationship",
4601 [NSArray arrayWithObjects:
4602 [NSDictionary dictionaryWithObjectsAndKeys:
4604 [NSNull null], @"version",
4605 @"installed", @"reason",
4612 if ([package essential])
4614 [removes addObject:name];
4617 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4618 substrate_ |= DepSubstrate(iterator.CurrentVer());
4623 else if (Advanced_) {
4624 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4626 essential_ = [[UIAlertView alloc]
4627 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4628 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4630 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4632 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4636 [essential_ setContext:@"remove"];
4638 essential_ = [[UIAlertView alloc]
4639 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4640 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4642 cancelButtonTitle:UCLocalize("OKAY")
4643 otherButtonTitles:nil
4646 [essential_ setContext:@"unable"];
4649 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4650 installs, @"installs",
4651 reinstalls, @"reinstalls",
4652 upgrades, @"upgrades",
4653 downgrades, @"downgrades",
4654 removes, @"removes",
4657 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4658 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4659 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4662 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4664 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4665 initWithTitle:UCLocalize("CANCEL")
4666 style:UIBarButtonItemStylePlain
4668 action:@selector(cancelButtonClicked)
4674 - (void) applyRightButton {
4675 if ([issues_ count] == 0 && ![self isLoading])
4676 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4677 initWithTitle:UCLocalize("CONFIRM")
4678 style:UIBarButtonItemStyleDone
4680 action:@selector(confirmButtonClicked)
4683 [[self navigationItem] setRightBarButtonItem:nil];
4687 - (void) cancelButtonClicked {
4688 [self dismissModalViewControllerAnimated:YES];
4689 [delegate_ cancelAndClear:YES];
4693 - (void) confirmButtonClicked {
4694 if (essential_ != nil)
4704 /* Progress Data {{{ */
4705 @interface ProgressData : NSObject {
4707 // XXX: should these really both be _transient?
4708 _transient id target_;
4709 _transient id object_;
4712 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4720 @implementation ProgressData
4722 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4723 if ((self = [super init]) != nil) {
4724 selector_ = selector;
4744 /* Progress Controller {{{ */
4745 @interface ProgressController : CYViewController <
4746 ConfigurationDelegate,
4749 _transient Database *database_;
4750 UIProgressBar *progress_;
4751 UITextView *output_;
4752 UITextLabel *status_;
4753 UIPushButton *close_;
4755 SHA1SumValue springlist_;
4756 SHA1SumValue notifyconf_;
4760 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4762 - (void) _retachThread;
4763 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4769 @protocol ProgressControllerDelegate
4770 - (void) progressControllerIsComplete:(ProgressController *)sender;
4773 @implementation ProgressController
4776 [database_ setDelegate:nil];
4777 [progress_ release];
4786 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4787 if ((self = [super init]) != nil) {
4788 database_ = database;
4789 [database_ setDelegate:self];
4790 delegate_ = delegate;
4792 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4794 progress_ = [[UIProgressBar alloc] init];
4795 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4796 [progress_ setStyle:0];
4798 status_ = [[UITextLabel alloc] init];
4799 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4800 [status_ setColor:[UIColor whiteColor]];
4801 [status_ setBackgroundColor:[UIColor clearColor]];
4802 [status_ setCentersHorizontally:YES];
4803 //[status_ setFont:font];
4805 output_ = [[UITextView alloc] init];
4806 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4807 //[output_ setTextFont:@"Courier New"];
4808 [output_ setFont:[[output_ font] fontWithSize:12]];
4809 [output_ setTextColor:[UIColor whiteColor]];
4810 [output_ setBackgroundColor:[UIColor clearColor]];
4811 [output_ setMarginTop:0];
4812 [output_ setAllowsRubberBanding:YES];
4813 [output_ setEditable:NO];
4814 [[self view] addSubview:output_];
4816 close_ = [[UIPushButton alloc] init];
4817 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4818 [close_ setAutosizesToFit:NO];
4819 [close_ setDrawsShadow:YES];
4820 [close_ setStretchBackground:YES];
4821 [close_ setEnabled:YES];
4822 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4823 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4824 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4825 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4829 - (void) positionViews {
4830 CGRect bounds = [[self view] bounds];
4831 CGSize prgsize = [UIProgressBar defaultSize];
4834 (bounds.size.width - prgsize.width) / 2,
4835 bounds.size.height - prgsize.height - 20
4838 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4840 [progress_ setFrame:prgrect];
4841 [status_ setFrame:CGRectMake(
4843 bounds.size.height - prgsize.height - 50,
4844 bounds.size.width - 20,
4847 [output_ setFrame:CGRectMake(
4850 bounds.size.width - 20,
4851 bounds.size.height - 96
4853 [close_ setFrame:CGRectMake(
4854 (bounds.size.width - closewidth) / 2,
4855 bounds.size.height - prgsize.height - 50,
4861 - (void) viewWillAppear:(BOOL)animated {
4862 [super viewDidAppear:animated];
4863 [[self navigationItem] setHidesBackButton:YES];
4864 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4866 [self positionViews];
4869 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4870 [self positionViews];
4873 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4874 NSString *context([alert context]);
4876 if ([context isEqualToString:@"conffile"]) {
4877 FILE *input = [database_ input];
4878 if (button == [alert cancelButtonIndex])
4879 fprintf(input, "N\n");
4880 else if (button == [alert firstOtherButtonIndex])
4881 fprintf(input, "Y\n");
4884 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4888 - (void) closeButtonPushed {
4891 UpdateExternalStatus(0);
4895 [self dismissModalViewControllerAnimated:YES];
4899 [delegate_ terminateWithSuccess];
4900 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4901 [delegate_ suspendWithAnimation:YES];
4903 [delegate_ suspend];*/
4915 system("/usr/bin/sbreload");
4921 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4922 SBReboot(SBSSpringBoardServerPort());
4924 reboot2(RB_AUTOBOOT);
4929 - (void) _retachThread {
4930 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4932 [[self view] addSubview:close_];
4933 [progress_ removeFromSuperview];
4934 [status_ removeFromSuperview];
4936 [database_ popErrorWithTitle:title_];
4937 [delegate_ progressControllerIsComplete:self];
4941 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4944 MMap mmap(file, MMap::ReadOnly);
4946 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4947 if (!(notifyconf_ == sha1.Result()))
4954 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4957 MMap mmap(file, MMap::ReadOnly);
4959 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4960 if (!(springlist_ == sha1.Result()))
4966 if (RestartSubstrate_)
4970 RestartSubstrate_ = false;
4973 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4974 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4975 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4976 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4977 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4981 system("su -c /usr/bin/uicache mobile");
4984 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4986 [delegate_ setStatusBarShowsProgress:NO];
4989 - (void) _detachNewThreadInvocation:(NSInvocation *)invocation { _pooled
4990 [invocation invoke];
4991 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4994 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4995 UpdateExternalStatus(1);
5002 title_ = [title retain];
5004 [[self navigationItem] setTitle:title_];
5006 [status_ setText:nil];
5007 [output_ setText:@""];
5008 [progress_ setProgress:0];
5010 [close_ removeFromSuperview];
5011 [[self view] addSubview:progress_];
5012 [[self view] addSubview:status_];
5014 [delegate_ setStatusBarShowsProgress:YES];
5019 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5022 MMap mmap(file, MMap::ReadOnly);
5024 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5025 notifyconf_ = sha1.Result();
5031 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5034 MMap mmap(file, MMap::ReadOnly);
5036 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5037 springlist_ = sha1.Result();
5041 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
5042 [invocation setTarget:target];
5043 [invocation setSelector:selector];
5044 _assert(object == nil);
5046 [NSThread detachNewThreadSelector:@selector(_detachNewThreadInvocation:) toTarget:self withObject:invocation];
5049 - (void) repairWithSelector:(SEL)selector {
5051 detachNewThreadSelector:selector
5054 title:UCLocalize("REPAIRING")
5058 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
5059 CYAlertView *sheet([[[CYAlertView alloc]
5061 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
5062 defaultButtonIndex:0
5065 [sheet setMessage:error];
5066 [sheet yieldToPopupAlertAnimated:YES];
5070 - (void) startProgress {
5073 - (bool) isCancelling:(size_t)received {
5077 - (void) setConfigurationData:(NSString *)data {
5078 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
5080 if (!conffile_r(data)) {
5081 lprintf("E:invalid conffile\n");
5085 NSString *ofile = conffile_r[1];
5086 //NSString *nfile = conffile_r[2];
5088 UIAlertView *alert = [[[UIAlertView alloc]
5089 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
5090 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
5092 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
5094 UCLocalize("ACCEPT_NEW_COPY"),
5095 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
5099 [alert setContext:@"conffile"];
5103 - (void) setProgressTitle:(NSString *)title {
5104 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
5105 for (size_t i(0), e([words count]); i != e; ++i) {
5106 NSString *word([words objectAtIndex:i]);
5107 if (Package *package = [database_ packageWithName:word])
5108 [words replaceObjectAtIndex:i withObject:[package name]];
5111 [status_ setText:[words componentsJoinedByString:@" "]];
5114 - (void) setProgressPercent:(NSNumber *)percent {
5115 [progress_ setProgress:[percent floatValue]];
5118 - (void) addProgressOutput:(NSString *)output {
5119 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
5120 CGSize size = [output_ contentSize];
5121 CGPoint offset = [output_ contentOffset];
5122 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
5123 CGRect rect = {{0, size.height-1}, {size.width, 1}};
5124 [output_ scrollRectToVisible:rect animated:YES];
5128 - (BOOL) isRunning {
5135 /* Cell Content View {{{ */
5136 @protocol ContentDelegate
5137 - (void) drawContentRect:(CGRect)rect;
5140 @interface ContentView : UIView {
5141 _transient id<ContentDelegate> delegate_;
5146 @implementation ContentView
5148 - (id) initWithFrame:(CGRect)frame {
5149 if ((self = [super initWithFrame:frame]) != nil) {
5150 [self setNeedsDisplayOnBoundsChange:YES];
5154 - (void) setDelegate:(id<ContentDelegate>)delegate {
5155 delegate_ = delegate;
5158 - (void) drawRect:(CGRect)rect {
5159 [super drawRect:rect];
5160 [delegate_ drawContentRect:rect];
5165 /* Cydia TableView Cell {{{ */
5166 @interface CYTableViewCell : UITableViewCell {
5167 ContentView *content_;
5173 @implementation CYTableViewCell
5180 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5181 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5183 if (view == content_) {
5184 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5185 highlighted_ = highlighted;
5188 [super _updateHighlightColorsForView:view highlighted:highlighted];
5191 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5192 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5193 highlighted_ = selected;
5195 [super setSelected:selected animated:animated];
5196 [content_ setNeedsDisplay];
5202 /* Package Cell {{{ */
5203 @interface PackageCell : CYTableViewCell <
5208 NSString *description_;
5216 - (PackageCell *) init;
5217 - (void) setPackage:(Package *)package;
5219 - (void) drawContentRect:(CGRect)rect;
5223 @implementation PackageCell
5225 - (void) clearPackage {
5236 if (description_ != nil) {
5237 [description_ release];
5241 if (source_ != nil) {
5246 if (badge_ != nil) {
5251 if (placard_ != nil) {
5261 [self clearPackage];
5265 - (PackageCell *) init {
5266 CGRect frame(CGRectMake(0, 0, 320, 74));
5267 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5268 UIView *content([self contentView]);
5269 CGRect bounds([content bounds]);
5271 content_ = [[ContentView alloc] initWithFrame:bounds];
5272 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5273 [content addSubview:content_];
5275 [content_ setDelegate:self];
5276 [content_ setOpaque:YES];
5280 - (NSString *) accessibilityLabel {
5281 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5284 - (void) setPackage:(Package *)package {
5285 [self clearPackage];
5288 Source *source = [package source];
5290 icon_ = [[package icon] retain];
5291 name_ = [[package name] retain];
5294 description_ = [package longDescription];
5295 if (description_ == nil)
5296 description_ = [package shortDescription];
5297 if (description_ != nil)
5298 description_ = [description_ retain];
5300 commercial_ = [package isCommercial];
5302 package_ = [package retain];
5304 NSString *label = nil;
5305 bool trusted = false;
5307 if (source != nil) {
5308 label = [source label];
5309 trusted = [source trusted];
5310 } else if ([[package id] isEqualToString:@"firmware"])
5311 label = UCLocalize("APPLE");
5313 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5315 NSString *from(label);
5317 NSString *section = [package simpleSection];
5318 if (section != nil && ![section isEqualToString:label]) {
5319 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5320 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5323 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5324 source_ = [from retain];
5326 if (NSString *purpose = [package primaryPurpose])
5327 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5328 badge_ = [badge_ retain];
5333 if (NSString *mode = [package_ mode]) {
5334 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5335 color = RemovingColor_;
5336 //placard = @"removing";
5338 color = InstallingColor_;
5339 //placard = @"installing";
5342 // XXX: the removing/installing placards are not @2x
5345 color = [UIColor whiteColor];
5347 if ([package installed] != nil)
5348 placard = @"installed";
5353 [content_ setBackgroundColor:color];
5356 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5357 placard_ = [placard_ retain];
5359 [self setNeedsDisplay];
5360 [content_ setNeedsDisplay];
5363 - (void) drawContentRect:(CGRect)rect {
5364 bool highlighted(highlighted_);
5365 float width([self bounds].size.width);
5368 CGContextRef context(UIGraphicsGetCurrentContext());
5369 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5370 CGContextFillRect(context, rect);
5375 rect.size = [icon_ size];
5377 rect.size.width /= 2;
5378 rect.size.height /= 2;
5380 rect.origin.x = 25 - rect.size.width / 2;
5381 rect.origin.y = 25 - rect.size.height / 2;
5383 [icon_ drawInRect:rect];
5386 if (badge_ != nil) {
5388 rect.size = [badge_ size];
5390 rect.size.width /= 2;
5391 rect.size.height /= 2;
5393 rect.origin.x = 36 - rect.size.width / 2;
5394 rect.origin.y = 36 - rect.size.height / 2;
5396 [badge_ drawInRect:rect];
5403 UISetColor(commercial_ ? Purple_ : Black_);
5404 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5405 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5408 UISetColor(commercial_ ? Purplish_ : Gray_);
5409 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5411 if (placard_ != nil)
5412 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5417 /* Section Cell {{{ */
5418 @interface SectionCell : CYTableViewCell <
5430 - (void) setSection:(Section *)section editing:(BOOL)editing;
5434 @implementation SectionCell
5436 - (void) clearSection {
5437 if (basic_ != nil) {
5442 if (section_ != nil) {
5452 if (count_ != nil) {
5459 [self clearSection];
5465 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5466 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5467 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5468 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5469 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5471 UIView *content([self contentView]);
5472 CGRect bounds([content bounds]);
5474 content_ = [[ContentView alloc] initWithFrame:bounds];
5475 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5476 [content addSubview:content_];
5477 [content_ setBackgroundColor:[UIColor whiteColor]];
5479 [content_ setDelegate:self];
5483 - (void) onSwitch:(id)sender {
5484 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5485 if (metadata == nil) {
5486 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5487 [Sections_ setObject:metadata forKey:basic_];
5490 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5494 - (void) setSection:(Section *)section editing:(BOOL)editing {
5495 if (editing != editing_) {
5497 [switch_ removeFromSuperview];
5499 [self addSubview:switch_];
5503 [self clearSection];
5505 if (section == nil) {
5506 name_ = [UCLocalize("ALL_PACKAGES") retain];
5509 basic_ = [section name];
5511 basic_ = [basic_ retain];
5513 section_ = [section localized];
5514 if (section_ != nil)
5515 section_ = [section_ retain];
5517 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5518 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5521 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5524 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5525 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5527 [content_ setNeedsDisplay];
5530 - (void) setFrame:(CGRect)frame {
5531 [super setFrame:frame];
5533 CGRect rect([switch_ frame]);
5534 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5537 - (NSString *) accessibilityLabel {
5541 - (void) drawContentRect:(CGRect)rect {
5542 bool highlighted(highlighted_ && !editing_);
5544 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5549 float width(rect.size.width);
5555 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5557 CGSize size = [count_ sizeWithFont:Font14_];
5561 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5567 /* File Table {{{ */
5568 @interface FileTable : CYViewController <
5569 UITableViewDataSource,
5572 _transient Database *database_;
5575 NSMutableArray *files_;
5579 - (id) initWithDatabase:(Database *)database;
5580 - (void) setPackage:(Package *)package;
5584 @implementation FileTable
5587 [self releaseSubviews];
5596 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5597 return files_ == nil ? 0 : [files_ count];
5600 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5604 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5605 static NSString *reuseIdentifier = @"Cell";
5607 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5609 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5610 [cell setFont:[UIFont systemFontOfSize:16]];
5612 [cell setText:[files_ objectAtIndex:indexPath.row]];
5613 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5618 - (NSURL *) navigationURL {
5619 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5623 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5625 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5626 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5627 [list_ setRowHeight:24.0f];
5628 [list_ setDataSource:self];
5629 [list_ setDelegate:self];
5630 [[self view] addSubview:list_];
5633 - (void) viewDidLoad {
5634 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5637 - (void) releaseSubviews {
5642 - (id) initWithDatabase:(Database *)database {
5643 if ((self = [super init]) != nil) {
5644 database_ = database;
5646 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5650 - (void) setPackage:(Package *)package {
5651 if (package_ != nil) {
5652 [package_ autorelease];
5661 [files_ removeAllObjects];
5663 if (package != nil) {
5664 package_ = [package retain];
5665 name_ = [[package id] retain];
5667 if (NSArray *files = [package files])
5668 [files_ addObjectsFromArray:files];
5670 if ([files_ count] != 0) {
5671 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5672 [files_ removeObjectAtIndex:0];
5673 [files_ sortUsingSelector:@selector(compareByPath:)];
5675 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5676 [stack addObject:@"/"];
5678 for (int i(0), e([files_ count]); i != e; ++i) {
5679 NSString *file = [files_ objectAtIndex:i];
5680 while (![file hasPrefix:[stack lastObject]])
5681 [stack removeLastObject];
5682 NSString *directory = [stack lastObject];
5683 [stack addObject:[file stringByAppendingString:@"/"]];
5684 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5685 ([stack count] - 2) * 3, "",
5686 [file substringFromIndex:[directory length]]
5695 - (void) reloadData {
5698 [self setPackage:[database_ packageWithName:name_]];
5703 /* Package Controller {{{ */
5704 @interface CYPackageController : CYBrowserController <
5705 UIActionSheetDelegate
5707 _transient Database *database_;
5711 NSMutableArray *buttons_;
5712 UIBarButtonItem *button_;
5715 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5719 @implementation CYPackageController
5722 if (package_ != nil)
5735 - (NSURL *) navigationURL {
5736 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5739 /* XXX: this is not safe at all... localization of /fail/ */
5740 - (void) _clickButtonWithName:(NSString *)name {
5741 if ([name isEqualToString:UCLocalize("CLEAR")])
5742 [delegate_ clearPackage:package_];
5743 else if ([name isEqualToString:UCLocalize("INSTALL")])
5744 [delegate_ installPackage:package_];
5745 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5746 [delegate_ installPackage:package_];
5747 else if ([name isEqualToString:UCLocalize("REMOVE")])
5748 [delegate_ removePackage:package_];
5749 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5750 [delegate_ installPackage:package_];
5751 else _assert(false);
5754 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5755 NSString *context([sheet context]);
5757 if ([context isEqualToString:@"modify"]) {
5758 if (button != [sheet cancelButtonIndex]) {
5759 NSString *buttonName = [buttons_ objectAtIndex:button];
5760 [self _clickButtonWithName:buttonName];
5763 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5767 - (bool) _allowJavaScriptPanel {
5772 - (void) _customButtonClicked {
5773 int count([buttons_ count]);
5778 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5780 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5781 [buttons addObjectsFromArray:buttons_];
5783 UIActionSheet *sheet = [[[UIActionSheet alloc]
5786 cancelButtonTitle:nil
5787 destructiveButtonTitle:nil
5788 otherButtonTitles:nil
5791 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5793 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5794 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5796 [sheet setContext:@"modify"];
5798 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5802 // We don't want to allow non-commercial packages to do custom things to the install button,
5803 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5804 - (void) customButtonClicked {
5806 [super customButtonClicked];
5808 [self _customButtonClicked];
5811 - (void) reloadButtonClicked {
5812 // Don't reload a commerical package by tapping the loading button,
5813 // but if it's not an Install button, we should forward it on.
5814 if (![package_ uninstalled])
5815 [self _customButtonClicked];
5818 - (void) applyLoadingTitle {
5819 // Don't show "Loading" as the title. Ever.
5822 - (UIBarButtonItem *) rightButton {
5827 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5828 if ((self = [super init]) != nil) {
5829 database_ = database;
5830 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5831 name_ = [[NSString alloc] initWithString:name];
5832 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5836 - (void) reloadData {
5837 if (package_ != nil)
5838 [package_ autorelease];
5839 package_ = [database_ packageWithName:name_];
5841 [buttons_ removeAllObjects];
5843 if (package_ != nil) {
5846 package_ = [package_ retain];
5847 commercial_ = [package_ isCommercial];
5849 if ([package_ mode] != nil)
5850 [buttons_ addObject:UCLocalize("CLEAR")];
5851 if ([package_ source] == nil);
5852 else if ([package_ upgradableAndEssential:NO])
5853 [buttons_ addObject:UCLocalize("UPGRADE")];
5854 else if ([package_ uninstalled])
5855 [buttons_ addObject:UCLocalize("INSTALL")];
5857 [buttons_ addObject:UCLocalize("REINSTALL")];
5858 if (![package_ uninstalled])
5859 [buttons_ addObject:UCLocalize("REMOVE")];
5866 switch ([buttons_ count]) {
5867 case 0: title = nil; break;
5868 case 1: title = [buttons_ objectAtIndex:0]; break;
5869 default: title = UCLocalize("MODIFY"); break;
5872 button_ = [[UIBarButtonItem alloc]
5874 style:UIBarButtonItemStylePlain
5876 action:@selector(customButtonClicked)
5882 - (bool) isLoading {
5883 return commercial_ ? [super isLoading] : false;
5889 /* Package List Controller {{{ */
5890 @interface PackageListController : CYViewController <
5891 UITableViewDataSource,
5894 _transient Database *database_;
5896 NSMutableArray *packages_;
5897 NSMutableArray *sections_;
5899 NSMutableArray *index_;
5900 NSMutableDictionary *indices_;
5904 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5905 - (void) setDelegate:(id)delegate;
5906 - (void) resetCursor;
5910 @implementation PackageListController
5913 [packages_ release];
5914 [sections_ release];
5923 - (void) deselectWithAnimation:(BOOL)animated {
5924 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5927 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5928 CGRect base = [[self view] bounds];
5929 base.size.height -= bounds.size.height;
5930 base.origin = [list_ frame].origin;
5932 [UIView beginAnimations:nil context:NULL];
5933 [UIView setAnimationBeginsFromCurrentState:YES];
5934 [UIView setAnimationCurve:curve];
5935 [UIView setAnimationDuration:duration];
5936 [list_ setFrame:base];
5937 [UIView commitAnimations];
5940 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5941 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5944 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5945 [self resizeForKeyboardBounds:bounds duration:0];
5948 - (void) keyboardWillShow:(NSNotification *)notification {
5951 NSTimeInterval duration;
5952 UIViewAnimationCurve curve;
5953 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5954 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5955 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5956 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5958 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);
5959 UIViewController *base = self;
5960 while ([base parentViewController] != nil)
5961 base = [base parentViewController];
5962 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5963 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5965 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5968 - (void) keyboardWillHide:(NSNotification *)notification {
5969 NSTimeInterval duration;
5970 UIViewAnimationCurve curve;
5971 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5972 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5974 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5977 - (void) viewWillAppear:(BOOL)animated {
5978 [super viewWillAppear:animated];
5980 [self resizeForKeyboardBounds:CGRectZero];
5981 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5982 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5985 - (void) viewWillDisappear:(BOOL)animated {
5986 [super viewWillDisappear:animated];
5988 [self resizeForKeyboardBounds:CGRectZero];
5989 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5990 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5993 - (void) viewDidAppear:(BOOL)animated {
5994 [super viewDidAppear:animated];
5995 [self deselectWithAnimation:animated];
5998 - (void) didSelectPackage:(Package *)package {
5999 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6000 [view setDelegate:delegate_];
6001 [[self navigationController] pushViewController:view animated:YES];
6004 #if TryIndexedCollation
6005 + (BOOL) hasIndexedCollation {
6006 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6010 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6011 NSInteger count([sections_ count]);
6012 return count == 0 ? 1 : count;
6015 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6016 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6018 return [[sections_ objectAtIndex:section] name];
6021 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6022 if ([sections_ count] == 0)
6024 return [[sections_ objectAtIndex:section] count];
6027 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6028 @synchronized (database_) {
6029 if ([database_ era] != era_)
6032 Section *section([sections_ objectAtIndex:[path section]]);
6033 NSInteger row([path row]);
6034 Package *package([packages_ objectAtIndex:([section row] + row)]);
6035 return [[package retain] autorelease];
6038 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6039 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6041 cell = [[[PackageCell alloc] init] autorelease];
6042 [cell setPackage:[self packageAtIndexPath:path]];
6046 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6047 Package *package([self packageAtIndexPath:path]);
6048 package = [database_ packageWithName:[package id]];
6049 [self didSelectPackage:package];
6052 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6053 // XXX: is 20 the most optimal number here?
6054 return [packages_ count] > 20 ? index_ : nil;
6057 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6058 #if TryIndexedCollation
6059 if ([[self class] hasIndexedCollation]) {
6060 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6067 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6068 if ((self = [super init]) != nil) {
6069 database_ = database;
6070 title_ = [title copy];
6071 [[self navigationItem] setTitle:title_];
6073 #if TryIndexedCollation
6074 if ([[self class] hasIndexedCollation])
6075 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6078 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6080 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6082 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6083 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6085 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6086 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6087 [list_ setRowHeight:73];
6088 [[self view] addSubview:list_];
6090 [list_ setDataSource:self];
6091 [list_ setDelegate:self];
6095 - (void) setDelegate:(id)delegate {
6096 delegate_ = delegate;
6099 - (bool) hasPackage:(Package *)package {
6103 - (void) reloadData {
6106 era_ = [database_ era];
6107 NSArray *packages = [database_ packages];
6109 [packages_ removeAllObjects];
6110 [sections_ removeAllObjects];
6112 _profile(PackageTable$reloadData$Filter)
6113 for (Package *package in packages)
6114 if ([self hasPackage:package])
6115 [packages_ addObject:package];
6118 [indices_ removeAllObjects];
6120 Section *section = nil;
6122 #if TryIndexedCollation
6123 if ([[self class] hasIndexedCollation]) {
6124 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6125 NSArray *titles = [collation sectionIndexTitles];
6128 _profile(PackageTable$reloadData$Section)
6129 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6133 _profile(PackageTable$reloadData$Section$Package)
6134 package = [packages_ objectAtIndex:offset];
6135 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6138 while (secidx < index) {
6141 _profile(PackageTable$reloadData$Section$Allocate)
6142 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6145 _profile(PackageTable$reloadData$Section$Add)
6146 [sections_ addObject:section];
6150 [section addToCount];
6156 [index_ removeAllObjects];
6158 _profile(PackageTable$reloadData$Section)
6159 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6163 _profile(PackageTable$reloadData$Section$Package)
6164 package = [packages_ objectAtIndex:offset];
6165 index = [package index];
6168 if (section == nil || [section index] != index) {
6169 _profile(PackageTable$reloadData$Section$Allocate)
6170 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6173 [index_ addObject:[section name]];
6174 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6176 _profile(PackageTable$reloadData$Section$Add)
6177 [sections_ addObject:section];
6181 [section addToCount];
6186 _profile(PackageTable$reloadData$List)
6191 - (void) resetCursor {
6192 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6197 /* Filtered Package List Controller {{{ */
6198 @interface FilteredPackageListController : PackageListController {
6204 - (void) setObject:(id)object;
6205 - (void) setObject:(id)object forFilter:(SEL)filter;
6207 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6211 @implementation FilteredPackageListController
6219 - (void) setFilter:(SEL)filter {
6222 /* XXX: this is an unsafe optimization of doomy hell */
6223 Method method(class_getInstanceMethod([Package class], filter));
6224 _assert(method != NULL);
6225 imp_ = method_getImplementation(method);
6226 _assert(imp_ != NULL);
6229 - (void) setObject:(id)object {
6235 object_ = [object retain];
6238 - (void) setObject:(id)object forFilter:(SEL)filter {
6239 [self setFilter:filter];
6240 [self setObject:object];
6243 - (bool) hasPackage:(Package *)package {
6244 _profile(FilteredPackageTable$hasPackage)
6245 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6249 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6250 if ((self = [super initWithDatabase:database title:title]) != nil) {
6251 [self setFilter:filter];
6252 [self setObject:object];
6259 /* Home Controller {{{ */
6260 @interface HomeController : CYBrowserController {
6265 @implementation HomeController
6267 + (BOOL) shouldHideNavigationBar {
6271 - (NSURL *) navigationURL {
6272 return [NSURL URLWithString:@"cydia://home"];
6275 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6276 [super _setMoreHeaders:request];
6279 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6280 if (UniqueID_ != nil)
6281 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6283 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6286 - (void) aboutButtonClicked {
6287 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6289 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6290 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6291 [alert setCancelButtonIndex:0];
6294 @"Copyright (C) 2008-2011\n"
6295 "Jay Freeman (saurik)\n"
6296 "saurik@saurik.com\n"
6297 "http://www.saurik.com/"
6303 - (void) viewWillDisappear:(BOOL)animated {
6304 [super viewWillDisappear:animated];
6306 if ([[self class] shouldHideNavigationBar])
6307 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6310 - (void) viewWillAppear:(BOOL)animated {
6311 if (![self hasLoaded])
6312 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6314 [super viewWillAppear:animated];
6316 if ([[self class] shouldHideNavigationBar])
6317 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6320 - (void) viewDidLoad {
6321 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6322 initWithTitle:UCLocalize("ABOUT")
6323 style:UIBarButtonItemStylePlain
6325 action:@selector(aboutButtonClicked)
6331 /* Manage Controller {{{ */
6332 @interface ManageController : CYBrowserController {
6335 - (void) queueStatusDidChange;
6339 @implementation ManageController
6341 - (NSURL *) navigationURL {
6342 return [NSURL URLWithString:@"cydia://manage"];
6345 - (void) viewWillAppear:(BOOL)animated {
6346 if (![self hasLoaded])
6347 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6349 [super viewWillAppear:animated];
6352 - (void) viewDidLoad {
6353 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6354 initWithTitle:UCLocalize("SETTINGS")
6355 style:UIBarButtonItemStylePlain
6357 action:@selector(settingsButtonClicked)
6360 [self queueStatusDidChange];
6363 - (void) settingsButtonClicked {
6364 [delegate_ showSettings];
6368 - (void) queueButtonClicked {
6372 - (void) applyLoadingTitle {
6373 // Disable "Loading" title.
6376 - (void) applyRightButton {
6377 // Disable right button.
6381 - (void) queueStatusDidChange {
6383 if (!IsWildcat_ && Queuing_) {
6384 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6385 initWithTitle:UCLocalize("QUEUE")
6386 style:UIBarButtonItemStyleDone
6388 action:@selector(queueButtonClicked)
6391 [[self navigationItem] setRightBarButtonItem:nil];
6396 - (bool) isLoading {
6397 // Never show as loading.
6404 /* Refresh Bar {{{ */
6405 @interface RefreshBar : UINavigationBar {
6406 UIProgressIndicator *indicator_;
6407 UITextLabel *prompt_;
6408 UIProgressBar *progress_;
6409 UINavigationButton *cancel_;
6414 @implementation RefreshBar
6417 [indicator_ release];
6419 [progress_ release];
6424 - (void) positionViews {
6425 CGRect frame = [cancel_ frame];
6426 frame.size = [cancel_ sizeThatFits:frame.size];
6427 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6428 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6429 [cancel_ setFrame:frame];
6431 CGSize prgsize = {75, 100};
6433 [self frame].size.width - prgsize.width - 10,
6434 ([self frame].size.height - prgsize.height) / 2
6436 [progress_ setFrame:prgrect];
6438 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6439 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6440 CGRect indrect = {{indoffset, indoffset}, indsize};
6441 [indicator_ setFrame:indrect];
6443 CGSize prmsize = {215, indsize.height + 4};
6445 indoffset * 2 + indsize.width,
6446 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6448 [prompt_ setFrame:prmrect];
6451 - (void) setFrame:(CGRect)frame {
6452 [super setFrame:frame];
6453 [self positionViews];
6456 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6457 if ((self = [super initWithFrame:frame]) != nil) {
6458 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6460 [self setBarStyle:UIBarStyleBlack];
6462 UIBarStyle barstyle([self _barStyle:NO]);
6463 bool ugly(barstyle == UIBarStyleDefault);
6465 UIProgressIndicatorStyle style = ugly ?
6466 UIProgressIndicatorStyleMediumBrown :
6467 UIProgressIndicatorStyleMediumWhite;
6469 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6470 [indicator_ setStyle:style];
6471 [indicator_ startAnimation];
6472 [self addSubview:indicator_];
6474 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6475 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6476 [prompt_ setBackgroundColor:[UIColor clearColor]];
6477 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6478 [self addSubview:prompt_];
6480 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6481 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6482 [progress_ setStyle:0];
6483 [self addSubview:progress_];
6485 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6486 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6487 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6488 [cancel_ setBarStyle:barstyle];
6490 [self positionViews];
6495 [cancel_ removeFromSuperview];
6499 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6500 [progress_ setProgress:0];
6501 [self addSubview:cancel_];
6505 [cancel_ removeFromSuperview];
6508 - (void) setPrompt:(NSString *)prompt {
6509 [prompt_ setText:prompt];
6512 - (void) setProgress:(float)progress {
6513 [progress_ setProgress:progress];
6519 @class CYNavigationController;
6521 /* Cydia Tab Bar Controller {{{ */
6522 @interface CYTabBarController : UITabBarController <
6523 UITabBarControllerDelegate,
6526 _transient Database *database_;
6527 RefreshBar *refreshbar_;
6531 // XXX: ok, "updatedelegate_"?...
6532 _transient NSObject<CydiaDelegate> *updatedelegate_;
6535 UIViewController *remembered_;
6536 _transient UIViewController *transient_;
6539 - (NSArray *) navigationURLCollection;
6540 - (void) dropBar:(BOOL)animated;
6541 - (void) beginUpdate;
6542 - (void) raiseBar:(BOOL)animated;
6547 @implementation CYTabBarController
6549 - (void) setUnselectedViewController:(UIViewController *)transient {
6550 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6551 if (transient != nil) {
6552 if (transient_ == nil)
6553 remembered_ = [[controllers objectAtIndex:0] retain];
6554 transient_ = transient;
6555 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6556 [controllers replaceObjectAtIndex:0 withObject:transient_];
6557 [self setSelectedIndex:0];
6558 [self setViewControllers:controllers];
6559 [self concealTabBarSelection];
6560 } else if (remembered_ != nil) {
6561 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6562 transient_ = transient;
6563 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6564 [remembered_ release];
6566 [self setViewControllers:controllers];
6567 [self revealTabBarSelection];
6571 - (UIViewController *) unselectedViewController {
6575 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6576 if ([self unselectedViewController])
6577 [self setUnselectedViewController:nil];
6580 - (NSArray *) navigationURLCollection {
6581 NSMutableArray *items([NSMutableArray array]);
6583 // XXX: Should this deal with transient view controllers?
6584 for (id navigation in [self viewControllers]) {
6585 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6587 [items addObject:stack];
6593 - (void) reloadData {
6594 for (CYViewController *controller in [self viewControllers])
6595 [controller reloadData];
6597 [(CYNavigationController *)[self unselectedViewController] reloadData];
6601 [refreshbar_ release];
6602 [[NSNotificationCenter defaultCenter] removeObserver:self];
6607 - (id) initWithDatabase:(Database *)database {
6608 if ((self = [super init]) != nil) {
6609 database_ = database;
6610 [self setDelegate:self];
6612 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6613 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6615 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6619 - (void) setUpdate:(NSDate *)date {
6623 - (void) beginUpdate {
6624 [refreshbar_ start];
6627 [updatedelegate_ retainNetworkActivityIndicator];
6631 detachNewThreadSelector:@selector(performUpdate)
6637 - (void) performUpdate { _pooled
6639 status.setDelegate(self);
6640 [database_ updateWithStatus:status];
6643 performSelectorOnMainThread:@selector(completeUpdate)
6649 - (void) stopUpdateWithSelector:(SEL)selector {
6651 [updatedelegate_ releaseNetworkActivityIndicator];
6653 [self raiseBar:YES];
6656 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6659 - (void) completeUpdate {
6662 [self stopUpdateWithSelector:@selector(reloadData)];
6665 - (void) cancelUpdate {
6666 [self stopUpdateWithSelector:@selector(updateData)];
6669 - (void) cancelPressed {
6670 [self cancelUpdate];
6677 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6678 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6681 - (void) startProgress {
6684 - (bool) isCancelling:(size_t)received {
6688 - (void) setProgressTitle:(NSString *)title {
6689 [refreshbar_ setPrompt:title];
6692 - (void) setProgressPercent:(NSNumber *)percent {
6693 [refreshbar_ setProgress:[percent floatValue]];
6696 - (void) addProgressOutput:(NSString *)output {
6699 - (void) setUpdateDelegate:(id)delegate {
6700 updatedelegate_ = delegate;
6703 - (CGFloat) statusBarHeight {
6704 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6705 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6707 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6711 - (UIView *) transitionView {
6712 if ([self respondsToSelector:@selector(_transitionView)])
6713 return [self _transitionView];
6715 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6718 - (void) dropBar:(BOOL)animated {
6723 UIView *transition([self transitionView]);
6724 [[self view] addSubview:refreshbar_];
6726 CGRect barframe([refreshbar_ frame]);
6728 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6729 barframe.origin.y = [self statusBarHeight];
6731 barframe.origin.y = 0;
6733 [refreshbar_ setFrame:barframe];
6736 [UIView beginAnimations:nil context:NULL];
6738 CGRect viewframe = [transition frame];
6739 viewframe.origin.y += barframe.size.height;
6740 viewframe.size.height -= barframe.size.height;
6741 [transition setFrame:viewframe];
6744 [UIView commitAnimations];
6746 // Ensure bar has the proper width for our view, it might have changed
6747 barframe.size.width = viewframe.size.width;
6748 [refreshbar_ setFrame:barframe];
6750 // XXX: fix Apple's layout bug
6751 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6754 - (void) raiseBar:(BOOL)animated {
6759 UIView *transition([self transitionView]);
6760 [refreshbar_ removeFromSuperview];
6762 CGRect barframe([refreshbar_ frame]);
6765 [UIView beginAnimations:nil context:NULL];
6767 CGRect viewframe = [transition frame];
6768 viewframe.origin.y -= barframe.size.height;
6769 viewframe.size.height += barframe.size.height;
6770 [transition setFrame:viewframe];
6773 [UIView commitAnimations];
6775 // XXX: fix Apple's layout bug
6776 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6780 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6781 // XXX: fix Apple's layout bug
6782 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6786 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6787 bool dropped(dropped_);
6792 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6797 // XXX: fix Apple's layout bug
6798 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6801 - (void) statusBarFrameChanged:(NSNotification *)notification {
6810 /* Cydia Navigation Controller {{{ */
6811 @interface CYNavigationController : UINavigationController {
6812 _transient Database *database_;
6813 _transient id<UINavigationControllerDelegate> delegate_;
6816 - (NSArray *) navigationURLCollection;
6817 - (id) initWithDatabase:(Database *)database;
6818 - (void) reloadData;
6823 @implementation CYNavigationController
6825 - (NSArray *) navigationURLCollection {
6826 NSMutableArray *stack([NSMutableArray array]);
6828 for (CYViewController *controller in [self viewControllers]) {
6829 NSString *url = [[controller navigationURL] absoluteString];
6831 [stack addObject:url];
6837 - (void) reloadData {
6838 for (CYViewController *page in [self viewControllers]) {
6839 // Only reload controllers that have already loaded.
6840 // This prevents a page from accidentally loading too
6841 // early if it hasn't been shown on the screen yet.
6842 if ([page hasLoaded])
6847 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6848 delegate_ = delegate;
6851 - (id) initWithDatabase:(Database *)database {
6852 if ((self = [super init]) != nil) {
6853 database_ = database;
6860 /* Cydia:// Protocol {{{ */
6861 @interface CydiaURLProtocol : NSURLProtocol {
6866 @implementation CydiaURLProtocol
6868 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6869 NSURL *url([request URL]);
6872 NSString *scheme([[url scheme] lowercaseString]);
6873 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6878 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6882 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6883 id<NSURLProtocolClient> client([self client]);
6885 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6887 NSData *data(UIImagePNGRepresentation(icon));
6889 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6890 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6891 [client URLProtocol:self didLoadData:data];
6892 [client URLProtocolDidFinishLoading:self];
6896 - (void) startLoading {
6897 id<NSURLProtocolClient> client([self client]);
6898 NSURLRequest *request([self request]);
6900 NSURL *url([request URL]);
6901 NSString *href([url absoluteString]);
6903 NSString *path([href substringFromIndex:8]);
6904 NSRange slash([path rangeOfString:@"/"]);
6907 if (slash.location == NSNotFound) {
6911 command = [path substringToIndex:slash.location];
6912 path = [path substringFromIndex:(slash.location + 1)];
6915 Database *database([Database sharedInstance]);
6917 if ([command isEqualToString:@"package-icon"]) {
6920 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6921 Package *package([database packageWithName:path]);
6924 UIImage *icon([package icon]);
6925 [self _returnPNGWithImage:icon forRequest:request];
6926 } else if ([command isEqualToString:@"source-icon"]) {
6929 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6930 NSString *source(Simplify(path));
6931 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6933 icon = [UIImage applicationImageNamed:@"unknown.png"];
6934 [self _returnPNGWithImage:icon forRequest:request];
6935 } else if ([command isEqualToString:@"uikit-image"]) {
6938 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6939 UIImage *icon(_UIImageWithName(path));
6940 [self _returnPNGWithImage:icon forRequest:request];
6941 } else if ([command isEqualToString:@"section-icon"]) {
6944 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6945 NSString *section(Simplify(path));
6946 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6948 icon = [UIImage applicationImageNamed:@"unknown.png"];
6949 [self _returnPNGWithImage:icon forRequest:request];
6951 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6955 - (void) stopLoading {
6961 /* Section Controller {{{ */
6962 @interface SectionController : FilteredPackageListController {
6966 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6970 @implementation SectionController
6972 - (NSURL *) navigationURL {
6973 NSString *name = section_;
6977 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6980 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6983 title = UCLocalize("ALL_PACKAGES");
6984 else if (![name isEqual:@""])
6985 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6987 title = UCLocalize("NO_SECTION");
6989 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6996 /* Sections Controller {{{ */
6997 @interface SectionsController : CYViewController <
6998 UITableViewDataSource,
7001 _transient Database *database_;
7002 NSMutableArray *sections_;
7003 NSMutableArray *filtered_;
7008 - (id) initWithDatabase:(Database *)database;
7009 - (void) editButtonClicked;
7013 @implementation SectionsController
7016 [self releaseSubviews];
7017 [sections_ release];
7018 [filtered_ release];
7023 - (NSURL *) navigationURL {
7024 return [NSURL URLWithString:@"cydia://sections"];
7027 - (void) updateNavigationItem {
7028 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7029 if ([sections_ count] == 0) {
7030 [[self navigationItem] setRightBarButtonItem:nil];
7032 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7033 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7035 action:@selector(editButtonClicked)
7036 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7040 - (BOOL) isEditing {
7044 - (void) setEditing:(BOOL)editing {
7045 if ((editing_ = editing))
7048 [delegate_ updateData];
7050 [self updateNavigationItem];
7053 - (void) viewDidAppear:(BOOL)animated {
7054 [super viewDidAppear:animated];
7055 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7058 - (void) viewWillDisappear:(BOOL)animated {
7059 [super viewWillDisappear:animated];
7060 if (editing_) [self setEditing:NO];
7063 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7064 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7068 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7069 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7072 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7076 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7077 static NSString *reuseIdentifier = @"SectionCell";
7079 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7081 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7083 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7088 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7092 Section *section = [self sectionAtIndexPath:indexPath];
7094 SectionController *controller = [[[SectionController alloc]
7095 initWithDatabase:database_
7096 section:[section name]
7098 [controller setDelegate:delegate_];
7100 [[self navigationController] pushViewController:controller animated:YES];
7104 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7106 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7107 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7108 [list_ setRowHeight:45.0f];
7109 [list_ setDataSource:self];
7110 [list_ setDelegate:self];
7111 [[self view] addSubview:list_];
7114 - (void) viewDidLoad {
7115 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7118 - (void) releaseSubviews {
7123 - (id) initWithDatabase:(Database *)database {
7124 if ((self = [super init]) != nil) {
7125 database_ = database;
7127 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7128 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7132 - (void) reloadData {
7135 NSArray *packages = [database_ packages];
7137 [sections_ removeAllObjects];
7138 [filtered_ removeAllObjects];
7140 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7143 for (Package *package in packages) {
7144 NSString *name([package section]);
7145 NSString *key(name == nil ? @"" : name);
7149 _profile(SectionsView$reloadData$Section)
7150 section = [sections objectForKey:key];
7151 if (section == nil) {
7152 _profile(SectionsView$reloadData$Section$Allocate)
7153 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7154 [sections setObject:section forKey:key];
7159 [section addToCount];
7161 _profile(SectionsView$reloadData$Filter)
7162 if (![package valid] || ![package visible])
7170 [sections_ addObjectsFromArray:[sections allValues]];
7172 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7174 for (Section *section in sections_) {
7175 size_t count([section row]);
7179 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7180 [section setCount:count];
7181 [filtered_ addObject:section];
7184 [self updateNavigationItem];
7189 - (void) editButtonClicked {
7190 [self setEditing:(!editing_)];
7196 /* Changes Controller {{{ */
7197 @interface ChangesController : CYViewController <
7198 UITableViewDataSource,
7201 _transient Database *database_;
7203 CFMutableArrayRef packages_;
7204 NSMutableArray *sections_;
7207 BOOL hasSentFirstLoad_;
7210 - (id) initWithDatabase:(Database *)database;
7214 @implementation ChangesController
7217 [self releaseSubviews];
7218 CFRelease(packages_);
7219 [sections_ release];
7224 - (NSURL *) navigationURL {
7225 return [NSURL URLWithString:@"cydia://changes"];
7228 - (void) viewWillAppear:(BOOL)animated {
7229 // Loads after it appears, so don't load beforehand.
7231 [super viewWillAppear:animated];
7234 - (void) viewDidAppear:(BOOL)animated {
7235 [super viewDidAppear:animated];
7237 if (!hasSentFirstLoad_) {
7238 hasSentFirstLoad_ = YES;
7239 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7241 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7245 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7246 NSInteger count([sections_ count]);
7247 return count == 0 ? 1 : count;
7250 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7251 if ([sections_ count] == 0)
7253 return [[sections_ objectAtIndex:section] name];
7256 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7257 if ([sections_ count] == 0)
7259 return [[sections_ objectAtIndex:section] count];
7262 - (Package *) packageAtIndex:(NSUInteger)index {
7263 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7266 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7267 @synchronized (database_) {
7268 if ([database_ era] != era_)
7271 NSUInteger sectionIndex([path section]);
7272 if (sectionIndex >= [sections_ count])
7274 Section *section([sections_ objectAtIndex:sectionIndex]);
7275 NSInteger row([path row]);
7276 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7279 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7280 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7282 cell = [[[PackageCell alloc] init] autorelease];
7283 [cell setPackage:[self packageAtIndexPath:path]];
7287 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7288 Package *package([self packageAtIndexPath:path]);
7289 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7290 [view setDelegate:delegate_];
7291 [[self navigationController] pushViewController:view animated:YES];
7295 - (void) refreshButtonClicked {
7296 [delegate_ beginUpdate];
7297 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7300 - (void) upgradeButtonClicked {
7301 [delegate_ distUpgrade];
7305 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7307 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7308 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7309 [list_ setRowHeight:73];
7310 [list_ setDataSource:self];
7311 [list_ setDelegate:self];
7312 [[self view] addSubview:list_];
7315 - (void) viewDidLoad {
7316 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7319 - (void) releaseSubviews {
7324 - (id) initWithDatabase:(Database *)database {
7325 if ((self = [super init]) != nil) {
7326 database_ = database;
7328 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7329 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7333 // this mostly works because reloadData (below) is @synchronized (database_)
7334 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7335 - (void) _reloadPackages:(NSArray *)packages {
7336 CFRelease(packages_);
7337 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7340 _profile(ChangesController$_reloadPackages$Filter)
7341 for (Package *package in packages)
7342 if ([package upgradableAndEssential:YES] || [package visible])
7343 CFArrayAppendValue(packages_, package);
7346 _profile(ChangesController$_reloadPackages$radixSort)
7347 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7352 - (void) reloadData {
7353 @synchronized (database_) {
7354 era_ = [database_ era];
7355 NSArray *packages = [database_ packages];
7357 [sections_ removeAllObjects];
7360 UIProgressHUD *hud([delegate_ addProgressHUD]);
7361 [hud setText:UCLocalize("LOADING")];
7362 //NSLog(@"HUD:%@::%@", delegate_, hud);
7363 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7364 [delegate_ removeProgressHUD:hud];
7366 [self _reloadPackages:packages];
7369 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7370 Section *ignored = nil;
7371 Section *section = nil;
7375 bool unseens = false;
7377 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7379 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7380 Package *package = [self packageAtIndex:offset];
7382 BOOL uae = [package upgradableAndEssential:YES];
7386 time_t seen([package seen]);
7388 if (section == nil || last != seen) {
7392 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7395 _profile(ChangesController$reloadData$Allocate)
7396 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7397 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7398 [sections_ addObject:section];
7402 [section addToCount];
7403 } else if ([package ignored]) {
7404 if (ignored == nil) {
7405 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7407 [ignored addToCount];
7410 [upgradable addToCount];
7415 CFRelease(formatter);
7418 Section *last = [sections_ lastObject];
7419 size_t count = [last count];
7420 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7421 [sections_ removeLastObject];
7424 if ([ignored count] != 0)
7425 [sections_ insertObject:ignored atIndex:0];
7427 [sections_ insertObject:upgradable atIndex:0];
7432 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7433 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7434 style:UIBarButtonItemStylePlain
7436 action:@selector(upgradeButtonClicked)
7439 if (![delegate_ updating])
7440 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7441 initWithTitle:UCLocalize("REFRESH")
7442 style:UIBarButtonItemStylePlain
7444 action:@selector(refreshButtonClicked)
7452 /* Search Controller {{{ */
7453 @interface SearchController : FilteredPackageListController <
7456 UISearchBar *search_;
7460 - (id) initWithDatabase:(Database *)database;
7461 - (void) setSearchTerm:(NSString *)term;
7462 - (void) reloadData;
7466 @implementation SearchController
7473 - (NSURL *) navigationURL {
7474 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7475 return [NSURL URLWithString:@"cydia://search"];
7477 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7480 - (void) setSearchTerm:(NSString *)searchTerm {
7481 [search_ setText:searchTerm];
7485 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7486 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7487 [search_ resignFirstResponder];
7491 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7492 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7496 - (id) initWithDatabase:(Database *)database {
7497 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7498 search_ = [[UISearchBar alloc] init];
7502 - (void) viewDidAppear:(BOOL)animated {
7503 [super viewDidAppear:animated];
7505 if (!searchloaded_) {
7506 searchloaded_ = YES;
7507 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7508 [search_ layoutSubviews];
7509 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7511 UITextField *textField;
7512 if ([search_ respondsToSelector:@selector(searchField)])
7513 textField = [search_ searchField];
7515 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7517 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7518 [search_ setDelegate:self];
7519 [textField setEnablesReturnKeyAutomatically:NO];
7520 [[self navigationItem] setTitleView:textField];
7524 - (void) reloadData {
7525 [self setObject:[search_ text]];
7530 - (void) didSelectPackage:(Package *)package {
7531 [search_ resignFirstResponder];
7532 [super didSelectPackage:package];
7537 /* Package Settings Controller {{{ */
7538 @interface PackageSettingsController : CYViewController <
7539 UITableViewDataSource,
7542 _transient Database *database_;
7545 UITableView *table_;
7546 UISwitch *subscribedSwitch_;
7547 UISwitch *ignoredSwitch_;
7548 UITableViewCell *subscribedCell_;
7549 UITableViewCell *ignoredCell_;
7552 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7556 @implementation PackageSettingsController
7559 [self releaseSubviews];
7566 - (NSURL *) navigationURL {
7567 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7570 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7571 if (package_ == nil)
7574 if ([package_ installed] == nil)
7580 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7581 if (package_ == nil)
7584 // both sections contain just one item right now.
7588 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7592 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7594 return UCLocalize("SHOW_ALL_CHANGES_EX");
7596 return UCLocalize("IGNORE_UPGRADES_EX");
7599 - (void) onSubscribed:(id)control {
7600 bool value([control isOn]);
7601 if (package_ == nil)
7603 if ([package_ setSubscribed:value])
7604 [delegate_ updateData];
7607 - (void) _updateIgnored {
7608 const char *package([name_ UTF8String]);
7609 bool on([ignoredSwitch_ isOn]);
7611 pid_t pid(ExecFork());
7613 FILE *dpkg(popen("dpkg --set-selections", "w"));
7614 fwrite(package, strlen(package), 1, dpkg);
7617 fwrite(" hold\n", 6, 1, dpkg);
7619 fwrite(" install\n", 9, 1, dpkg);
7629 int result(waitpid(pid, &status, 0));
7632 _assert(result == pid);
7638 - (void) onIgnored:(id)control {
7639 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7640 [invocation setTarget:self];
7641 [invocation setSelector:@selector(_updateIgnored)];
7643 [delegate_ reloadDataWithInvocation:invocation];
7646 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7647 if (package_ == nil)
7650 switch ([indexPath section]) {
7651 case 0: return subscribedCell_;
7652 case 1: return ignoredCell_;
7661 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7663 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7664 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7665 [table_ setDataSource:self];
7666 [table_ setDelegate:self];
7667 [[self view] addSubview:table_];
7669 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7670 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7671 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7673 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7674 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7675 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7677 subscribedCell_ = [[UITableViewCell alloc] init];
7678 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7679 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7680 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7682 ignoredCell_ = [[UITableViewCell alloc] init];
7683 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7684 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7685 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7688 - (void) viewDidLoad {
7689 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7692 - (void) releaseSubviews {
7693 [ignoredCell_ release];
7696 [subscribedCell_ release];
7697 subscribedCell_ = nil;
7702 [ignoredSwitch_ release];
7703 ignoredSwitch_ = nil;
7705 [subscribedSwitch_ release];
7706 subscribedSwitch_ = nil;
7709 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7710 if ((self = [super init]) != nil) {
7711 database_ = database;
7712 name_ = [package retain];
7716 - (void) reloadData {
7719 if (package_ != nil)
7720 [package_ autorelease];
7721 package_ = [database_ packageWithName:name_];
7723 if (package_ != nil) {
7724 package_ = [package_ retain];
7725 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7726 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7727 } // XXX: what now, G?
7729 [table_ reloadData];
7735 /* Installed Controller {{{ */
7736 @interface InstalledController : FilteredPackageListController {
7740 - (id) initWithDatabase:(Database *)database;
7742 - (void) updateRoleButton;
7743 - (void) queueStatusDidChange;
7747 @implementation InstalledController
7753 - (NSURL *) navigationURL {
7754 return [NSURL URLWithString:@"cydia://installed"];
7757 - (id) initWithDatabase:(Database *)database {
7758 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7759 [self updateRoleButton];
7760 [self queueStatusDidChange];
7765 - (void) queueButtonClicked {
7770 - (void) queueStatusDidChange {
7774 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7775 initWithTitle:UCLocalize("QUEUE")
7776 style:UIBarButtonItemStyleDone
7778 action:@selector(queueButtonClicked)
7781 [[self navigationItem] setLeftBarButtonItem:nil];
7787 - (void) updateRoleButton {
7788 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7789 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7790 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7791 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7793 action:@selector(roleButtonClicked)
7797 - (void) roleButtonClicked {
7798 [self setObject:[NSNumber numberWithBool:expert_]];
7802 [self updateRoleButton];
7808 /* Source Cell {{{ */
7809 @interface SourceCell : CYTableViewCell <
7817 - (void) setSource:(Source *)source;
7821 @implementation SourceCell
7823 - (void) clearSource {
7833 - (void) setSource:(Source *)source {
7837 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7839 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7840 icon_ = [icon_ retain];
7842 origin_ = [[source name] retain];
7843 label_ = [[source uri] retain];
7845 [content_ setNeedsDisplay];
7853 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7854 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7855 UIView *content([self contentView]);
7856 CGRect bounds([content bounds]);
7858 content_ = [[ContentView alloc] initWithFrame:bounds];
7859 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7860 [content_ setBackgroundColor:[UIColor whiteColor]];
7861 [content addSubview:content_];
7863 [content_ setDelegate:self];
7864 [content_ setOpaque:YES];
7868 - (NSString *) accessibilityLabel {
7872 - (void) drawContentRect:(CGRect)rect {
7873 bool highlighted(highlighted_);
7874 float width(rect.size.width);
7877 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7884 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7888 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7893 /* Source Controller {{{ */
7894 @interface SourceController : FilteredPackageListController {
7895 _transient Source *source_;
7899 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7903 @implementation SourceController
7905 - (NSURL *) navigationURL {
7906 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7909 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7910 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7912 key_ = [[source key] retain];
7916 - (void) reloadData {
7917 source_ = [database_ sourceWithKey:key_];
7919 key_ = [[source_ key] retain];
7920 [self setObject:source_];
7921 [[self navigationItem] setTitle:[source_ label]];
7928 /* Sources Controller {{{ */
7929 @interface SourcesController : CYViewController <
7930 UITableViewDataSource,
7933 _transient Database *database_;
7935 NSMutableArray *sources_;
7939 UIProgressHUD *hud_;
7942 //NSURLConnection *installer_;
7943 NSURLConnection *trivial_;
7944 NSURLConnection *trivial_bz2_;
7945 NSURLConnection *trivial_gz_;
7946 //NSURLConnection *automatic_;
7951 - (id) initWithDatabase:(Database *)database;
7952 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7956 @implementation SourcesController
7958 - (void) _releaseConnection:(NSURLConnection *)connection {
7959 if (connection != nil) {
7960 [connection cancel];
7961 //[connection setDelegate:nil];
7962 [connection release];
7967 [self releaseSubviews];
7973 //[self _releaseConnection:installer_];
7974 [self _releaseConnection:trivial_];
7975 [self _releaseConnection:trivial_gz_];
7976 [self _releaseConnection:trivial_bz2_];
7977 //[self _releaseConnection:automatic_];
7983 - (NSURL *) navigationURL {
7984 return [NSURL URLWithString:@"cydia://sources"];
7987 - (void) viewDidAppear:(BOOL)animated {
7988 [super viewDidAppear:animated];
7989 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7992 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7993 return offset_ == 0 ? 1 : 2;
7996 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7997 switch (section + (offset_ == 0 ? 1 : 0)) {
7998 case 0: return UCLocalize("ENTERED_BY_USER");
7999 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8005 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8006 int count = [sources_ count];
8008 case 0: return (offset_ == 0 ? count : offset_);
8009 case 1: return count - offset_;
8015 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8017 switch (indexPath.section) {
8018 case 0: idx = indexPath.row; break;
8019 case 1: idx = indexPath.row + offset_; break;
8023 return [sources_ objectAtIndex:idx];
8026 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8027 static NSString *cellIdentifier = @"SourceCell";
8029 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8030 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8031 [cell setSource:[self sourceAtIndexPath:indexPath]];
8032 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8037 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8038 Source *source = [self sourceAtIndexPath:indexPath];
8040 SourceController *controller = [[[SourceController alloc]
8041 initWithDatabase:database_
8045 [controller setDelegate:delegate_];
8047 [[self navigationController] pushViewController:controller animated:YES];
8050 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8051 Source *source = [self sourceAtIndexPath:indexPath];
8052 return [source record] != nil;
8055 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8056 Source *source = [self sourceAtIndexPath:indexPath];
8057 [Sources_ removeObjectForKey:[source key]];
8058 [delegate_ syncData];
8062 [delegate_ addTrivialSource:href_];
8063 [delegate_ syncData];
8066 - (NSString *) getWarning {
8067 NSString *href(href_);
8068 NSRange colon([href rangeOfString:@"://"]);
8069 if (colon.location != NSNotFound)
8070 href = [href substringFromIndex:(colon.location + 3)];
8071 href = [href stringByAddingPercentEscapes];
8072 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8073 href = [href stringByCachingURLWithCurrentCDN];
8075 NSURL *url([NSURL URLWithString:href]);
8077 NSStringEncoding encoding;
8078 NSError *error(nil);
8080 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8081 return [warning length] == 0 ? nil : warning;
8085 - (void) _endConnection:(NSURLConnection *)connection {
8086 // XXX: the memory management in this method is horribly awkward
8088 NSURLConnection **field = NULL;
8089 if (connection == trivial_)
8091 else if (connection == trivial_bz2_)
8092 field = &trivial_bz2_;
8093 else if (connection == trivial_gz_)
8094 field = &trivial_gz_;
8095 _assert(field != NULL);
8096 [connection release];
8101 trivial_bz2_ == nil &&
8107 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8110 UIAlertView *alert = [[[UIAlertView alloc]
8111 initWithTitle:UCLocalize("SOURCE_WARNING")
8114 cancelButtonTitle:UCLocalize("CANCEL")
8116 UCLocalize("ADD_ANYWAY"),
8120 [alert setContext:@"warning"];
8121 [alert setNumberOfRows:1];
8125 } else if (error_ != nil) {
8126 UIAlertView *alert = [[[UIAlertView alloc]
8127 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8128 message:[error_ localizedDescription]
8130 cancelButtonTitle:UCLocalize("OK")
8131 otherButtonTitles:nil
8134 [alert setContext:@"urlerror"];
8137 UIAlertView *alert = [[[UIAlertView alloc]
8138 initWithTitle:UCLocalize("NOT_REPOSITORY")
8139 message:UCLocalize("NOT_REPOSITORY_EX")
8141 cancelButtonTitle:UCLocalize("OK")
8142 otherButtonTitles:nil
8145 [alert setContext:@"trivial"];
8149 [delegate_ setStatusBarShowsProgress:NO];
8150 [delegate_ removeProgressHUD:hud_];
8160 if (error_ != nil) {
8167 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8168 switch ([response statusCode]) {
8174 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8175 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8177 error_ = [error retain];
8178 [self _endConnection:connection];
8181 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8182 [self _endConnection:connection];
8185 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8186 NSMutableURLRequest *request = [NSMutableURLRequest
8187 requestWithURL:[NSURL URLWithString:href]
8188 cachePolicy:NSURLRequestUseProtocolCachePolicy
8189 timeoutInterval:120.0
8192 [request setHTTPMethod:method];
8194 if (Machine_ != NULL)
8195 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8196 if (UniqueID_ != nil)
8197 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8199 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8201 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8204 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8205 NSString *context([alert context]);
8207 if ([context isEqualToString:@"source"]) {
8210 NSString *href = [[alert textField] text];
8212 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8214 if (![href hasSuffix:@"/"])
8215 href_ = [href stringByAppendingString:@"/"];
8218 href_ = [href_ retain];
8220 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8221 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8222 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8223 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8227 // XXX: this is stupid
8228 hud_ = [[delegate_ addProgressHUD] retain];
8229 [hud_ setText:UCLocalize("VERIFYING_URL")];
8238 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8239 } else if ([context isEqualToString:@"trivial"])
8240 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8241 else if ([context isEqualToString:@"urlerror"])
8242 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8243 else if ([context isEqualToString:@"warning"]) {
8258 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8263 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8265 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8266 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8267 [list_ setRowHeight:56];
8268 [list_ setDataSource:self];
8269 [list_ setDelegate:self];
8270 [[self view] addSubview:list_];
8273 - (void) viewDidLoad {
8274 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8275 [self updateButtonsForEditingStatus:NO animated:NO];
8278 - (void) releaseSubviews {
8283 - (id) initWithDatabase:(Database *)database {
8284 if ((self = [super init]) != nil) {
8285 database_ = database;
8286 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8290 - (void) reloadData {
8294 if (!list.ReadMainList())
8297 [sources_ removeAllObjects];
8298 [sources_ addObjectsFromArray:[database_ sources]];
8300 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8303 int count([sources_ count]);
8305 for (int i = 0; i != count; i++) {
8306 if ([[sources_ objectAtIndex:i] record] == nil)
8311 [list_ setEditing:NO];
8312 [self updateButtonsForEditingStatus:NO animated:NO];
8316 - (void) showAddSourcePrompt {
8317 UIAlertView *alert = [[[UIAlertView alloc]
8318 initWithTitle:UCLocalize("ENTER_APT_URL")
8321 cancelButtonTitle:UCLocalize("CANCEL")
8323 UCLocalize("ADD_SOURCE"),
8327 [alert setContext:@"source"];
8328 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8330 [alert setNumberOfRows:1];
8331 [alert addTextFieldWithValue:@"http://" label:@""];
8333 UITextInputTraits *traits = [[alert textField] textInputTraits];
8334 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8335 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8336 [traits setKeyboardType:UIKeyboardTypeURL];
8337 // XXX: UIReturnKeyDone
8338 [traits setReturnKeyType:UIReturnKeyNext];
8343 - (void) addButtonClicked {
8344 [self showAddSourcePrompt];
8347 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8348 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8349 initWithTitle:UCLocalize("ADD")
8350 style:UIBarButtonItemStylePlain
8352 action:@selector(addButtonClicked)
8353 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8355 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8356 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8357 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8359 action:@selector(editButtonClicked)
8360 ] autorelease] animated:animated];
8362 if (IsWildcat_ && !editing)
8363 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8364 initWithTitle:UCLocalize("SETTINGS")
8365 style:UIBarButtonItemStylePlain
8367 action:@selector(settingsButtonClicked)
8371 - (void) settingsButtonClicked {
8372 [delegate_ showSettings];
8375 - (void) editButtonClicked {
8376 [list_ setEditing:![list_ isEditing] animated:YES];
8378 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8384 /* Settings Controller {{{ */
8385 @interface SettingsController : CYViewController <
8386 UITableViewDataSource,
8389 _transient Database *database_;
8390 // XXX: ok, "roledelegate_"?...
8391 _transient id roledelegate_;
8392 UITableView *table_;
8393 UISegmentedControl *segment_;
8397 - (void) showDoneButton;
8398 - (void) resizeSegmentedControl;
8402 @implementation SettingsController
8405 [self releaseSubviews];
8411 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8413 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8414 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8415 [table_ setDelegate:self];
8416 [table_ setDataSource:self];
8417 [[self view] addSubview:table_];
8419 NSArray *items = [NSArray arrayWithObjects:
8421 UCLocalize("HACKER"),
8422 UCLocalize("DEVELOPER"),
8424 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8425 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8426 [container_ addSubview:segment_];
8429 - (void) viewDidLoad {
8430 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8433 if ([Role_ isEqualToString:@"User"]) index = 0;
8434 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8435 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8437 [segment_ setSelectedSegmentIndex:index];
8438 [self showDoneButton];
8441 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8442 [self resizeSegmentedControl];
8445 - (void) releaseSubviews {
8452 [container_ release];
8456 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8457 if ((self = [super init]) != nil) {
8458 database_ = database;
8459 roledelegate_ = delegate;
8463 - (void) resizeSegmentedControl {
8464 CGFloat width = [[self view] frame].size.width;
8465 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8468 - (void) viewWillAppear:(BOOL)animated {
8469 [super viewWillAppear:animated];
8471 [self resizeSegmentedControl];
8474 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8475 [self resizeSegmentedControl];
8478 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8479 [self resizeSegmentedControl];
8483 NSString *role(nil);
8485 switch ([segment_ selectedSegmentIndex]) {
8486 case 0: role = @"User"; break;
8487 case 1: role = @"Hacker"; break;
8488 case 2: role = @"Developer"; break;
8493 if (![role isEqualToString:Role_]) {
8494 bool rolling(Role_ == nil);
8497 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8501 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8505 [roledelegate_ loadData];
8507 [roledelegate_ updateData];
8511 - (void) segmentChanged:(UISegmentedControl *)control {
8512 [self showDoneButton];
8515 - (void) saveAndClose {
8518 [[self navigationItem] setRightBarButtonItem:nil];
8519 [[self navigationController] dismissModalViewControllerAnimated:YES];
8522 - (void) doneButtonClicked {
8523 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8524 [spinner startAnimating];
8525 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8526 [[self navigationItem] setRightBarButtonItem:spinItem];
8528 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8531 - (void) showDoneButton {
8532 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8533 initWithTitle:UCLocalize("DONE")
8534 style:UIBarButtonItemStyleDone
8536 action:@selector(doneButtonClicked)
8537 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8540 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8541 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8545 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8549 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8550 return nil; // This method is required by the protocol.
8553 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8555 return UCLocalize("ROLE_EX");
8557 return [NSString stringWithFormat:
8558 @"%@: %@\n%@: %@\n%@: %@",
8559 UCLocalize("USER"), UCLocalize("USER_EX"),
8560 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8561 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8566 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8567 return section == 3 ? 44.0f : 0;
8570 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8571 return section == 3 ? container_ : nil;
8574 - (void) reloadData {
8576 [table_ reloadData];
8581 /* Stash Controller {{{ */
8582 @interface StashController : CYViewController {
8583 UIActivityIndicatorView *spinner_;
8590 @implementation StashController
8593 [self releaseSubviews];
8599 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8600 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8602 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8603 CGRect spinrect = [spinner_ frame];
8604 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8605 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8606 [spinner_ setFrame:spinrect];
8607 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8608 [[self view] addSubview:spinner_];
8609 [spinner_ startAnimating];
8612 captrect.size.width = [[self view] frame].size.width;
8613 captrect.size.height = 40.0f;
8614 captrect.origin.x = 0;
8615 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8616 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8617 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8618 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8619 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8620 [caption_ setTextColor:[UIColor whiteColor]];
8621 [caption_ setBackgroundColor:[UIColor clearColor]];
8622 [caption_ setShadowColor:[UIColor blackColor]];
8623 [caption_ setTextAlignment:UITextAlignmentCenter];
8624 [[self view] addSubview:caption_];
8627 statusrect.size.width = [[self view] frame].size.width;
8628 statusrect.size.height = 30.0f;
8629 statusrect.origin.x = 0;
8630 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8631 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8632 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8633 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8634 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8635 [status_ setTextColor:[UIColor whiteColor]];
8636 [status_ setBackgroundColor:[UIColor clearColor]];
8637 [status_ setShadowColor:[UIColor blackColor]];
8638 [status_ setTextAlignment:UITextAlignmentCenter];
8639 [[self view] addSubview:status_];
8642 - (void) releaseSubviews {
8656 @interface Cydia : UIApplication <
8657 ConfirmationControllerDelegate,
8658 ProgressControllerDelegate,
8660 UINavigationControllerDelegate,
8661 UITabBarControllerDelegate
8663 // XXX: evaluate all fields for _transient
8666 CYTabBarController *tabbar_;
8668 NSMutableArray *essential_;
8669 NSMutableArray *broken_;
8671 Database *database_;
8678 StashController *stash_;
8687 @implementation Cydia
8689 - (void) beginUpdate {
8690 [tabbar_ beginUpdate];
8694 return [tabbar_ updating];
8698 if ([broken_ count] != 0) {
8699 int count = [broken_ count];
8701 UIAlertView *alert = [[[UIAlertView alloc]
8702 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8703 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8705 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8707 UCLocalize("TEMPORARY_IGNORE"),
8711 [alert setContext:@"fixhalf"];
8713 } else if (!Ignored_ && [essential_ count] != 0) {
8714 int count = [essential_ count];
8716 UIAlertView *alert = [[[UIAlertView alloc]
8717 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8718 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8720 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8722 UCLocalize("UPGRADE_ESSENTIAL"),
8723 UCLocalize("COMPLETE_UPGRADE"),
8727 [alert setContext:@"upgrade"];
8732 - (void) _saveConfig {
8738 NSString *error(nil);
8740 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8742 NSError *error(nil);
8743 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8744 NSLog(@"failure to save metadata data: %@", error);
8749 NSLog(@"failure to serialize metadata: %@", error);
8754 // Navigation controller for the queuing badge.
8755 - (CYNavigationController *) queueNavigationController {
8756 NSArray *controllers = [tabbar_ viewControllers];
8757 return [controllers objectAtIndex:3];
8760 - (void) _updateData {
8763 [tabbar_ reloadData];
8765 CYNavigationController *navigation = [self queueNavigationController];
8767 id queuedelegate = nil;
8768 if ([[navigation viewControllers] count] > 0)
8769 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8771 [queuedelegate queueStatusDidChange];
8772 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8775 - (void) _refreshIfPossible:(NSDate *)update {
8776 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8778 bool recently = false;
8779 if (update != nil) {
8780 NSTimeInterval interval([update timeIntervalSinceNow]);
8781 if (interval <= 0 && interval > -(15*60))
8785 // Don't automatic refresh if:
8786 // - We already refreshed recently.
8787 // - We already auto-refreshed this launch.
8788 // - Auto-refresh is disabled.
8789 if (recently || loaded_ || ManualRefresh) {
8790 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8792 // If we are cancelling, we need to make sure it knows it's already loaded.
8796 // We are going to load, so remember that.
8800 SCNetworkReachabilityFlags flags; {
8801 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8802 SCNetworkReachabilityGetFlags(reachability, &flags);
8803 CFRelease(reachability);
8806 // XXX: this elaborate mess is what Apple is using to determine this? :(
8807 // XXX: do we care if the user has to intervene? maybe that's ok?
8809 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8810 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8811 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8812 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8813 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8814 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8818 // If we can reach the server, auto-refresh!
8820 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8825 - (void) refreshIfPossible {
8826 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8829 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8830 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8831 [hud setText:UCLocalize("RELOADING_DATA")];
8833 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8836 [self removeProgressHUD:hud];
8840 [essential_ removeAllObjects];
8841 [broken_ removeAllObjects];
8843 NSArray *packages([database_ packages]);
8844 for (Package *package in packages) {
8846 [broken_ addObject:package];
8847 if ([package upgradableAndEssential:NO]) {
8848 if ([package essential])
8849 [essential_ addObject:package];
8854 NSLog(@"changes:#%u", changes);
8856 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8859 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8860 [changesItem setBadgeValue:badge];
8861 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8862 [self setApplicationIconBadgeNumber:changes];
8865 [changesItem setBadgeValue:nil];
8866 [changesItem setAnimatedBadge:NO];
8867 [self setApplicationIconBadgeNumber:0];
8872 [self refreshIfPossible];
8875 - (void) updateData {
8886 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8887 _assert(file != NULL);
8889 for (NSString *key in [Sources_ allKeys]) {
8890 NSDictionary *source([Sources_ objectForKey:key]);
8892 fprintf(file, "%s %s %s\n",
8893 [[source objectForKey:@"Type"] UTF8String],
8894 [[source objectForKey:@"URI"] UTF8String],
8895 [[source objectForKey:@"Distribution"] UTF8String]
8901 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8902 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8904 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8905 [tabbar_ presentModalViewController:navigation animated:YES];
8908 detachNewThreadSelector:@selector(update_)
8911 title:UCLocalize("UPDATING_SOURCES")
8915 - (void) addTrivialSource:(NSString *)href {
8916 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8919 @"./", @"Distribution",
8920 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8925 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8926 @synchronized (self) {
8927 [self _reloadDataWithInvocation:invocation];
8931 - (void) reloadData {
8932 [self reloadDataWithInvocation:nil];
8936 pkgProblemResolver *resolver = [database_ resolver];
8938 resolver->InstallProtect();
8939 if (!resolver->Resolve(true))
8944 // XXX: this is a really crappy way of doing this.
8945 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8946 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8947 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8948 if ([tabbar_ updating])
8949 [tabbar_ cancelUpdate];
8951 if (![database_ prepare])
8954 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8955 [page setDelegate:self];
8956 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8957 [confirm_ setDelegate:self];
8960 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8961 [tabbar_ presentModalViewController:confirm_ animated:YES];
8967 @synchronized (self) {
8972 - (void) clearPackage:(Package *)package {
8973 @synchronized (self) {
8980 - (void) installPackages:(NSArray *)packages {
8981 @synchronized (self) {
8982 for (Package *package in packages)
8989 - (void) installPackage:(Package *)package {
8990 @synchronized (self) {
8997 - (void) removePackage:(Package *)package {
8998 @synchronized (self) {
9005 - (void) distUpgrade {
9006 @synchronized (self) {
9007 if (![database_ upgrade])
9014 @synchronized (self) {
9015 [self _reloadDataWithInvocation:nil];
9019 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9022 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
9024 if (navigation != nil) {
9025 [navigation pushViewController:progress animated:YES];
9027 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
9029 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9030 [tabbar_ presentModalViewController:navigation animated:YES];
9034 detachNewThreadSelector:@selector(perform)
9037 title:UCLocalize("RUNNING")
9043 - (void) progressControllerIsComplete:(ProgressController *)progress {
9048 - (void) showSettings {
9049 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9050 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9052 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9053 [tabbar_ presentModalViewController:nav animated:YES];
9056 - (void) retainNetworkActivityIndicator {
9057 if (activity_++ == 0)
9058 [self setNetworkActivityIndicatorVisible:YES];
9061 - (void) releaseNetworkActivityIndicator {
9062 if (--activity_ == 0)
9063 [self setNetworkActivityIndicatorVisible:NO];
9066 - (void) cancelAndClear:(bool)clear {
9067 @synchronized (self) {
9079 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9080 NSString *context([alert context]);
9082 if ([context isEqualToString:@"fixhalf"]) {
9083 if (button == [alert cancelButtonIndex]) {
9084 @synchronized (self) {
9085 for (Package *broken in broken_) {
9088 NSString *id = [broken id];
9089 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9090 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9091 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9092 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9098 } else if (button == [alert firstOtherButtonIndex]) {
9099 [broken_ removeAllObjects];
9103 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9104 } else if ([context isEqualToString:@"upgrade"]) {
9105 if (button == [alert firstOtherButtonIndex]) {
9106 @synchronized (self) {
9107 for (Package *essential in essential_)
9108 [essential install];
9113 } else if (button == [alert firstOtherButtonIndex] + 1) {
9115 } else if (button == [alert cancelButtonIndex]) {
9119 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9123 - (void) system:(NSString *)command { _pooled
9125 system([command UTF8String]);
9129 - (void) applicationWillSuspend {
9131 [super applicationWillSuspend];
9134 - (BOOL) isSafeToSuspend {
9135 // Use external process status API internally.
9136 // This is probably a really bad idea.
9137 // XXX: what is the point of this? does this solve anything at all?
9138 uint64_t status = 0;
9140 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9141 notify_get_state(notify_token, &status);
9142 notify_cancel(notify_token);
9145 return locked_ == 0 && status == 0;
9148 - (void) applicationSuspend:(__GSEvent *)event {
9149 if ([self isSafeToSuspend])
9150 [super applicationSuspend:event];
9153 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9154 if ([self isSafeToSuspend])
9155 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9158 - (void) _setSuspended:(BOOL)value {
9159 if ([self isSafeToSuspend])
9160 [super _setSuspended:value];
9163 - (UIProgressHUD *) addProgressHUD {
9164 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9165 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9167 [window_ setUserInteractionEnabled:NO];
9170 UIViewController *target = tabbar_;
9171 while ([target modalViewController] != nil) target = [target modalViewController];
9172 [[target view] addSubview:hud];
9178 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9180 [hud removeFromSuperview];
9181 [window_ setUserInteractionEnabled:YES];
9185 - (CYViewController *) pageForPackage:(NSString *)name {
9186 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9189 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9190 NSString *scheme([[url scheme] lowercaseString]);
9191 if ([[url absoluteString] length] <= [scheme length] + 3)
9193 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9194 NSArray *components([path pathComponents]);
9196 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9197 return [self pageForPackage:[components objectAtIndex:1]];
9199 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9202 NSString *base([components objectAtIndex:0]);
9204 CYViewController *controller = nil;
9206 if ([base isEqualToString:@"url"]) {
9207 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9208 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9209 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9210 } else if (!external && [components count] == 1) {
9211 if ([base isEqualToString:@"manage"]) {
9212 controller = [[[ManageController alloc] init] autorelease];
9215 if ([base isEqualToString:@"sources"]) {
9216 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9219 if ([base isEqualToString:@"home"]) {
9220 controller = [[[HomeController alloc] init] autorelease];
9223 if ([base isEqualToString:@"sections"]) {
9224 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9227 if ([base isEqualToString:@"search"]) {
9228 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9231 if ([base isEqualToString:@"changes"]) {
9232 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9235 if ([base isEqualToString:@"installed"]) {
9236 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9238 } else if ([components count] == 2) {
9239 NSString *argument = [components objectAtIndex:1];
9241 if ([base isEqualToString:@"package"]) {
9242 controller = [self pageForPackage:argument];
9245 if (!external && [base isEqualToString:@"search"]) {
9246 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9247 [(SearchController *)controller setSearchTerm:argument];
9250 if (!external && [base isEqualToString:@"sections"]) {
9251 if ([argument isEqualToString:@"all"])
9253 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9256 if (!external && [base isEqualToString:@"sources"]) {
9257 if ([argument isEqualToString:@"add"]) {
9258 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9259 [(SourcesController *)controller showAddSourcePrompt];
9261 Source *source = [database_ sourceWithKey:argument];
9262 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9266 if (!external && [base isEqualToString:@"launch"]) {
9267 [self launchApplicationWithIdentifier:argument suspended:NO];
9270 } else if (!external && [components count] == 3) {
9271 NSString *arg1 = [components objectAtIndex:1];
9272 NSString *arg2 = [components objectAtIndex:2];
9274 if ([base isEqualToString:@"package"]) {
9275 if ([arg2 isEqualToString:@"settings"]) {
9276 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9277 } else if ([arg2 isEqualToString:@"files"]) {
9278 if (Package *package = [database_ packageWithName:arg1]) {
9279 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9280 [(FileTable *)controller setPackage:package];
9286 [controller setDelegate:self];
9290 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9291 CYViewController *page([self pageForURL:url forExternal:external]);
9294 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9295 [nav setViewControllers:[NSArray arrayWithObject:page]];
9296 [tabbar_ setUnselectedViewController:nav];
9302 - (void) applicationOpenURL:(NSURL *)url {
9303 [super applicationOpenURL:url];
9305 if (!loaded_) starturl_ = [url retain];
9306 else [self openCydiaURL:url forExternal:YES];
9309 - (void) applicationWillResignActive:(UIApplication *)application {
9310 // Stop refreshing if you get a phone call or lock the device.
9311 if ([tabbar_ updating])
9312 [tabbar_ cancelUpdate];
9314 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9315 [super applicationWillResignActive:application];
9318 - (void) applicationWillTerminate:(UIApplication *)application {
9320 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9321 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9322 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9327 - (void) addStashController {
9329 stash_ = [[StashController alloc] init];
9330 [window_ addSubview:[stash_ view]];
9333 - (void) removeStashController {
9334 [[stash_ view] removeFromSuperview];
9340 [self setIdleTimerDisabled:YES];
9342 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9343 [self setStatusBarShowsProgress:YES];
9344 UpdateExternalStatus(1);
9346 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9348 UpdateExternalStatus(0);
9349 [self setStatusBarShowsProgress:NO];
9351 [self removeStashController];
9353 if (ExecFork() == 0) {
9354 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9355 perror("launchctl stop");
9359 - (void) setupViewControllers {
9360 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9362 NSMutableArray *items([NSMutableArray arrayWithObjects:
9363 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9364 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9365 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9366 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9370 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9371 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9373 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9376 NSMutableArray *controllers([NSMutableArray array]);
9377 for (UITabBarItem *item in items) {
9378 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9379 [controller setTabBarItem:item];
9380 [controllers addObject:controller];
9382 [tabbar_ setViewControllers:controllers];
9384 [tabbar_ setUpdateDelegate:self];
9387 - (CYEmulatedLoadingController *) showEmulatedLoadingControllerInView:(UIView *)view {
9388 static CYEmulatedLoadingController *fake = nil;
9392 fake = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9393 [view addSubview:[fake view]];
9395 [[fake view] removeFromSuperview];
9403 - (void) applicationDidFinishLaunching:(id)unused {
9407 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9408 [self setApplicationSupportsShakeToEdit:NO];
9410 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9411 initWithMemoryCapacity:524288
9412 diskCapacity:10485760
9413 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9416 [CYBrowserController _initialize];
9418 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9420 Font12_ = [[UIFont systemFontOfSize:12] retain];
9421 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9422 Font14_ = [[UIFont systemFontOfSize:14] retain];
9423 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9424 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9426 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9427 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9429 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9430 [window_ orderFront:self];
9431 [window_ makeKey:self];
9432 [window_ setHidden:NO];
9435 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9436 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9437 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9438 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9439 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9440 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9441 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9442 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9443 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9446 [self addStashController];
9447 // XXX: this would be much cleaner as a yieldToSelector:
9448 // that way the removeStashController could happen right here inline
9449 // we also could no longer require the useless stash_ field anymore
9450 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9454 database_ = [Database sharedInstance];
9456 [window_ setUserInteractionEnabled:NO];
9457 [self setupViewControllers];
9458 [self showEmulatedLoadingControllerInView:window_];
9460 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9467 [window_ setUserInteractionEnabled:YES];
9469 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9470 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9472 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9473 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9477 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9478 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9479 [window_ setUserInteractionEnabled:NO];
9485 [window_ addSubview:[tabbar_ view]];
9486 [self showEmulatedLoadingControllerInView:nil];
9487 [window_ setUserInteractionEnabled:YES];
9489 int selectedIndex = 0;
9490 NSMutableArray *items = nil;
9492 bool recently = false;
9493 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9494 if (closed != nil) {
9495 NSTimeInterval interval([closed timeIntervalSinceNow]);
9496 // XXX: Is 15 minutes the optimal time here?
9497 if (interval <= 0 && interval > -(15*60))
9501 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9502 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9505 for (NSArray *entry in items)
9506 if ([entry count] <= 0)
9509 if (!recently || !items || !enough) {
9511 items = [NSMutableArray array];
9512 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9513 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9514 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9516 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9518 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9519 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9521 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9524 [tabbar_ setSelectedIndex:selectedIndex];
9525 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9526 NSArray *stack = [items objectAtIndex:tab];
9527 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9528 NSMutableArray *current = [NSMutableArray array];
9530 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9531 NSString *addr = [stack objectAtIndex:nav];
9532 NSURL *url = [NSURL URLWithString:addr];
9533 CYViewController *page = [self pageForURL:url forExternal:NO];
9535 [current addObject:page];
9538 [navigation setViewControllers:current];
9541 // (Try to) show the startup URL.
9542 if (starturl_ != nil) {
9543 [self openCydiaURL:starturl_ forExternal:NO];
9544 [starturl_ release];
9549 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9550 if (item != nil && IsWildcat_) {
9551 [sheet showFromBarButtonItem:item animated:YES];
9553 [sheet showInView:window_];
9560 id Alloc_(id self, SEL selector) {
9561 id object = alloc_(self, selector);
9562 lprintf("[%s]A-%p\n", self->isa->name, object);
9567 id Dealloc_(id self, SEL selector) {
9568 id object = dealloc_(self, selector);
9569 lprintf("[%s]D-%p\n", self->isa->name, object);
9573 Class $WebDefaultUIKitDelegate;
9575 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9576 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9577 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9578 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9581 static NSNumber *shouldPlayKeyboardSounds;
9585 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9587 case 1104: // Keyboard Button Clicked
9588 case 1105: // Keyboard Delete Repeated
9589 if (shouldPlayKeyboardSounds == nil) {
9590 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9591 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9594 if (![shouldPlayKeyboardSounds boolValue])
9598 _UIHardware$_playSystemSound$(self, _cmd, sound);
9602 Class $UIApplication;
9604 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9605 static BOOL initialized = NO;
9606 static BOOL started = NO;
9608 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9609 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9611 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9612 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9613 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9614 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9616 if (initialized && !enabled) {
9618 [bundle performSelector:@selector(_accessibilityStopServer)];
9619 } else if (enabled) {
9623 [bundle performSelector:@selector(_accessibilityStartServer)];
9629 int main(int argc, char *argv[]) { _pooled
9632 UpdateExternalStatus(0);
9634 if (Class $UIDevice = objc_getClass("UIDevice")) {
9635 UIDevice *device([$UIDevice currentDevice]);
9636 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9640 UIScreen *screen([UIScreen mainScreen]);
9641 if ([screen respondsToSelector:@selector(scale)])
9642 ScreenScale_ = [screen scale];
9646 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9647 if (ScreenScale_ > 1)
9648 [parts addObject:@"@2x"];
9649 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9650 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9652 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9654 /* Library Hacks {{{ */
9655 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9657 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9658 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9659 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9660 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9661 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9664 $UIHardware = objc_getClass("UIHardware");
9665 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9666 if (UIHardware$_playSystemSound$ != NULL) {
9667 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9668 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9671 $UIApplication = objc_getClass("UIApplication");
9672 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9673 if (UIApplication$_updateApplicationAccessibility != NULL) {
9674 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9675 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9678 /* Set Locale {{{ */
9679 Locale_ = CFLocaleCopyCurrent();
9680 Languages_ = [NSLocale preferredLanguages];
9681 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9682 //NSLog(@"%@", [Languages_ description]);
9685 if (Languages_ == nil || [Languages_ count] == 0)
9686 // XXX: consider just setting to C and then falling through?
9689 lang = [[Languages_ objectAtIndex:0] UTF8String];
9690 setenv("LANG", lang, true);
9693 //std::setlocale(LC_ALL, lang);
9694 NSLog(@"Setting Language: %s", lang);
9697 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9699 /* Parse Arguments {{{ */
9700 bool substrate(false);
9706 for (int argi(1); argi != argc; ++argi)
9707 if (strcmp(argv[argi], "--") == 0) {
9709 argv[argi] = argv[0];
9715 for (int argi(1); argi != arge; ++argi)
9716 if (strcmp(args[argi], "--substrate") == 0)
9719 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9723 App_ = [[NSBundle mainBundle] bundlePath];
9724 Home_ = NSHomeDirectory();
9730 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9731 alloc_ = alloc->method_imp;
9732 alloc->method_imp = (IMP) &Alloc_;*/
9734 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9735 dealloc_ = dealloc->method_imp;
9736 dealloc->method_imp = (IMP) &Dealloc_;*/
9738 /* System Information {{{ */
9742 size = sizeof(maxproc);
9743 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9744 perror("sysctlbyname(\"kern.maxproc\", ?)");
9745 else if (maxproc < 64) {
9747 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9748 perror("sysctlbyname(\"kern.maxproc\", #)");
9751 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9752 char *osversion = new char[size];
9753 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9754 perror("sysctlbyname(\"kern.osversion\", ?)");
9756 System_ = [NSString stringWithUTF8String:osversion];
9758 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9759 char *machine = new char[size];
9760 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9761 perror("sysctlbyname(\"hw.machine\", ?)");
9765 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9766 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9767 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9768 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9772 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9773 NSData *data((NSData *) ecid);
9774 size_t length([data length]);
9775 uint8_t bytes[length];
9776 [data getBytes:bytes];
9777 char string[length * 2 + 1];
9778 for (size_t i(0); i != length; ++i)
9779 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9780 ChipID_ = [NSString stringWithUTF8String:string];
9784 IOObjectRelease(service);
9788 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9790 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9791 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9792 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9794 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9795 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9796 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9798 if (mcc != NULL && mnc != NULL)
9799 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9806 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9807 Build_ = [system objectForKey:@"ProductBuildVersion"];
9808 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9809 Product_ = [info objectForKey:@"SafariProductVersion"];
9810 Safari_ = [info objectForKey:@"CFBundleVersion"];
9813 /* Load Database {{{ */
9815 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9817 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9819 if (Metadata_ == NULL)
9820 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9822 Settings_ = [Metadata_ objectForKey:@"Settings"];
9824 Packages_ = [Metadata_ objectForKey:@"Packages"];
9825 Sections_ = [Metadata_ objectForKey:@"Sections"];
9826 Sources_ = [Metadata_ objectForKey:@"Sources"];
9828 Token_ = [Metadata_ objectForKey:@"Token"];
9831 if (Settings_ != nil)
9832 Role_ = [Settings_ objectForKey:@"Role"];
9834 if (Sections_ == nil) {
9835 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9836 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9839 if (Sources_ == nil) {
9840 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9841 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9846 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9849 if (Packages_ != nil) {
9851 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9855 [Metadata_ removeObjectForKey:@"Packages"];
9861 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9863 #define MobileSubstrate_(name) \
9864 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) \
9865 dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL);
9867 MobileSubstrate_(Activator)
9868 MobileSubstrate_(libstatusbar)
9869 MobileSubstrate_(SimulatedKeyEvents)
9870 MobileSubstrate_(WinterBoard)
9872 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9873 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9875 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9877 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9878 unlink("/tmp/.cydia.fw");
9880 } else if (access("/User", F_OK) != 0 || version < 2) {
9883 system("/usr/libexec/cydia/firmware.sh");
9887 _assert([[NSFileManager defaultManager]
9888 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9889 withIntermediateDirectories:YES
9894 if (access("/tmp/cydia.chk", F_OK) == 0) {
9895 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9896 _assert(errno == ENOENT);
9897 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9898 _assert(errno == ENOENT);
9901 /* APT Initialization {{{ */
9902 _assert(pkgInitConfig(*_config));
9903 _assert(pkgInitSystem(*_config, _system));
9906 _config->Set("APT::Acquire::Translation", lang);
9908 // XXX: this timeout might be important :(
9909 //_config->Set("Acquire::http::Timeout", 15);
9911 _config->Set("Acquire::http::MaxParallel", 3);
9913 /* Color Choices {{{ */
9914 space_ = CGColorSpaceCreateDeviceRGB();
9916 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9917 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9918 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9919 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9920 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9921 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9922 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9923 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9924 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9926 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9927 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9929 /* UIKit Configuration {{{ */
9930 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9931 if ($GSFontSetUseLegacyFontMetrics != NULL)
9932 $GSFontSetUseLegacyFontMetrics(YES);
9934 // XXX: I have a feeling this was important
9935 //UIKeyboardDisableAutomaticAppearance();
9938 Colon_ = UCLocalize("COLON_DELIMITED");
9939 Elision_ = UCLocalize("ELISION");
9940 Error_ = UCLocalize("ERROR");
9941 Warning_ = UCLocalize("WARNING");
9944 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9946 CGColorSpaceRelease(space_);