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 id<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() {
1251 /* Progress Delegation {{{ */
1256 _transient id<ProgressDelegate> delegate_;
1260 virtual void Update() {
1261 /*if (abs(Percent - percent_) > 2)
1262 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1266 //[delegate_ performSelectorOnMainThread:@selector(setProgressTitle:) withObject:[NSString stringWithUTF8String:Op.c_str()] waitUntilDone:YES];
1267 //[delegate_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(Percent / 100)] waitUntilDone:YES];
1277 void setDelegate(id delegate) {
1278 delegate_ = delegate;
1281 id getDelegate() const {
1285 virtual void Done() {
1287 //[delegate_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:1] waitUntilDone:YES];
1292 /* Database Interface {{{ */
1293 typedef std::map< unsigned long, _H<Source> > SourceMap;
1295 @interface Database : NSObject {
1301 pkgCacheFile cache_;
1302 pkgDepCache::Policy *policy_;
1303 pkgRecords *records_;
1304 pkgProblemResolver *resolver_;
1305 pkgAcquire *fetcher_;
1307 SPtr<pkgPackageManager> manager_;
1308 pkgSourceList *list_;
1310 SourceMap sourceMap_;
1311 NSMutableArray *sourceList_;
1313 CFMutableArrayRef packages_;
1315 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1323 std::map<const char *, _H<NSString> > sections_;
1326 + (Database *) sharedInstance;
1329 - (void) _readCydia:(NSNumber *)fd;
1330 - (void) _readStatus:(NSNumber *)fd;
1331 - (void) _readOutput:(NSNumber *)fd;
1335 - (Package *) packageWithName:(NSString *)name;
1337 - (pkgCacheFile &) cache;
1338 - (pkgDepCache::Policy *) policy;
1339 - (pkgRecords *) records;
1340 - (pkgProblemResolver *) resolver;
1341 - (pkgAcquire &) fetcher;
1342 - (pkgSourceList &) list;
1343 - (NSArray *) packages;
1344 - (NSArray *) sources;
1345 - (Source *) sourceWithKey:(NSString *)key;
1346 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1354 - (void) updateWithStatus:(Status &)status;
1356 - (void) setDelegate:(id)delegate;
1357 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1359 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1363 /* Delegate Helpers {{{ */
1364 @implementation NSObject (ProgressDelegate)
1366 - (void) _setProgressErrorPackage:(NSArray *)args {
1367 [self performSelector:@selector(setProgressError:forPackage:)
1368 withObject:[args objectAtIndex:0]
1369 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1373 - (void) _setProgressErrorTitle:(NSArray *)args {
1374 [self performSelector:@selector(setProgressError:withTitle:)
1375 withObject:[args objectAtIndex:0]
1376 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1380 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1381 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1382 withObject:[NSArray arrayWithObjects:error, title, nil]
1387 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1388 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1390 [self performSelector:@selector(setProgressError:withTitle:)
1392 withObject:(package == nil ? id : [package name])
1399 // Cytore Definitions {{{
1400 struct PackageValue :
1403 Cytore::Offset<PackageValue> next_;
1405 uint32_t index_ : 23;
1406 uint32_t subscribed_ : 1;
1423 Cytore::Offset<PackageValue> packages_[1 << 16];
1426 static Cytore::File<MetaValue> MetaFile_;
1428 // Cytore Helper Functions {{{
1429 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1430 SplitHash nhash = { hashlittle(name, length) };
1432 PackageValue *metadata;
1434 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1435 offset: if (offset->IsNull()) {
1436 *offset = MetaFile_.New<PackageValue>(length + 1);
1437 metadata = &MetaFile_.Get(*offset);
1439 if (metadata == NULL) {
1443 metadata = new PackageValue();
1444 memset(metadata, 0, sizeof(*metadata));
1447 memcpy(metadata->name_, name, length + 1);
1448 metadata->nhash_ = nhash.u16[1];
1450 metadata = &MetaFile_.Get(*offset);
1452 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1453 offset = &metadata->next_;
1461 static void PackageImport(const void *key, const void *value, void *context) {
1462 bool &fail(*reinterpret_cast<bool *>(context));
1465 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1466 NSLog(@"failed to import package %@", key);
1470 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1471 NSDictionary *package((NSDictionary *) value);
1473 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1474 if ([subscribed boolValue] && !metadata->subscribed_)
1475 metadata->subscribed_ = true;
1477 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1478 time_t time([date timeIntervalSince1970]);
1479 if (metadata->first_ > time || metadata->first_ == 0)
1480 metadata->first_ = time;
1483 NSDate *date([package objectForKey:@"LastSeen"]);
1484 NSString *version([package objectForKey:@"LastVersion"]);
1486 if (date != nil && version != nil) {
1487 time_t time([date timeIntervalSince1970]);
1488 if (metadata->last_ < time || metadata->last_ == 0)
1489 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1490 size_t length(strlen(buffer));
1491 uint16_t vhash(hashlittle(buffer, length));
1493 size_t capped(std::min<size_t>(8, length));
1494 char *latest(buffer + length - capped);
1496 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1497 metadata->vhash_ = vhash;
1499 metadata->last_ = time;
1505 /* Source Class {{{ */
1506 @interface Source : NSObject {
1507 CYString depiction_;
1508 CYString description_;
1514 CYString distribution_;
1519 NSString *authority_;
1521 CYString defaultIcon_;
1523 NSDictionary *record_;
1527 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1529 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1531 - (NSString *) depictionForPackage:(NSString *)package;
1532 - (NSString *) supportForPackage:(NSString *)package;
1534 - (NSDictionary *) record;
1538 - (NSString *) distribution;
1539 - (NSString *) type;
1541 - (NSString *) host;
1543 - (NSString *) name;
1544 - (NSString *) description;
1545 - (NSString *) label;
1546 - (NSString *) origin;
1547 - (NSString *) version;
1549 - (NSString *) defaultIcon;
1553 @implementation Source
1557 distribution_.clear();
1560 description_.clear();
1566 defaultIcon_.clear();
1568 if (record_ != nil) {
1578 if (authority_ != nil) {
1579 [authority_ release];
1585 // XXX: this is a very inefficient way to call these deconstructors
1590 + (NSArray *) _attributeKeys {
1591 return [NSArray arrayWithObjects:
1606 - (NSArray *) attributeKeys {
1607 return [[self class] _attributeKeys];
1610 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1611 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1614 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1617 trusted_ = index->IsTrusted();
1619 uri_.set(pool, index->GetURI());
1620 distribution_.set(pool, index->GetDist());
1621 type_.set(pool, index->GetType());
1623 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1624 if (dindex != NULL) {
1626 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1629 pkgTagFile tags(&fd);
1631 pkgTagSection section;
1638 {"default-icon", &defaultIcon_},
1639 {"depiction", &depiction_},
1640 {"description", &description_},
1642 {"origin", &origin_},
1643 {"support", &support_},
1644 {"version", &version_},
1647 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1648 const char *start, *end;
1650 if (section.Find(names[i].name_, start, end)) {
1651 CYString &value(*names[i].value_);
1652 value.set(pool, start, end - start);
1658 record_ = [Sources_ objectForKey:[self key]];
1660 record_ = [record_ retain];
1662 NSURL *url([NSURL URLWithString:uri_]);
1666 host_ = [[host_ lowercaseString] retain];
1671 authority_ = [url path];
1673 if (authority_ != nil)
1674 authority_ = [authority_ retain];
1677 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1678 if ((self = [super init]) != nil) {
1679 [self setMetaIndex:index inPool:pool];
1683 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1684 NSDictionary *lhr = [self record];
1685 NSDictionary *rhr = [source record];
1688 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1690 NSString *lhs = [self name];
1691 NSString *rhs = [source name];
1693 if ([lhs length] != 0 && [rhs length] != 0) {
1694 unichar lhc = [lhs characterAtIndex:0];
1695 unichar rhc = [rhs characterAtIndex:0];
1697 if (isalpha(lhc) && !isalpha(rhc))
1698 return NSOrderedAscending;
1699 else if (!isalpha(lhc) && isalpha(rhc))
1700 return NSOrderedDescending;
1703 return [lhs compare:rhs options:LaxCompareOptions_];
1706 - (NSString *) depictionForPackage:(NSString *)package {
1707 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1710 - (NSString *) supportForPackage:(NSString *)package {
1711 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1714 - (NSDictionary *) record {
1722 - (NSString *) uri {
1726 - (NSString *) distribution {
1727 return distribution_;
1730 - (NSString *) type {
1734 - (NSString *) key {
1735 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1738 - (NSString *) host {
1742 - (NSString *) name {
1743 return origin_.empty() ? authority_ : origin_;
1746 - (NSString *) description {
1747 return description_;
1750 - (NSString *) label {
1751 return label_.empty() ? authority_ : label_;
1754 - (NSString *) origin {
1758 - (NSString *) version {
1762 - (NSString *) defaultIcon {
1763 return defaultIcon_;
1768 /* CydiaOperation Class {{{ */
1769 @interface CydiaOperation : NSObject {
1770 NSString *operator_;
1774 - (NSString *) operator;
1775 - (NSString *) value;
1779 @implementation CydiaOperation
1782 [operator_ release];
1787 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1788 if ((self = [super init]) != nil) {
1789 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1790 value_ = [[NSString alloc] initWithUTF8String:value];
1794 + (NSArray *) _attributeKeys {
1795 return [NSArray arrayWithObjects:
1801 - (NSArray *) attributeKeys {
1802 return [[self class] _attributeKeys];
1805 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1806 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1809 - (NSString *) operator {
1813 - (NSString *) value {
1819 /* CydiaClause Class {{{ */
1820 @interface CydiaClause : NSObject {
1822 CydiaOperation *version_;
1825 - (NSString *) package;
1826 - (CydiaOperation *) version;
1830 @implementation CydiaClause
1838 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1839 if ((self = [super init]) != nil) {
1840 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1842 if (const char *version = dep.TargetVer())
1843 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1845 version_ = [[NSNull null] retain];
1849 + (NSArray *) _attributeKeys {
1850 return [NSArray arrayWithObjects:
1856 - (NSArray *) attributeKeys {
1857 return [[self class] _attributeKeys];
1860 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1861 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1864 - (NSString *) package {
1868 - (CydiaOperation *) version {
1874 /* CydiaRelation Class {{{ */
1875 @interface CydiaRelation : NSObject {
1876 NSString *relationship_;
1877 NSMutableArray *clauses_;
1880 - (NSString *) relationship;
1881 - (NSArray *) clauses;
1885 @implementation CydiaRelation
1888 [relationship_ release];
1893 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1894 if ((self = [super init]) != nil) {
1895 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1896 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1898 pkgCache::DepIterator start;
1899 pkgCache::DepIterator end;
1900 dep.GlobOr(start, end); // ++dep
1903 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1905 // yes, seriously. (wtf?)
1913 + (NSArray *) _attributeKeys {
1914 return [NSArray arrayWithObjects:
1920 - (NSArray *) attributeKeys {
1921 return [[self class] _attributeKeys];
1924 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1925 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1928 - (NSString *) relationship {
1929 return relationship_;
1932 - (NSArray *) clauses {
1936 - (void) addClause:(CydiaClause *)clause {
1937 [clauses_ addObject:clause];
1942 /* Package Class {{{ */
1943 struct ParsedPackage {
1948 CYString depiction_;
1958 @interface Package : NSObject {
1961 uint32_t essential_ : 1;
1962 uint32_t obsolete_ : 1;
1963 uint32_t ignored_ : 1;
1967 _transient Database *database_;
1969 pkgCache::VerIterator version_;
1970 pkgCache::PkgIterator iterator_;
1971 pkgCache::VerFileIterator file_;
1977 CYString installed_;
1979 const char *section_;
1980 _transient NSString *section$_;
1984 PackageValue *metadata_;
1985 ParsedPackage *parsed_;
1987 NSMutableArray *tags_;
1990 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1991 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1993 - (pkgCache::PkgIterator) iterator;
1996 - (NSString *) section;
1997 - (NSString *) simpleSection;
1999 - (NSString *) longSection;
2000 - (NSString *) shortSection;
2004 - (Address *) maintainer;
2006 - (NSString *) longDescription;
2007 - (NSString *) shortDescription;
2010 - (PackageValue *) metadata;
2013 - (bool) subscribed;
2014 - (bool) setSubscribed:(bool)subscribed;
2018 - (NSString *) latest;
2019 - (NSString *) installed;
2020 - (BOOL) uninstalled;
2023 - (BOOL) upgradableAndEssential:(BOOL)essential;
2026 - (BOOL) unfiltered;
2030 - (BOOL) halfConfigured;
2031 - (BOOL) halfInstalled;
2033 - (NSString *) mode;
2036 - (NSString *) name;
2038 - (NSString *) homepage;
2039 - (NSString *) depiction;
2040 - (Address *) author;
2042 - (NSString *) support;
2044 - (NSArray *) files;
2045 - (NSArray *) warnings;
2046 - (NSArray *) applications;
2048 - (Source *) source;
2050 - (BOOL) matches:(NSString *)text;
2052 - (bool) hasSupportingRole;
2053 - (BOOL) hasTag:(NSString *)tag;
2054 - (NSString *) primaryPurpose;
2055 - (NSArray *) purposes;
2056 - (bool) isCommercial;
2058 - (void) setIndex:(size_t)index;
2060 - (CYString &) cyname;
2062 - (uint32_t) compareBySection:(NSArray *)sections;
2067 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2068 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2069 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2070 - (bool) isVisibleInSection:(NSString *)section;
2071 - (bool) isVisibleInSource:(Source *)source;
2075 uint32_t PackageChangesRadix(Package *self, void *) {
2080 uint32_t timestamp : 30;
2081 uint32_t ignored : 1;
2082 uint32_t upgradable : 1;
2086 bool upgradable([self upgradableAndEssential:YES]);
2087 value.bits.upgradable = upgradable ? 1 : 0;
2090 value.bits.timestamp = 0;
2091 value.bits.ignored = [self ignored] ? 0 : 1;
2092 value.bits.upgradable = 1;
2094 value.bits.timestamp = [self seen] >> 2;
2095 value.bits.ignored = 0;
2096 value.bits.upgradable = 0;
2099 return _not(uint32_t) - value.key;
2102 uint32_t PackagePrefixRadix(Package *self, void *context) {
2103 size_t offset(reinterpret_cast<size_t>(context));
2104 CYString &name([self cyname]);
2106 size_t size(name.size());
2109 char *text(name.data());
2112 if (!isdigit(text[0]))
2116 while (size != digits && isdigit(text[digits]))
2124 if (offset == 0 && zeros != 0) {
2125 memset(data, '0', zeros);
2126 memcpy(data + zeros, text, 4 - zeros);
2128 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2129 if (size <= offset - zeros)
2132 text += offset - zeros;
2133 size -= offset - zeros;
2136 memcpy(data, text, 4);
2138 memcpy(data, text, size);
2139 memset(data + size, 0, 4 - size);
2142 for (size_t i(0); i != 4; ++i)
2143 if (isalpha(data[i]))
2151 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2153 /* XXX: ntohl may be more honest */
2154 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2157 CYString &(*PackageName)(Package *self, SEL sel);
2159 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2160 _profile(PackageNameCompare)
2161 CYString &lhi(PackageName(lhs, @selector(cyname)));
2162 CYString &rhi(PackageName(rhs, @selector(cyname)));
2163 CFStringRef lhn(lhi), rhn(rhi);
2166 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2167 else if (rhn == NULL)
2168 return NSOrderedDescending;
2170 _profile(PackageNameCompare$NumbersLast)
2171 if (!lhi.empty() && !rhi.empty()) {
2172 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2173 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2174 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2175 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2176 return lha ? NSOrderedAscending : NSOrderedDescending;
2180 CFIndex length = CFStringGetLength(lhn);
2182 _profile(PackageNameCompare$Compare)
2183 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2188 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2189 return PackageNameCompare(*lhs, *rhs, context);
2192 struct PackageNameOrdering :
2193 std::binary_function<Package *, Package *, bool>
2195 _finline bool operator ()(Package *lhs, Package *rhs) const {
2196 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2200 @implementation Package
2202 - (NSString *) description {
2203 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2207 if (parsed_ != NULL)
2216 + (NSString *) webScriptNameForSelector:(SEL)selector {
2218 else if (selector == @selector(clear))
2220 else if (selector == @selector(hasTag:))
2222 else if (selector == @selector(install))
2224 else if (selector == @selector(remove))
2230 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2231 return [self webScriptNameForSelector:selector] == nil;
2234 + (NSArray *) _attributeKeys {
2235 return [NSArray arrayWithObjects:
2253 @"shortDescription",
2264 - (NSArray *) attributeKeys {
2265 return [[self class] _attributeKeys];
2268 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2269 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2272 - (NSArray *) relations {
2273 @synchronized (database_) {
2274 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2275 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2276 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2281 if (parsed_ != NULL)
2283 @synchronized (database_) {
2284 if ([database_ era] != era_ || file_.end())
2287 ParsedPackage *parsed(new ParsedPackage);
2290 _profile(Package$parse)
2291 pkgRecords::Parser *parser;
2293 _profile(Package$parse$Lookup)
2294 parser = &[database_ records]->Lookup(file_);
2299 _profile(Package$parse$Find)
2304 {"icon", &parsed->icon_},
2305 {"depiction", &parsed->depiction_},
2306 {"homepage", &parsed->homepage_},
2307 {"website", &website},
2308 {"bugs", &parsed->bugs_},
2309 {"support", &parsed->support_},
2310 {"sponsor", &parsed->sponsor_},
2311 {"author", &parsed->author_},
2314 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2315 const char *start, *end;
2317 if (parser->Find(names[i].name_, start, end)) {
2318 CYString &value(*names[i].value_);
2319 _profile(Package$parse$Value)
2320 value.set(pool_, start, end - start);
2326 _profile(Package$parse$Tagline)
2327 const char *start, *end;
2328 if (parser->ShortDesc(start, end)) {
2329 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2332 while (stop != start && stop[-1] == '\r')
2334 parsed->tagline_.set(pool_, start, stop - start);
2338 _profile(Package$parse$Retain)
2339 if (parsed->homepage_.empty())
2340 parsed->homepage_ = website;
2341 if (parsed->homepage_ == parsed->depiction_)
2342 parsed->homepage_.clear();
2347 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2348 if ((self = [super init]) != nil) {
2349 _profile(Package$initWithVersion)
2352 database_ = database;
2353 era_ = [database era];
2357 pkgCache::PkgIterator iterator(version.ParentPkg());
2358 iterator_ = iterator;
2360 _profile(Package$initWithVersion$Version)
2361 if (!version_.end())
2362 file_ = version_.FileList();
2364 pkgCache &cache([database_ cache]);
2365 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2369 _profile(Package$initWithVersion$Cache)
2370 name_.set(NULL, iterator.Display());
2372 latest_.set(NULL, StripVersion_(version_.VerStr()));
2374 pkgCache::VerIterator current(iterator.CurrentVer());
2376 installed_.set(NULL, StripVersion_(current.VerStr()));
2379 _profile(Package$initWithVersion$Tags)
2380 pkgCache::TagIterator tag(iterator.TagList());
2382 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2384 const char *name(tag.Name());
2385 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2387 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2388 if (strcmp(name + 6, "enduser") == 0)
2390 else if (strcmp(name + 6, "hacker") == 0)
2392 else if (strcmp(name + 6, "developer") == 0)
2394 else if (strcmp(name + 6, "cydia") == 0)
2400 if (strncmp(name, "cydia::", 7) == 0) {
2401 if (strcmp(name + 7, "essential") == 0)
2403 else if (strcmp(name + 7, "obsolete") == 0)
2408 } while (!tag.end());
2412 _profile(Package$initWithVersion$Metadata)
2413 const char *mixed(iterator.Name());
2414 size_t size(strlen(mixed));
2415 char lower[size + 1];
2417 for (size_t i(0); i != size; ++i)
2418 lower[i] = mixed[i] | 0x20;
2421 PackageValue *metadata(PackageFind(lower, size));
2422 metadata_ = metadata;
2424 id_.set(NULL, metadata->name_, size);
2426 const char *latest(version_.VerStr());
2427 size_t length(strlen(latest));
2429 uint16_t vhash(hashlittle(latest, length));
2431 size_t capped(std::min<size_t>(8, length));
2432 latest = latest + length - capped;
2434 if (metadata->first_ == 0)
2435 metadata->first_ = now_;
2437 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2438 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2439 metadata->vhash_ = vhash;
2440 metadata->last_ = now_;
2441 } else if (metadata->last_ == 0)
2442 metadata->last_ = metadata->first_;
2445 _profile(Package$initWithVersion$Section)
2446 section_ = iterator.Section();
2449 _profile(Package$initWithVersion$Flags)
2450 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2451 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2456 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2457 pkgCache::VerIterator version;
2459 _profile(Package$packageWithIterator$GetCandidateVer)
2460 version = [database policy]->GetCandidateVer(iterator);
2468 _profile(Package$packageWithIterator$Allocate)
2469 package = [Package allocWithZone:zone];
2472 _profile(Package$packageWithIterator$Initialize)
2474 initWithVersion:version
2481 _profile(Package$packageWithIterator$Autorelease)
2482 package = [package autorelease];
2488 - (pkgCache::PkgIterator) iterator {
2492 - (NSString *) section {
2493 if (section$_ == nil) {
2494 if (section_ == NULL)
2497 _profile(Package$section$mappedSectionForPointer)
2498 section$_ = [database_ mappedSectionForPointer:section_];
2503 - (NSString *) simpleSection {
2504 if (NSString *section = [self section])
2505 return Simplify(section);
2510 - (NSString *) longSection {
2511 return LocalizeSection([self section]);
2514 - (NSString *) shortSection {
2515 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2518 - (NSString *) uri {
2521 pkgIndexFile *index;
2522 pkgCache::PkgFileIterator file(file_.File());
2523 if (![database_ list].FindIndex(file, index))
2525 return [NSString stringWithUTF8String:iterator_->Path];
2526 //return [NSString stringWithUTF8String:file.Site()];
2527 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2531 - (Address *) maintainer {
2532 @synchronized (database_) {
2533 if ([database_ era] != era_ || file_.end())
2536 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2537 const std::string &maintainer(parser->Maintainer());
2538 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2542 @synchronized (database_) {
2543 if ([database_ era] != era_ || version_.end())
2546 return version_->InstalledSize;
2549 - (NSString *) longDescription {
2550 @synchronized (database_) {
2551 if ([database_ era] != era_ || file_.end())
2554 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2555 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2557 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2558 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2559 if ([lines count] < 2)
2562 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2563 for (size_t i(1), e([lines count]); i != e; ++i) {
2564 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2565 [trimmed addObject:trim];
2568 return [trimmed componentsJoinedByString:@"\n"];
2571 - (NSString *) shortDescription {
2572 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2576 _profile(Package$index)
2577 CFStringRef name((CFStringRef) [self name]);
2578 if (CFStringGetLength(name) == 0)
2580 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2581 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2583 return toupper(character);
2587 - (PackageValue *) metadata {
2592 PackageValue *metadata([self metadata]);
2593 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2596 - (bool) subscribed {
2597 return [self metadata]->subscribed_;
2600 - (bool) setSubscribed:(bool)subscribed {
2601 PackageValue *metadata([self metadata]);
2602 if (metadata->subscribed_ == subscribed)
2604 metadata->subscribed_ = subscribed;
2612 - (NSString *) latest {
2616 - (NSString *) installed {
2620 - (BOOL) uninstalled {
2621 return installed_.empty();
2625 return !version_.end();
2628 - (BOOL) upgradableAndEssential:(BOOL)essential {
2629 _profile(Package$upgradableAndEssential)
2630 pkgCache::VerIterator current(iterator_.CurrentVer());
2632 return essential && essential_;
2634 return !version_.end() && version_ != current;
2638 - (BOOL) essential {
2643 return [database_ cache][iterator_].InstBroken();
2646 - (BOOL) unfiltered {
2647 _profile(Package$unfiltered$obsolete)
2648 if (_unlikely(obsolete_))
2652 _profile(Package$unfiltered$hasSupportingRole)
2653 if (_unlikely(![self hasSupportingRole]))
2661 if (![self unfiltered])
2666 _profile(Package$visible$section)
2667 section = [self section];
2670 _profile(Package$visible$isSectionVisible)
2671 if (!isSectionVisible(section))
2679 unsigned char current(iterator_->CurrentState);
2680 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2683 - (BOOL) halfConfigured {
2684 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2687 - (BOOL) halfInstalled {
2688 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2692 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2693 return state.Mode != pkgDepCache::ModeKeep;
2696 - (NSString *) mode {
2697 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2699 switch (state.Mode) {
2700 case pkgDepCache::ModeDelete:
2701 if ((state.iFlags & pkgDepCache::Purge) != 0)
2705 case pkgDepCache::ModeKeep:
2706 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2707 return @"REINSTALL";
2708 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2712 case pkgDepCache::ModeInstall:
2713 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2714 return @"REINSTALL";
2715 else*/ switch (state.Status) {
2717 return @"DOWNGRADE";
2723 return @"NEW_INSTALL";
2734 - (NSString *) name {
2735 return name_.empty() ? id_ : name_;
2738 - (UIImage *) icon {
2739 NSString *section = [self simpleSection];
2742 if (parsed_ != NULL)
2743 if (NSString *href = parsed_->icon_)
2744 if ([href hasPrefix:@"file:///"])
2745 // XXX: correct escaping
2746 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2747 if (icon == nil) if (section != nil)
2748 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2749 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2750 if ([dicon hasPrefix:@"file:///"])
2751 // XXX: correct escaping
2752 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2754 icon = [UIImage applicationImageNamed:@"unknown.png"];
2758 - (NSString *) homepage {
2759 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2762 - (NSString *) depiction {
2763 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2766 - (Address *) sponsor {
2767 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2770 - (Address *) author {
2771 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2774 - (NSString *) support {
2775 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2778 - (NSArray *) files {
2779 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2780 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2783 fin.open([path UTF8String]);
2788 while (std::getline(fin, line))
2789 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2794 - (NSArray *) warnings {
2795 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2796 const char *name(iterator_.Name());
2798 size_t length(strlen(name));
2799 if (length < 2) invalid:
2800 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2801 else for (size_t i(0); i != length; ++i)
2803 /* XXX: technically this is not allowed */
2804 (name[i] < 'A' || name[i] > 'Z') &&
2805 (name[i] < 'a' || name[i] > 'z') &&
2806 (name[i] < '0' || name[i] > '9') &&
2807 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2810 if (strcmp(name, "cydia") != 0) {
2813 bool _private = false;
2816 bool repository = [[self section] isEqualToString:@"Repositories"];
2818 if (NSArray *files = [self files])
2819 for (NSString *file in files)
2820 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2822 else if (!user && [file isEqualToString:@"/User"])
2824 else if (!_private && [file isEqualToString:@"/private"])
2826 else if (!stash && [file isEqualToString:@"/var/stash"])
2829 /* XXX: this is not sensitive enough. only some folders are valid. */
2830 if (cydia && !repository)
2831 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2833 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2835 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2837 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2840 return [warnings count] == 0 ? nil : warnings;
2843 - (NSArray *) applications {
2844 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2846 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2848 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2849 if (NSArray *files = [self files])
2850 for (NSString *file in files)
2851 if (application_r(file)) {
2852 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2853 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2854 if ([id isEqualToString:me])
2857 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2859 display = application_r[1];
2861 NSString *bundle([file stringByDeletingLastPathComponent]);
2862 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2863 if (icon == nil || [icon length] == 0)
2865 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2867 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2868 [applications addObject:application];
2870 [application addObject:id];
2871 [application addObject:display];
2872 [application addObject:url];
2875 return [applications count] == 0 ? nil : applications;
2878 - (Source *) source {
2879 if (source_ == nil) {
2880 @synchronized (database_) {
2881 if ([database_ era] != era_ || file_.end())
2882 source_ = (Source *) [NSNull null];
2884 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2888 return source_ == (Source *) [NSNull null] ? nil : source_;
2891 - (BOOL) matches:(NSString *)text {
2897 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2898 if (range.location != NSNotFound)
2901 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2902 if (range.location != NSNotFound)
2907 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2908 if (range.location != NSNotFound)
2914 - (bool) hasSupportingRole {
2919 if ([Role_ isEqualToString:@"User"])
2923 if ([Role_ isEqualToString:@"Hacker"])
2927 if ([Role_ isEqualToString:@"Developer"])
2932 - (BOOL) hasTag:(NSString *)tag {
2933 return tags_ == nil ? NO : [tags_ containsObject:tag];
2936 - (NSString *) primaryPurpose {
2937 for (NSString *tag in tags_)
2938 if ([tag hasPrefix:@"purpose::"])
2939 return [tag substringFromIndex:9];
2943 - (NSArray *) purposes {
2944 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2945 for (NSString *tag in tags_)
2946 if ([tag hasPrefix:@"purpose::"])
2947 [purposes addObject:[tag substringFromIndex:9]];
2948 return [purposes count] == 0 ? nil : purposes;
2951 - (bool) isCommercial {
2952 return [self hasTag:@"cydia::commercial"];
2955 - (void) setIndex:(size_t)index {
2956 if (metadata_->index_ != index)
2957 metadata_->index_ = index;
2960 - (CYString &) cyname {
2961 return name_.empty() ? id_ : name_;
2964 - (uint32_t) compareBySection:(NSArray *)sections {
2965 NSString *section([self section]);
2966 for (size_t i(0), e([sections count]); i != e; ++i) {
2967 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2971 return _not(uint32_t);
2975 @synchronized (database_) {
2976 pkgProblemResolver *resolver = [database_ resolver];
2977 resolver->Clear(iterator_);
2979 pkgCacheFile &cache([database_ cache]);
2980 cache->SetReInstall(iterator_, false);
2981 cache->MarkKeep(iterator_, false);
2985 @synchronized (database_) {
2986 pkgProblemResolver *resolver = [database_ resolver];
2987 resolver->Clear(iterator_);
2988 resolver->Protect(iterator_);
2990 pkgCacheFile &cache([database_ cache]);
2991 cache->SetReInstall(iterator_, false);
2992 cache->MarkInstall(iterator_, false);
2994 pkgDepCache::StateCache &state((*cache)[iterator_]);
2995 if (!state.Install())
2996 cache->SetReInstall(iterator_, true);
3000 @synchronized (database_) {
3001 pkgProblemResolver *resolver = [database_ resolver];
3002 resolver->Clear(iterator_);
3003 resolver->Remove(iterator_);
3004 resolver->Protect(iterator_);
3006 pkgCacheFile &cache([database_ cache]);
3007 cache->SetReInstall(iterator_, false);
3008 cache->MarkDelete(iterator_, true);
3011 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3012 _profile(Package$isUnfilteredAndSearchedForBy)
3015 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3016 value &= [self unfiltered];
3019 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3020 value &= [self matches:search];
3027 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3028 if ([search length] == 0)
3031 _profile(Package$isUnfilteredAndSelectedForBy)
3034 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3035 value &= [self unfiltered];
3038 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3039 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3046 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3047 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3050 - (bool) isVisibleInSection:(NSString *)name {
3051 NSString *section([self section]);
3055 section == nil && [name length] == 0 ||
3056 [name isEqualToString:section]
3057 ) && [self visible];
3060 - (bool) isVisibleInSource:(Source *)source {
3061 return [self source] == source && [self visible];
3066 /* Section Class {{{ */
3067 @interface Section : NSObject {
3072 NSString *localized_;
3075 - (NSComparisonResult) compareByLocalized:(Section *)section;
3076 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3077 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3078 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3079 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3080 - (NSString *) name;
3087 - (void) addToCount;
3089 - (void) setCount:(size_t)count;
3090 - (NSString *) localized;
3094 @implementation Section
3098 if (localized_ != nil)
3099 [localized_ release];
3103 - (NSComparisonResult) compareByLocalized:(Section *)section {
3104 NSString *lhs(localized_);
3105 NSString *rhs([section localized]);
3107 /*if ([lhs length] != 0 && [rhs length] != 0) {
3108 unichar lhc = [lhs characterAtIndex:0];
3109 unichar rhc = [rhs characterAtIndex:0];
3111 if (isalpha(lhc) && !isalpha(rhc))
3112 return NSOrderedAscending;
3113 else if (!isalpha(lhc) && isalpha(rhc))
3114 return NSOrderedDescending;
3117 return [lhs compare:rhs options:LaxCompareOptions_];
3120 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3121 if ((self = [self initWithName:name localize:NO]) != nil) {
3122 if (localized != nil)
3123 localized_ = [localized retain];
3127 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3128 return [self initWithName:name row:0 localize:localize];
3131 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3132 if ((self = [super init]) != nil) {
3133 name_ = [name retain];
3137 localized_ = [LocalizeSection(name_) retain];
3141 /* XXX: localize the index thingees */
3142 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3143 if ((self = [super init]) != nil) {
3144 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3150 - (NSString *) name {
3170 - (void) addToCount {
3174 - (void) setCount:(size_t)count {
3178 - (NSString *) localized {
3185 static NSString *Colon_;
3186 static NSString *Elision_;
3187 static NSString *Error_;
3188 static NSString *Warning_;
3190 /* Database Implementation {{{ */
3191 @implementation Database
3193 + (Database *) sharedInstance {
3194 static Database *instance;
3195 if (instance == nil)
3196 instance = [[Database alloc] init];
3204 - (void) releasePackages {
3205 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3206 CFArrayRemoveAllValues(packages_);
3210 // XXX: actually implement this thing
3212 [sourceList_ release];
3213 [self releasePackages];
3214 apr_pool_destroy(pool_);
3215 NSRecycleZone(zone_);
3219 - (void) _readCydia:(NSNumber *)fd { _pooled
3220 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3221 std::istream is(&ib);
3224 static Pcre finish_r("^finish:([^:]*)$");
3226 while (std::getline(is, line)) {
3227 const char *data(line.c_str());
3228 size_t size = line.size();
3229 lprintf("C:%s\n", data);
3231 if (finish_r(data, size)) {
3232 NSString *finish = finish_r[1];
3233 int index = [Finishes_ indexOfObject:finish];
3234 if (index != INT_MAX && index > Finish_)
3242 - (void) _readStatus:(NSNumber *)fd { _pooled
3243 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3244 std::istream is(&ib);
3247 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3248 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3250 while (std::getline(is, line)) {
3251 const char *data(line.c_str());
3252 size_t size(line.size());
3253 lprintf("S:%s\n", data);
3255 if (conffile_r(data, size))
3256 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3257 else if (strncmp(data, "status: ", 8) == 0)
3258 [delegate_ performSelectorOnMainThread:@selector(setProgressTitle:) withObject:[NSString stringWithUTF8String:(data + 8)] waitUntilDone:YES];
3259 else if (pmstatus_r(data, size)) {
3260 std::string type([pmstatus_r[1] UTF8String]);
3261 NSString *id = pmstatus_r[2];
3263 float percent([pmstatus_r[3] floatValue]);
3264 [delegate_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3266 NSString *string = pmstatus_r[4];
3268 if (type == "pmerror")
3269 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3270 withObject:[NSArray arrayWithObjects:string, id, nil]
3273 else if (type == "pmstatus")
3274 [delegate_ performSelectorOnMainThread:@selector(setProgressTitle:) withObject:string waitUntilDone:YES];
3275 else if (type == "pmconffile")
3276 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3278 lprintf("E:unknown pmstatus\n");
3280 lprintf("E:unknown status\n");
3286 - (void) _readOutput:(NSNumber *)fd { _pooled
3287 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3288 std::istream is(&ib);
3291 while (std::getline(is, line)) {
3292 lprintf("O:%s\n", line.c_str());
3294 [delegate_ performSelectorOnMainThread:@selector(addProgressOutput:) withObject:[NSString stringWithUTF8String:line.c_str()] waitUntilDone:YES];
3304 - (Package *) packageWithName:(NSString *)name {
3305 @synchronized (self) {
3306 if (static_cast<pkgDepCache *>(cache_) == NULL)
3308 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3309 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3313 if ((self = [super init]) != nil) {
3320 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3321 apr_pool_create(&pool_, NULL);
3323 size_t capacity(MetaFile_->active_);
3329 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3330 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3334 _assert(pipe(fds) != -1);
3337 _config->Set("APT::Keep-Fds::", cydiafd_);
3338 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3341 detachNewThreadSelector:@selector(_readCydia:)
3343 withObject:[NSNumber numberWithInt:fds[0]]
3346 _assert(pipe(fds) != -1);
3350 detachNewThreadSelector:@selector(_readStatus:)
3352 withObject:[NSNumber numberWithInt:fds[0]]
3355 _assert(pipe(fds) != -1);
3356 _assert(dup2(fds[0], 0) != -1);
3357 _assert(close(fds[0]) != -1);
3359 input_ = fdopen(fds[1], "a");
3361 _assert(pipe(fds) != -1);
3362 _assert(dup2(fds[1], 1) != -1);
3363 _assert(close(fds[1]) != -1);
3366 detachNewThreadSelector:@selector(_readOutput:)
3368 withObject:[NSNumber numberWithInt:fds[0]]
3373 - (pkgCacheFile &) cache {
3377 - (pkgDepCache::Policy *) policy {
3381 - (pkgRecords *) records {
3385 - (pkgProblemResolver *) resolver {
3389 - (pkgAcquire &) fetcher {
3393 - (pkgSourceList &) list {
3397 - (NSArray *) packages {
3398 return (NSArray *) packages_;
3401 - (NSArray *) sources {
3405 - (Source *) sourceWithKey:(NSString *)key {
3406 for (Source *source in [self sources]) {
3407 if ([[source key] isEqualToString:key])
3412 - (bool) popErrorWithTitle:(NSString *)title {
3414 std::string message;
3416 while (!_error->empty()) {
3418 bool warning(!_error->PopMessage(error));
3422 size_t size(error.size());
3423 if (size == 0 || error[size - 1] != '\n')
3425 error.resize(size - 1);
3427 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3429 if (!message.empty())
3434 if (fatal && !message.empty())
3435 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3440 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3441 return [self popErrorWithTitle:title] || !success;
3444 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3445 @synchronized (self) {
3448 [self releasePackages];
3451 [sourceList_ removeAllObjects];
3471 apr_pool_clear(pool_);
3473 NSRecycleZone(zone_);
3474 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3476 int chk(creat("/tmp/cydia.chk", 0644));
3480 if (invocation != nil)
3481 [invocation invoke];
3483 NSString *title(UCLocalize("DATABASE"));
3486 while (!cache_.Open(progress_, true)) { pop:
3488 bool warning(!_error->PopMessage(error));
3489 lprintf("cache_.Open():[%s]\n", error.c_str());
3491 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3492 [delegate_ repairWithSelector:@selector(configure)];
3493 else if (error == "The package lists or status file could not be parsed or opened.")
3494 [delegate_ repairWithSelector:@selector(update)];
3495 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3496 else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3497 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, Error_, title]];
3498 // else if (error == "The list of sources could not be read.")
3500 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3510 unlink("/tmp/cydia.chk");
3512 now_ = [[NSDate date] timeIntervalSince1970];
3514 policy_ = new pkgDepCache::Policy();
3515 records_ = new pkgRecords(cache_);
3516 resolver_ = new pkgProblemResolver(cache_);
3517 fetcher_ = new pkgAcquire(&status_);
3520 list_ = new pkgSourceList();
3521 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3524 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3525 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3529 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3532 if (cache_->BrokenCount() != 0) {
3533 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3536 if (cache_->BrokenCount() != 0) {
3537 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3541 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3545 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3546 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3547 [sourceList_ addObject:object];
3549 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3550 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3551 // XXX: this could be more intelligent
3552 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3553 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3555 sourceMap_[cached->ID] = object;
3560 /*std::vector<Package *> packages;
3561 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3562 [packages_ release];
3567 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3568 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3569 //packages.push_back(package);
3570 CFArrayAppendValue(packages_, [package retain]);
3574 /*if (packages.empty())
3575 packages_ = [[NSArray alloc] init];
3577 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3580 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3581 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3582 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3590 /*if (!packages.empty())
3591 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3592 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3594 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3596 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3598 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3602 size_t count(CFArrayGetCount(packages_));
3603 MetaFile_->active_ = count;
3605 for (size_t index(0); index != count; ++index)
3606 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3610 } } CYPoolEnd() _trace(); }
3613 @synchronized (self) {
3615 resolver_ = new pkgProblemResolver(cache_);
3617 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3618 if (!cache_[iterator].Keep())
3619 cache_->MarkKeep(iterator, false);
3620 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3621 cache_->SetReInstall(iterator, false);
3624 - (void) configure {
3625 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3627 system([dpkg UTF8String]);
3632 // XXX: I don't remember this condition
3637 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3639 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3641 if ([self popErrorWithTitle:title])
3645 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3648 public pkgArchiveCleaner
3651 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3656 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3663 fetcher_->Shutdown();
3665 pkgRecords records(cache_);
3667 lock_ = new FileFd();
3668 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3670 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3672 if ([self popErrorWithTitle:title])
3676 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3679 manager_ = (_system->CreatePM(cache_));
3680 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3687 bool substrate(RestartSubstrate_);
3688 RestartSubstrate_ = false;
3690 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3692 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3694 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3696 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3697 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3700 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3705 [(id)CydiaApp performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3707 bool failed = false;
3708 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3709 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3711 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3714 std::string uri = (*item)->DescURI();
3715 std::string error = (*item)->ErrorText;
3717 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3720 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3721 withObject:[NSArray arrayWithObjects:
3722 [NSString stringWithUTF8String:error.c_str()],
3728 [(id)CydiaApp performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3736 RestartSubstrate_ = true;
3739 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3741 if (_error->PendingError()) {
3746 if (result == pkgPackageManager::Failed) {
3751 if (result != pkgPackageManager::Completed) {
3756 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3758 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3760 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3761 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3764 if (![before isEqualToArray:after])
3769 NSString *title(UCLocalize("UPGRADE"));
3770 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3776 [self updateWithStatus:status_];
3779 - (void) updateWithStatus:(Status &)status {
3780 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3781 NSString *title(UCLocalize("REFRESHING_DATA"));
3784 if (!list.ReadMainList())
3785 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3788 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3789 if ([self popErrorWithTitle:title])
3792 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3793 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3794 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3796 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3800 - (void) setDelegate:(id)delegate {
3801 delegate_ = delegate;
3802 status_.setDelegate(delegate);
3803 progress_.setDelegate(delegate);
3806 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3807 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3808 return i == sourceMap_.end() ? nil : i->second;
3811 - (NSString *) mappedSectionForPointer:(const char *)section {
3812 _H<NSString> *mapped;
3814 _profile(Database$mappedSectionForPointer$Cache)
3815 mapped = §ions_[section];
3818 if (*mapped == NULL) {
3819 size_t length(strlen(section));
3820 char spaced[length + 1];
3822 _profile(Database$mappedSectionForPointer$Replace)
3823 for (size_t index(0); index != length; ++index)
3824 spaced[index] = section[index] == '_' ? ' ' : section[index];
3825 spaced[length] = '\0';
3830 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3831 string = [NSString stringWithUTF8String:spaced];
3834 _profile(Database$mappedSectionForPointer$Map)
3835 string = [SectionMap_ objectForKey:string] ?: string;
3845 /* Web Scripting {{{ */
3846 @interface CydiaObject : NSObject {
3848 _transient id delegate_;
3851 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3855 @implementation CydiaObject
3858 [indirect_ release];
3862 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3863 if ((self = [super init]) != nil) {
3864 indirect_ = [indirect retain];
3868 - (void) setDelegate:(id)delegate {
3869 delegate_ = delegate;
3872 + (NSArray *) _attributeKeys {
3873 return [NSArray arrayWithObjects:
3883 - (NSArray *) attributeKeys {
3884 return [[self class] _attributeKeys];
3887 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3888 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3891 - (NSString *) device {
3892 return [[UIDevice currentDevice] uniqueIdentifier];
3895 - (NSString *) plmn {
3899 - (NSString *) ecid {
3903 - (NSString *) serial {
3904 return SerialNumber_;
3907 - (NSString *) role {
3911 - (NSString *) model {
3912 return [NSString stringWithUTF8String:Machine_];
3915 + (NSString *) webScriptNameForSelector:(SEL)selector {
3917 else if (selector == @selector(addTrivialSource:))
3918 return @"addTrivialSource";
3919 else if (selector == @selector(close))
3921 else if (selector == @selector(du:))
3923 else if (selector == @selector(stringWithFormat:arguments:))
3925 else if (selector == @selector(getAllSources))
3926 return @"getAllSourcs";
3927 else if (selector == @selector(getKernelNumber:))
3928 return @"getKernelNumber";
3929 else if (selector == @selector(getKernelString:))
3930 return @"getKernelString";
3931 else if (selector == @selector(getInstalledPackages))
3932 return @"getInstalledPackages";
3933 else if (selector == @selector(getPackageById:))
3934 return @"getPackageById";
3935 else if (selector == @selector(installPackages:))
3936 return @"installPackages";
3937 else if (selector == @selector(localizedStringForKey:value:table:))
3939 else if (selector == @selector(refreshSources))
3940 return @"refreshSources";
3941 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3942 return @"setButtonImage";
3943 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3944 return @"setButtonTitle";
3945 else if (selector == @selector(setPopupHook:))
3946 return @"setPopupHook";
3947 else if (selector == @selector(setToken:))
3949 else if (selector == @selector(setViewportWidth:))
3950 return @"setViewportWidth";
3951 else if (selector == @selector(statfs:))
3953 else if (selector == @selector(supports:))
3959 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3960 return [self webScriptNameForSelector:selector] == nil;
3963 - (BOOL) supports:(NSString *)feature {
3964 return [feature isEqualToString:@"window.open"];
3967 - (NSNumber *) getKernelNumber:(NSString *)name {
3968 const char *string([name UTF8String]);
3971 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3972 return (id) [NSNull null];
3974 if (size != sizeof(int))
3975 return (id) [NSNull null];
3978 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3979 return (id) [NSNull null];
3981 return [NSNumber numberWithInt:value];
3984 - (NSString *) getKernelString:(NSString *)name {
3985 const char *string([name UTF8String]);
3988 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3989 return (id) [NSNull null];
3991 char value[size + 1];
3992 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3993 return (id) [NSNull null];
3995 // XXX: just in case you request something ludicrous
3998 return [NSString stringWithCString:value];
4001 - (void) addTrivialSource:(NSString *)href {
4002 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4005 - (void) refreshSources {
4006 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4009 - (NSArray *) getAllSources {
4010 return [[Database sharedInstance] sources];
4013 - (NSArray *) getInstalledPackages {
4014 Database *database([Database sharedInstance]);
4015 @synchronized (database) {
4016 NSArray *packages([database packages]);
4017 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4018 for (Package *package in packages)
4019 if (![package uninstalled])
4020 [installed addObject:package];
4024 - (Package *) getPackageById:(NSString *)id {
4025 Package *package([[Database sharedInstance] packageWithName:id]);
4030 - (NSArray *) statfs:(NSString *)path {
4033 if (path == nil || statfs([path UTF8String], &stat) == -1)
4036 return [NSArray arrayWithObjects:
4037 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4038 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4039 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4043 - (NSNumber *) du:(NSString *)path {
4044 NSNumber *value(nil);
4047 _assert(pipe(fds) != -1);
4049 pid_t pid(ExecFork());
4051 _assert(dup2(fds[1], 1) != -1);
4052 _assert(close(fds[0]) != -1);
4053 _assert(close(fds[1]) != -1);
4054 /* XXX: this should probably not use du */
4055 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4060 _assert(close(fds[1]) != -1);
4062 if (FILE *du = fdopen(fds[0], "r")) {
4064 while (fgets(line, sizeof(line), du) != NULL) {
4065 size_t length(strlen(line));
4066 while (length != 0 && line[length - 1] == '\n')
4067 line[--length] = '\0';
4068 if (char *tab = strchr(line, '\t')) {
4070 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4075 } else _assert(close(fds[0]));
4079 if (waitpid(pid, &status, 0) == -1)
4082 else _assert(false);
4088 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4091 - (void) installPackages:(NSArray *)packages {
4092 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4095 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4096 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4099 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4100 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4103 - (void) _setToken:(NSString *)token {
4106 Token_ = [token retain];
4108 [Metadata_ setObject:Token_ forKey:@"Token"];
4112 - (void) setToken:(NSString *)token {
4113 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4116 - (void) setPopupHook:(id)function {
4117 [indirect_ setPopupHook:function];
4120 - (void) setViewportWidth:(float)width {
4121 [indirect_ setViewportWidthOnMainThread:width];
4124 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4125 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4126 unsigned count([arguments count]);
4128 for (unsigned i(0); i != count; ++i)
4129 values[i] = [arguments objectAtIndex:i];
4130 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4133 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4134 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4136 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4138 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4144 /* @ Loading... Indicator {{{ */
4145 @interface CYLoadingIndicator : UIView {
4146 UIActivityIndicatorView *spinner_;
4151 @property (readonly, nonatomic) UILabel *label;
4152 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4156 @implementation CYLoadingIndicator
4158 - (id) initWithFrame:(CGRect)frame {
4159 if ((self = [super initWithFrame:frame]) != nil) {
4160 container_ = [[[UIView alloc] init] autorelease];
4161 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4163 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4164 [spinner_ startAnimating];
4165 [container_ addSubview:spinner_];
4167 label_ = [[[UILabel alloc] init] autorelease];
4168 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4169 [label_ setBackgroundColor:[UIColor clearColor]];
4170 [label_ setTextColor:[UIColor blackColor]];
4171 [label_ setShadowColor:[UIColor whiteColor]];
4172 [label_ setShadowOffset:CGSizeMake(0, 1)];
4173 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4174 [container_ addSubview:label_];
4176 CGSize viewsize = frame.size;
4177 CGSize spinnersize = [spinner_ bounds].size;
4178 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4179 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4181 CGRect containrect = {
4182 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4183 CGSizeMake(bothwidth, spinnersize.height)
4186 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4194 [container_ setFrame:containrect];
4195 [spinner_ setFrame:spinrect];
4196 [label_ setFrame:textrect];
4197 [self addSubview:container_];
4201 - (UILabel *) label {
4205 - (UIActivityIndicatorView *) activityIndicatorView {
4211 /* Emulated Loading Controller {{{ */
4212 @interface CYEmulatedLoadingController : CYViewController <
4214 ConfigurationDelegate
4216 _transient Database *database_;
4217 CYLoadingIndicator *indicator_;
4219 UINavigationBar *navbar_;
4224 @implementation CYEmulatedLoadingController
4227 [self releaseSubviews];
4228 [database_ setDelegate:nil];
4233 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4234 CYAlertView *sheet([[[CYAlertView alloc]
4236 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4237 defaultButtonIndex:0
4240 [sheet setMessage:error];
4241 [sheet yieldToPopupAlertAnimated:YES];
4245 - (void) setProgressTitle:(NSString *)title { }
4246 - (void) setProgressPercent:(NSNumber *)percent { }
4247 - (void) startProgress { }
4248 - (void) addProgressOutput:(NSString *)output { }
4249 - (bool) isCancelling:(size_t)received { return NO; }
4250 - (void) setConfigurationData:(NSString *)data { }
4252 - (void) repairWithSelector:(SEL)selector {
4253 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("REPAIRING"), nil] waitUntilDone:YES];
4254 [database_ performSelector:selector];
4256 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil] waitUntilDone:YES];
4259 - (id) initWithDatabase:(Database *)database {
4260 if ((self = [super init]) != nil) {
4261 database_ = database;
4262 [database_ setDelegate:self];
4267 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4268 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4270 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4271 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4272 [[self view] addSubview:indicator_];
4274 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4275 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4276 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4277 [[self view] addSubview:tabbar_];
4279 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4280 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4281 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4282 [[self view] addSubview:navbar_];
4285 - (void) releaseSubviews {
4286 [indicator_ release];
4299 /* Cydia Browser Controller {{{ */
4300 @interface CYBrowserController : BrowserController {
4301 CydiaObject *cydia_;
4306 @implementation CYBrowserController
4313 - (NSURL *) navigationURL {
4314 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4317 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4320 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4321 [super webView:view didClearWindowObject:window forFrame:frame];
4323 WebDataSource *source([frame dataSource]);
4324 NSURLResponse *response([source response]);
4326 NSURL *url([response URL]);
4327 NSString *scheme([url scheme]);
4328 NSString *host([url host]);
4330 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4331 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4332 NSDictionary *headers([http allHeaderFields]);
4333 [self setHeaders:headers forHost:host];
4337 [host isEqualToString:@"cydia.saurik.com"] ||
4338 [host hasSuffix:@".cydia.saurik.com"] ||
4339 [scheme isEqualToString:@"file"]
4341 [window setValue:cydia_ forKey:@"cydia"];
4344 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4345 if (System_ != NULL)
4346 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4347 if (Machine_ != NULL)
4348 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4350 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4352 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4355 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4356 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4357 [self _setMoreHeaders:copy];
4361 - (void) setDelegate:(id)delegate {
4362 [super setDelegate:delegate];
4363 [cydia_ setDelegate:delegate];
4367 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4368 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4370 WebView *webview([[webview_ _documentView] webView]);
4372 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4374 NSString *application = package == nil ? @"Cydia" : [NSString
4375 stringWithFormat:@"Cydia/%@",
4380 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4382 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4383 if (Product_ != nil)
4384 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4386 [webview setApplicationNameForUserAgent:application];
4394 @interface NSObject (CydiaScript)
4395 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4398 @implementation NSObject (CydiaScript)
4400 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4406 @implementation NSArray (CydiaScript)
4408 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4409 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4410 for (size_t i(0), e([self count]); i != e; ++i)
4411 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4417 @implementation NSDictionary (CydiaScript)
4419 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4420 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4422 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4429 /* Confirmation Controller {{{ */
4430 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4431 if (!iterator.end())
4432 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4433 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4435 pkgCache::PkgIterator package(dep.TargetPkg());
4438 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4445 @protocol ConfirmationControllerDelegate
4446 - (void) cancelAndClear:(bool)clear;
4447 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4451 @interface ConfirmationController : CYBrowserController {
4452 _transient Database *database_;
4454 UIAlertView *essential_;
4456 NSDictionary *changes_;
4457 NSMutableArray *issues_;
4458 NSDictionary *sizes_;
4463 - (id) initWithDatabase:(Database *)database;
4467 @implementation ConfirmationController
4474 if (essential_ != nil)
4475 [essential_ release];
4482 RestartSubstrate_ = true;
4483 [delegate_ confirmWithNavigationController:[self navigationController]];
4486 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4487 NSString *context([alert context]);
4489 if ([context isEqualToString:@"remove"]) {
4490 if (button == [alert cancelButtonIndex])
4491 [self dismissModalViewControllerAnimated:YES];
4492 else if (button == [alert firstOtherButtonIndex]) {
4496 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4497 } else if ([context isEqualToString:@"unable"]) {
4498 [self dismissModalViewControllerAnimated:YES];
4499 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4501 [super alertView:alert clickedButtonAtIndex:button];
4505 - (void) _doContinue {
4506 [self dismissModalViewControllerAnimated:YES];
4507 [delegate_ cancelAndClear:NO];
4510 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4511 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4515 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4516 [super webView:view didClearWindowObject:window forFrame:frame];
4518 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4519 changes_, @"changes",
4523 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4526 - (id) initWithDatabase:(Database *)database {
4527 if ((self = [super init]) != nil) {
4528 database_ = database;
4530 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4531 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4532 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4533 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4534 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4538 pkgCacheFile &cache([database_ cache]);
4539 NSArray *packages([database_ packages]);
4540 pkgDepCache::Policy *policy([database_ policy]);
4542 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4544 for (Package *package in packages) {
4545 pkgCache::PkgIterator iterator([package iterator]);
4546 NSString *name([package id]);
4548 if ([package broken]) {
4549 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4551 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4553 reasons, @"reasons",
4556 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4560 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4561 pkgCache::DepIterator start;
4562 pkgCache::DepIterator end;
4563 dep.GlobOr(start, end); // ++dep
4565 if (!cache->IsImportantDep(end))
4567 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4570 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4572 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4573 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4574 clauses, @"clauses",
4578 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4580 pkgCache::PkgIterator target(start.TargetPkg());
4581 if (target->ProvidesList != 0)
4582 reason = @"missing";
4584 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4586 reason = @"installed";
4587 installed = [NSString stringWithUTF8String:ver.VerStr()];
4588 } else if (!cache[target].CandidateVerIter(cache).end())
4589 reason = @"uninstalled";
4590 else if (target->ProvidesList == 0)
4591 reason = @"uninstallable";
4593 reason = @"virtual";
4596 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4597 [NSString stringWithUTF8String:start.CompType()], @"operator",
4598 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4601 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4602 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4603 version, @"version",
4605 installed, @"installed",
4608 // yes, seriously. (wtf?)
4616 pkgDepCache::StateCache &state(cache[iterator]);
4618 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4620 if (state.NewInstall())
4621 [installs addObject:name];
4622 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4623 [reinstalls addObject:name];
4624 else if (state.Upgrade())
4625 [upgrades addObject:name];
4626 else if (state.Downgrade())
4627 [downgrades addObject:name];
4628 else if (!state.Delete())
4630 else if (special_r(name))
4631 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4632 [NSNull null], @"package",
4633 [NSArray arrayWithObjects:
4634 [NSDictionary dictionaryWithObjectsAndKeys:
4635 @"Conflicts", @"relationship",
4636 [NSArray arrayWithObjects:
4637 [NSDictionary dictionaryWithObjectsAndKeys:
4639 [NSNull null], @"version",
4640 @"installed", @"reason",
4647 if ([package essential])
4649 [removes addObject:name];
4652 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4653 substrate_ |= DepSubstrate(iterator.CurrentVer());
4658 else if (Advanced_) {
4659 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4661 essential_ = [[UIAlertView alloc]
4662 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4663 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4665 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4667 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4671 [essential_ setContext:@"remove"];
4673 essential_ = [[UIAlertView alloc]
4674 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4675 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4677 cancelButtonTitle:UCLocalize("OKAY")
4678 otherButtonTitles:nil
4681 [essential_ setContext:@"unable"];
4684 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4685 installs, @"installs",
4686 reinstalls, @"reinstalls",
4687 upgrades, @"upgrades",
4688 downgrades, @"downgrades",
4689 removes, @"removes",
4692 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4693 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4694 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4697 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4699 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4700 initWithTitle:UCLocalize("CANCEL")
4701 style:UIBarButtonItemStylePlain
4703 action:@selector(cancelButtonClicked)
4709 - (void) applyRightButton {
4710 if ([issues_ count] == 0 && ![self isLoading])
4711 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4712 initWithTitle:UCLocalize("CONFIRM")
4713 style:UIBarButtonItemStyleDone
4715 action:@selector(confirmButtonClicked)
4718 [[self navigationItem] setRightBarButtonItem:nil];
4722 - (void) cancelButtonClicked {
4723 [self dismissModalViewControllerAnimated:YES];
4724 [delegate_ cancelAndClear:YES];
4728 - (void) confirmButtonClicked {
4729 if (essential_ != nil)
4739 /* Progress Data {{{ */
4740 @interface ProgressData : NSObject {
4742 // XXX: should these really both be _transient?
4743 _transient id target_;
4744 _transient id object_;
4747 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4755 @implementation ProgressData
4757 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4758 if ((self = [super init]) != nil) {
4759 selector_ = selector;
4779 /* Progress Controller {{{ */
4780 @interface ProgressController : CYViewController <
4781 ConfigurationDelegate,
4784 _transient Database *database_;
4785 UIProgressBar *progress_;
4786 UITextView *output_;
4787 UITextLabel *status_;
4788 UIPushButton *close_;
4790 SHA1SumValue springlist_;
4791 SHA1SumValue notifyconf_;
4795 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4797 - (void) _retachThread;
4798 - (void) _detachNewThreadData:(ProgressData *)data;
4799 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4805 @protocol ProgressControllerDelegate
4806 - (void) progressControllerIsComplete:(ProgressController *)sender;
4809 @implementation ProgressController
4812 [database_ setDelegate:nil];
4813 [progress_ release];
4822 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4823 if ((self = [super init]) != nil) {
4824 database_ = database;
4825 [database_ setDelegate:self];
4826 delegate_ = delegate;
4828 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4830 progress_ = [[UIProgressBar alloc] init];
4831 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4832 [progress_ setStyle:0];
4834 status_ = [[UITextLabel alloc] init];
4835 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4836 [status_ setColor:[UIColor whiteColor]];
4837 [status_ setBackgroundColor:[UIColor clearColor]];
4838 [status_ setCentersHorizontally:YES];
4839 //[status_ setFont:font];
4841 output_ = [[UITextView alloc] init];
4842 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4843 //[output_ setTextFont:@"Courier New"];
4844 [output_ setFont:[[output_ font] fontWithSize:12]];
4845 [output_ setTextColor:[UIColor whiteColor]];
4846 [output_ setBackgroundColor:[UIColor clearColor]];
4847 [output_ setMarginTop:0];
4848 [output_ setAllowsRubberBanding:YES];
4849 [output_ setEditable:NO];
4850 [[self view] addSubview:output_];
4852 close_ = [[UIPushButton alloc] init];
4853 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4854 [close_ setAutosizesToFit:NO];
4855 [close_ setDrawsShadow:YES];
4856 [close_ setStretchBackground:YES];
4857 [close_ setEnabled:YES];
4858 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4859 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4860 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4861 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4865 - (void) positionViews {
4866 CGRect bounds = [[self view] bounds];
4867 CGSize prgsize = [UIProgressBar defaultSize];
4870 (bounds.size.width - prgsize.width) / 2,
4871 bounds.size.height - prgsize.height - 20
4874 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4876 [progress_ setFrame:prgrect];
4877 [status_ setFrame:CGRectMake(
4879 bounds.size.height - prgsize.height - 50,
4880 bounds.size.width - 20,
4883 [output_ setFrame:CGRectMake(
4886 bounds.size.width - 20,
4887 bounds.size.height - 96
4889 [close_ setFrame:CGRectMake(
4890 (bounds.size.width - closewidth) / 2,
4891 bounds.size.height - prgsize.height - 50,
4897 - (void) viewWillAppear:(BOOL)animated {
4898 [super viewDidAppear:animated];
4899 [[self navigationItem] setHidesBackButton:YES];
4900 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4902 [self positionViews];
4905 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4906 [self positionViews];
4909 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4910 NSString *context([alert context]);
4912 if ([context isEqualToString:@"conffile"]) {
4913 FILE *input = [database_ input];
4914 if (button == [alert cancelButtonIndex])
4915 fprintf(input, "N\n");
4916 else if (button == [alert firstOtherButtonIndex])
4917 fprintf(input, "Y\n");
4922 - (void) closeButtonPushed {
4925 UpdateExternalStatus(0);
4929 [self dismissModalViewControllerAnimated:YES];
4933 [delegate_ terminateWithSuccess];
4934 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4935 [delegate_ suspendWithAnimation:YES];
4937 [delegate_ suspend];*/
4949 system("/usr/bin/sbreload");
4955 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4956 SBReboot(SBSSpringBoardServerPort());
4958 reboot2(RB_AUTOBOOT);
4963 - (void) _retachThread {
4964 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4966 [[self view] addSubview:close_];
4967 [progress_ removeFromSuperview];
4968 [status_ removeFromSuperview];
4970 [database_ popErrorWithTitle:title_];
4971 [delegate_ progressControllerIsComplete:self];
4975 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4978 MMap mmap(file, MMap::ReadOnly);
4980 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4981 if (!(notifyconf_ == sha1.Result()))
4988 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4991 MMap mmap(file, MMap::ReadOnly);
4993 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4994 if (!(springlist_ == sha1.Result()))
5000 if (RestartSubstrate_)
5004 RestartSubstrate_ = false;
5007 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5008 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
5009 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
5010 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5011 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
5015 system("su -c /usr/bin/uicache mobile");
5018 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
5020 [delegate_ setStatusBarShowsProgress:NO];
5023 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
5024 [[data target] performSelector:[data selector] withObject:[data object]];
5025 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
5028 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
5029 UpdateExternalStatus(1);
5036 title_ = [title retain];
5038 [[self navigationItem] setTitle:title_];
5040 [status_ setText:nil];
5041 [output_ setText:@""];
5042 [progress_ setProgress:0];
5044 [close_ removeFromSuperview];
5045 [[self view] addSubview:progress_];
5046 [[self view] addSubview:status_];
5048 [delegate_ setStatusBarShowsProgress:YES];
5053 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5056 MMap mmap(file, MMap::ReadOnly);
5058 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5059 notifyconf_ = sha1.Result();
5065 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5068 MMap mmap(file, MMap::ReadOnly);
5070 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5071 springlist_ = sha1.Result();
5076 detachNewThreadSelector:@selector(_detachNewThreadData:)
5078 withObject:[[[ProgressData alloc]
5079 initWithSelector:selector
5086 - (void) repairWithSelector:(SEL)selector {
5088 detachNewThreadSelector:selector
5091 title:UCLocalize("REPAIRING")
5095 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
5096 CYAlertView *sheet([[[CYAlertView alloc]
5098 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
5099 defaultButtonIndex:0
5102 [sheet setMessage:error];
5103 [sheet yieldToPopupAlertAnimated:YES];
5107 - (void) startProgress {
5110 - (bool) isCancelling:(size_t)received {
5114 - (void) setConfigurationData:(NSString *)data {
5115 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
5117 if (!conffile_r(data)) {
5118 lprintf("E:invalid conffile\n");
5122 NSString *ofile = conffile_r[1];
5123 //NSString *nfile = conffile_r[2];
5125 UIAlertView *alert = [[[UIAlertView alloc]
5126 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
5127 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
5129 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
5131 UCLocalize("ACCEPT_NEW_COPY"),
5132 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
5136 [alert setContext:@"conffile"];
5140 - (void) setProgressTitle:(NSString *)title {
5141 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
5142 for (size_t i(0), e([words count]); i != e; ++i) {
5143 NSString *word([words objectAtIndex:i]);
5144 if (Package *package = [database_ packageWithName:word])
5145 [words replaceObjectAtIndex:i withObject:[package name]];
5148 [status_ setText:[words componentsJoinedByString:@" "]];
5151 - (void) setProgressPercent:(NSNumber *)percent {
5152 [progress_ setProgress:[percent floatValue]];
5155 - (void) addProgressOutput:(NSString *)output {
5156 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
5157 CGSize size = [output_ contentSize];
5158 CGPoint offset = [output_ contentOffset];
5159 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
5160 CGRect rect = {{0, size.height-1}, {size.width, 1}};
5161 [output_ scrollRectToVisible:rect animated:YES];
5165 - (BOOL) isRunning {
5172 /* Cell Content View {{{ */
5173 @protocol ContentDelegate
5174 - (void) drawContentRect:(CGRect)rect;
5177 @interface ContentView : UIView {
5178 _transient id<ContentDelegate> delegate_;
5183 @implementation ContentView
5185 - (id) initWithFrame:(CGRect)frame {
5186 if ((self = [super initWithFrame:frame]) != nil) {
5187 [self setNeedsDisplayOnBoundsChange:YES];
5191 - (void) setDelegate:(id<ContentDelegate>)delegate {
5192 delegate_ = delegate;
5195 - (void) drawRect:(CGRect)rect {
5196 [super drawRect:rect];
5197 [delegate_ drawContentRect:rect];
5202 /* Cydia TableView Cell {{{ */
5203 @interface CYTableViewCell : UITableViewCell {
5204 ContentView *content_;
5210 @implementation CYTableViewCell
5217 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5218 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5220 if (view == content_) {
5221 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5222 highlighted_ = highlighted;
5225 [super _updateHighlightColorsForView:view highlighted:highlighted];
5228 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5229 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5230 highlighted_ = selected;
5232 [super setSelected:selected animated:animated];
5233 [content_ setNeedsDisplay];
5239 /* Package Cell {{{ */
5240 @interface PackageCell : CYTableViewCell <
5245 NSString *description_;
5253 - (PackageCell *) init;
5254 - (void) setPackage:(Package *)package;
5256 - (void) drawContentRect:(CGRect)rect;
5260 @implementation PackageCell
5262 - (void) clearPackage {
5273 if (description_ != nil) {
5274 [description_ release];
5278 if (source_ != nil) {
5283 if (badge_ != nil) {
5288 if (placard_ != nil) {
5298 [self clearPackage];
5302 - (PackageCell *) init {
5303 CGRect frame(CGRectMake(0, 0, 320, 74));
5304 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5305 UIView *content([self contentView]);
5306 CGRect bounds([content bounds]);
5308 content_ = [[ContentView alloc] initWithFrame:bounds];
5309 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5310 [content addSubview:content_];
5312 [content_ setDelegate:self];
5313 [content_ setOpaque:YES];
5317 - (NSString *) accessibilityLabel {
5318 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5321 - (void) setPackage:(Package *)package {
5322 [self clearPackage];
5325 Source *source = [package source];
5327 icon_ = [[package icon] retain];
5328 name_ = [[package name] retain];
5331 description_ = [package longDescription];
5332 if (description_ == nil)
5333 description_ = [package shortDescription];
5334 if (description_ != nil)
5335 description_ = [description_ retain];
5337 commercial_ = [package isCommercial];
5339 package_ = [package retain];
5341 NSString *label = nil;
5342 bool trusted = false;
5344 if (source != nil) {
5345 label = [source label];
5346 trusted = [source trusted];
5347 } else if ([[package id] isEqualToString:@"firmware"])
5348 label = UCLocalize("APPLE");
5350 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5352 NSString *from(label);
5354 NSString *section = [package simpleSection];
5355 if (section != nil && ![section isEqualToString:label]) {
5356 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5357 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5360 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5361 source_ = [from retain];
5363 if (NSString *purpose = [package primaryPurpose])
5364 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5365 badge_ = [badge_ retain];
5370 if (NSString *mode = [package_ mode]) {
5371 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5372 color = RemovingColor_;
5373 //placard = @"removing";
5375 color = InstallingColor_;
5376 //placard = @"installing";
5379 // XXX: the removing/installing placards are not @2x
5382 color = [UIColor whiteColor];
5384 if ([package installed] != nil)
5385 placard = @"installed";
5390 [content_ setBackgroundColor:color];
5393 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5394 placard_ = [placard_ retain];
5396 [self setNeedsDisplay];
5397 [content_ setNeedsDisplay];
5400 - (void) drawContentRect:(CGRect)rect {
5401 bool highlighted(highlighted_);
5402 float width([self bounds].size.width);
5405 CGContextRef context(UIGraphicsGetCurrentContext());
5406 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5407 CGContextFillRect(context, rect);
5412 rect.size = [icon_ size];
5414 rect.size.width /= 2;
5415 rect.size.height /= 2;
5417 rect.origin.x = 25 - rect.size.width / 2;
5418 rect.origin.y = 25 - rect.size.height / 2;
5420 [icon_ drawInRect:rect];
5423 if (badge_ != nil) {
5425 rect.size = [badge_ size];
5427 rect.size.width /= 2;
5428 rect.size.height /= 2;
5430 rect.origin.x = 36 - rect.size.width / 2;
5431 rect.origin.y = 36 - rect.size.height / 2;
5433 [badge_ drawInRect:rect];
5440 UISetColor(commercial_ ? Purple_ : Black_);
5441 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5442 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5445 UISetColor(commercial_ ? Purplish_ : Gray_);
5446 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5448 if (placard_ != nil)
5449 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5454 /* Section Cell {{{ */
5455 @interface SectionCell : CYTableViewCell <
5467 - (void) setSection:(Section *)section editing:(BOOL)editing;
5471 @implementation SectionCell
5473 - (void) clearSection {
5474 if (basic_ != nil) {
5479 if (section_ != nil) {
5489 if (count_ != nil) {
5496 [self clearSection];
5502 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5503 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5504 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5505 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5506 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5508 UIView *content([self contentView]);
5509 CGRect bounds([content bounds]);
5511 content_ = [[ContentView alloc] initWithFrame:bounds];
5512 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5513 [content addSubview:content_];
5514 [content_ setBackgroundColor:[UIColor whiteColor]];
5516 [content_ setDelegate:self];
5520 - (void) onSwitch:(id)sender {
5521 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5522 if (metadata == nil) {
5523 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5524 [Sections_ setObject:metadata forKey:basic_];
5527 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5531 - (void) setSection:(Section *)section editing:(BOOL)editing {
5532 if (editing != editing_) {
5534 [switch_ removeFromSuperview];
5536 [self addSubview:switch_];
5540 [self clearSection];
5542 if (section == nil) {
5543 name_ = [UCLocalize("ALL_PACKAGES") retain];
5546 basic_ = [section name];
5548 basic_ = [basic_ retain];
5550 section_ = [section localized];
5551 if (section_ != nil)
5552 section_ = [section_ retain];
5554 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5555 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5558 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5561 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5562 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5564 [content_ setNeedsDisplay];
5567 - (void) setFrame:(CGRect)frame {
5568 [super setFrame:frame];
5570 CGRect rect([switch_ frame]);
5571 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5574 - (NSString *) accessibilityLabel {
5578 - (void) drawContentRect:(CGRect)rect {
5579 bool highlighted(highlighted_ && !editing_);
5581 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5586 float width(rect.size.width);
5592 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5594 CGSize size = [count_ sizeWithFont:Font14_];
5598 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5604 /* File Table {{{ */
5605 @interface FileTable : CYViewController <
5606 UITableViewDataSource,
5609 _transient Database *database_;
5612 NSMutableArray *files_;
5616 - (id) initWithDatabase:(Database *)database;
5617 - (void) setPackage:(Package *)package;
5621 @implementation FileTable
5624 [self releaseSubviews];
5633 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5634 return files_ == nil ? 0 : [files_ count];
5637 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5641 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5642 static NSString *reuseIdentifier = @"Cell";
5644 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5646 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5647 [cell setFont:[UIFont systemFontOfSize:16]];
5649 [cell setText:[files_ objectAtIndex:indexPath.row]];
5650 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5655 - (NSURL *) navigationURL {
5656 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5660 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5662 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5663 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5664 [list_ setRowHeight:24.0f];
5665 [list_ setDataSource:self];
5666 [list_ setDelegate:self];
5667 [[self view] addSubview:list_];
5670 - (void) viewDidLoad {
5671 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5674 - (void) releaseSubviews {
5679 - (id) initWithDatabase:(Database *)database {
5680 if ((self = [super init]) != nil) {
5681 database_ = database;
5683 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5687 - (void) setPackage:(Package *)package {
5688 if (package_ != nil) {
5689 [package_ autorelease];
5698 [files_ removeAllObjects];
5700 if (package != nil) {
5701 package_ = [package retain];
5702 name_ = [[package id] retain];
5704 if (NSArray *files = [package files])
5705 [files_ addObjectsFromArray:files];
5707 if ([files_ count] != 0) {
5708 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5709 [files_ removeObjectAtIndex:0];
5710 [files_ sortUsingSelector:@selector(compareByPath:)];
5712 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5713 [stack addObject:@"/"];
5715 for (int i(0), e([files_ count]); i != e; ++i) {
5716 NSString *file = [files_ objectAtIndex:i];
5717 while (![file hasPrefix:[stack lastObject]])
5718 [stack removeLastObject];
5719 NSString *directory = [stack lastObject];
5720 [stack addObject:[file stringByAppendingString:@"/"]];
5721 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5722 ([stack count] - 2) * 3, "",
5723 [file substringFromIndex:[directory length]]
5732 - (void) reloadData {
5735 [self setPackage:[database_ packageWithName:name_]];
5740 /* Package Controller {{{ */
5741 @interface CYPackageController : CYBrowserController <
5742 UIActionSheetDelegate
5744 _transient Database *database_;
5748 NSMutableArray *buttons_;
5749 UIBarButtonItem *button_;
5752 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5756 @implementation CYPackageController
5759 if (package_ != nil)
5772 - (NSURL *) navigationURL {
5773 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5776 /* XXX: this is not safe at all... localization of /fail/ */
5777 - (void) _clickButtonWithName:(NSString *)name {
5778 if ([name isEqualToString:UCLocalize("CLEAR")])
5779 [delegate_ clearPackage:package_];
5780 else if ([name isEqualToString:UCLocalize("INSTALL")])
5781 [delegate_ installPackage:package_];
5782 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5783 [delegate_ installPackage:package_];
5784 else if ([name isEqualToString:UCLocalize("REMOVE")])
5785 [delegate_ removePackage:package_];
5786 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5787 [delegate_ installPackage:package_];
5788 else _assert(false);
5791 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5792 NSString *context([sheet context]);
5794 if ([context isEqualToString:@"modify"]) {
5795 if (button != [sheet cancelButtonIndex]) {
5796 NSString *buttonName = [buttons_ objectAtIndex:button];
5797 [self _clickButtonWithName:buttonName];
5800 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5804 - (bool) _allowJavaScriptPanel {
5809 - (void) _customButtonClicked {
5810 int count([buttons_ count]);
5815 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5817 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5818 [buttons addObjectsFromArray:buttons_];
5820 UIActionSheet *sheet = [[[UIActionSheet alloc]
5823 cancelButtonTitle:nil
5824 destructiveButtonTitle:nil
5825 otherButtonTitles:nil
5828 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5830 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5831 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5833 [sheet setContext:@"modify"];
5835 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5839 // We don't want to allow non-commercial packages to do custom things to the install button,
5840 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5841 - (void) customButtonClicked {
5843 [super customButtonClicked];
5845 [self _customButtonClicked];
5848 - (void) reloadButtonClicked {
5849 // Don't reload a commerical package by tapping the loading button,
5850 // but if it's not an Install button, we should forward it on.
5851 if (![package_ uninstalled])
5852 [self _customButtonClicked];
5855 - (void) applyLoadingTitle {
5856 // Don't show "Loading" as the title. Ever.
5859 - (UIBarButtonItem *) rightButton {
5864 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5865 if ((self = [super init]) != nil) {
5866 database_ = database;
5867 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5868 name_ = [[NSString alloc] initWithString:name];
5869 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5873 - (void) reloadData {
5874 if (package_ != nil)
5875 [package_ autorelease];
5876 package_ = [database_ packageWithName:name_];
5878 [buttons_ removeAllObjects];
5880 if (package_ != nil) {
5883 package_ = [package_ retain];
5884 commercial_ = [package_ isCommercial];
5886 if ([package_ mode] != nil)
5887 [buttons_ addObject:UCLocalize("CLEAR")];
5888 if ([package_ source] == nil);
5889 else if ([package_ upgradableAndEssential:NO])
5890 [buttons_ addObject:UCLocalize("UPGRADE")];
5891 else if ([package_ uninstalled])
5892 [buttons_ addObject:UCLocalize("INSTALL")];
5894 [buttons_ addObject:UCLocalize("REINSTALL")];
5895 if (![package_ uninstalled])
5896 [buttons_ addObject:UCLocalize("REMOVE")];
5903 switch ([buttons_ count]) {
5904 case 0: title = nil; break;
5905 case 1: title = [buttons_ objectAtIndex:0]; break;
5906 default: title = UCLocalize("MODIFY"); break;
5909 button_ = [[UIBarButtonItem alloc]
5911 style:UIBarButtonItemStylePlain
5913 action:@selector(customButtonClicked)
5919 - (bool) isLoading {
5920 return commercial_ ? [super isLoading] : false;
5926 /* Package List Controller {{{ */
5927 @interface PackageListController : CYViewController <
5928 UITableViewDataSource,
5931 _transient Database *database_;
5933 NSMutableArray *packages_;
5934 NSMutableArray *sections_;
5936 NSMutableArray *index_;
5937 NSMutableDictionary *indices_;
5941 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5942 - (void) setDelegate:(id)delegate;
5943 - (void) resetCursor;
5947 @implementation PackageListController
5950 [packages_ release];
5951 [sections_ release];
5960 - (void) deselectWithAnimation:(BOOL)animated {
5961 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5964 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5965 CGRect base = [[self view] bounds];
5966 base.size.height -= bounds.size.height;
5967 base.origin = [list_ frame].origin;
5969 [UIView beginAnimations:nil context:NULL];
5970 [UIView setAnimationBeginsFromCurrentState:YES];
5971 [UIView setAnimationCurve:curve];
5972 [UIView setAnimationDuration:duration];
5973 [list_ setFrame:base];
5974 [UIView commitAnimations];
5977 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5978 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5981 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5982 [self resizeForKeyboardBounds:bounds duration:0];
5985 - (void) keyboardWillShow:(NSNotification *)notification {
5988 NSTimeInterval duration;
5989 UIViewAnimationCurve curve;
5990 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5991 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5992 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5993 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5995 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);
5996 UIViewController *base = self;
5997 while ([base parentViewController] != nil)
5998 base = [base parentViewController];
5999 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6000 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6002 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6005 - (void) keyboardWillHide:(NSNotification *)notification {
6006 NSTimeInterval duration;
6007 UIViewAnimationCurve curve;
6008 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6009 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6011 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6014 - (void) viewWillAppear:(BOOL)animated {
6015 [super viewWillAppear:animated];
6017 [self resizeForKeyboardBounds:CGRectZero];
6018 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6019 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6022 - (void) viewWillDisappear:(BOOL)animated {
6023 [super viewWillDisappear:animated];
6025 [self resizeForKeyboardBounds:CGRectZero];
6026 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6027 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6030 - (void) viewDidAppear:(BOOL)animated {
6031 [super viewDidAppear:animated];
6032 [self deselectWithAnimation:animated];
6035 - (void) didSelectPackage:(Package *)package {
6036 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6037 [view setDelegate:delegate_];
6038 [[self navigationController] pushViewController:view animated:YES];
6041 #if TryIndexedCollation
6042 + (BOOL) hasIndexedCollation {
6043 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6047 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6048 NSInteger count([sections_ count]);
6049 return count == 0 ? 1 : count;
6052 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6053 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6055 return [[sections_ objectAtIndex:section] name];
6058 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6059 if ([sections_ count] == 0)
6061 return [[sections_ objectAtIndex:section] count];
6064 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6065 @synchronized (database_) {
6066 if ([database_ era] != era_)
6069 Section *section([sections_ objectAtIndex:[path section]]);
6070 NSInteger row([path row]);
6071 Package *package([packages_ objectAtIndex:([section row] + row)]);
6072 return [[package retain] autorelease];
6075 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6076 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6078 cell = [[[PackageCell alloc] init] autorelease];
6079 [cell setPackage:[self packageAtIndexPath:path]];
6083 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6084 Package *package([self packageAtIndexPath:path]);
6085 package = [database_ packageWithName:[package id]];
6086 [self didSelectPackage:package];
6089 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6090 // XXX: is 20 the most optimal number here?
6091 return [packages_ count] > 20 ? index_ : nil;
6094 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6095 #if TryIndexedCollation
6096 if ([[self class] hasIndexedCollation]) {
6097 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6104 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6105 if ((self = [super init]) != nil) {
6106 database_ = database;
6107 title_ = [title copy];
6108 [[self navigationItem] setTitle:title_];
6110 #if TryIndexedCollation
6111 if ([[self class] hasIndexedCollation])
6112 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6115 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6117 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6119 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6120 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6122 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6123 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6124 [list_ setRowHeight:73];
6125 [[self view] addSubview:list_];
6127 [list_ setDataSource:self];
6128 [list_ setDelegate:self];
6132 - (void) setDelegate:(id)delegate {
6133 delegate_ = delegate;
6136 - (bool) hasPackage:(Package *)package {
6140 - (void) reloadData {
6143 era_ = [database_ era];
6144 NSArray *packages = [database_ packages];
6146 [packages_ removeAllObjects];
6147 [sections_ removeAllObjects];
6149 _profile(PackageTable$reloadData$Filter)
6150 for (Package *package in packages)
6151 if ([self hasPackage:package])
6152 [packages_ addObject:package];
6155 [indices_ removeAllObjects];
6157 Section *section = nil;
6159 #if TryIndexedCollation
6160 if ([[self class] hasIndexedCollation]) {
6161 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6162 NSArray *titles = [collation sectionIndexTitles];
6165 _profile(PackageTable$reloadData$Section)
6166 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6170 _profile(PackageTable$reloadData$Section$Package)
6171 package = [packages_ objectAtIndex:offset];
6172 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6175 while (secidx < index) {
6178 _profile(PackageTable$reloadData$Section$Allocate)
6179 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6182 _profile(PackageTable$reloadData$Section$Add)
6183 [sections_ addObject:section];
6187 [section addToCount];
6193 [index_ removeAllObjects];
6195 _profile(PackageTable$reloadData$Section)
6196 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6200 _profile(PackageTable$reloadData$Section$Package)
6201 package = [packages_ objectAtIndex:offset];
6202 index = [package index];
6205 if (section == nil || [section index] != index) {
6206 _profile(PackageTable$reloadData$Section$Allocate)
6207 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6210 [index_ addObject:[section name]];
6211 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6213 _profile(PackageTable$reloadData$Section$Add)
6214 [sections_ addObject:section];
6218 [section addToCount];
6223 _profile(PackageTable$reloadData$List)
6228 - (void) resetCursor {
6229 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6234 /* Filtered Package List Controller {{{ */
6235 @interface FilteredPackageListController : PackageListController {
6241 - (void) setObject:(id)object;
6242 - (void) setObject:(id)object forFilter:(SEL)filter;
6244 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6248 @implementation FilteredPackageListController
6256 - (void) setFilter:(SEL)filter {
6259 /* XXX: this is an unsafe optimization of doomy hell */
6260 Method method(class_getInstanceMethod([Package class], filter));
6261 _assert(method != NULL);
6262 imp_ = method_getImplementation(method);
6263 _assert(imp_ != NULL);
6266 - (void) setObject:(id)object {
6272 object_ = [object retain];
6275 - (void) setObject:(id)object forFilter:(SEL)filter {
6276 [self setFilter:filter];
6277 [self setObject:object];
6280 - (bool) hasPackage:(Package *)package {
6281 _profile(FilteredPackageTable$hasPackage)
6282 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6286 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6287 if ((self = [super initWithDatabase:database title:title]) != nil) {
6288 [self setFilter:filter];
6289 [self setObject:object];
6296 /* Home Controller {{{ */
6297 @interface HomeController : CYBrowserController {
6302 @implementation HomeController
6304 + (BOOL) shouldHideNavigationBar {
6308 - (NSURL *) navigationURL {
6309 return [NSURL URLWithString:@"cydia://home"];
6312 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6313 [super _setMoreHeaders:request];
6316 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6317 if (UniqueID_ != nil)
6318 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6320 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6323 - (void) aboutButtonClicked {
6324 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6326 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6327 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6328 [alert setCancelButtonIndex:0];
6331 @"Copyright (C) 2008-2011\n"
6332 "Jay Freeman (saurik)\n"
6333 "saurik@saurik.com\n"
6334 "http://www.saurik.com/"
6340 - (void) viewWillDisappear:(BOOL)animated {
6341 [super viewWillDisappear:animated];
6343 if ([[self class] shouldHideNavigationBar])
6344 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6347 - (void) viewWillAppear:(BOOL)animated {
6348 if (![self hasLoaded])
6349 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6351 [super viewWillAppear:animated];
6353 if ([[self class] shouldHideNavigationBar])
6354 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6357 - (void) viewDidLoad {
6358 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6359 initWithTitle:UCLocalize("ABOUT")
6360 style:UIBarButtonItemStylePlain
6362 action:@selector(aboutButtonClicked)
6368 /* Manage Controller {{{ */
6369 @interface ManageController : CYBrowserController {
6372 - (void) queueStatusDidChange;
6376 @implementation ManageController
6378 - (NSURL *) navigationURL {
6379 return [NSURL URLWithString:@"cydia://manage"];
6382 - (void) viewWillAppear:(BOOL)animated {
6383 if (![self hasLoaded])
6384 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6386 [super viewWillAppear:animated];
6389 - (void) viewDidLoad {
6390 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6391 initWithTitle:UCLocalize("SETTINGS")
6392 style:UIBarButtonItemStylePlain
6394 action:@selector(settingsButtonClicked)
6397 [self queueStatusDidChange];
6400 - (void) settingsButtonClicked {
6401 [delegate_ showSettings];
6405 - (void) queueButtonClicked {
6409 - (void) applyLoadingTitle {
6410 // Disable "Loading" title.
6413 - (void) applyRightButton {
6414 // Disable right button.
6418 - (void) queueStatusDidChange {
6420 if (!IsWildcat_ && Queuing_) {
6421 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6422 initWithTitle:UCLocalize("QUEUE")
6423 style:UIBarButtonItemStyleDone
6425 action:@selector(queueButtonClicked)
6428 [[self navigationItem] setRightBarButtonItem:nil];
6433 - (bool) isLoading {
6434 // Never show as loading.
6441 /* Refresh Bar {{{ */
6442 @interface RefreshBar : UINavigationBar {
6443 UIProgressIndicator *indicator_;
6444 UITextLabel *prompt_;
6445 UIProgressBar *progress_;
6446 UINavigationButton *cancel_;
6451 @implementation RefreshBar
6454 [indicator_ release];
6456 [progress_ release];
6461 - (void) positionViews {
6462 CGRect frame = [cancel_ frame];
6463 frame.size = [cancel_ sizeThatFits:frame.size];
6464 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6465 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6466 [cancel_ setFrame:frame];
6468 CGSize prgsize = {75, 100};
6470 [self frame].size.width - prgsize.width - 10,
6471 ([self frame].size.height - prgsize.height) / 2
6473 [progress_ setFrame:prgrect];
6475 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6476 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6477 CGRect indrect = {{indoffset, indoffset}, indsize};
6478 [indicator_ setFrame:indrect];
6480 CGSize prmsize = {215, indsize.height + 4};
6482 indoffset * 2 + indsize.width,
6483 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6485 [prompt_ setFrame:prmrect];
6488 - (void) setFrame:(CGRect)frame {
6489 [super setFrame:frame];
6490 [self positionViews];
6493 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6494 if ((self = [super initWithFrame:frame]) != nil) {
6495 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6497 [self setBarStyle:UIBarStyleBlack];
6499 UIBarStyle barstyle([self _barStyle:NO]);
6500 bool ugly(barstyle == UIBarStyleDefault);
6502 UIProgressIndicatorStyle style = ugly ?
6503 UIProgressIndicatorStyleMediumBrown :
6504 UIProgressIndicatorStyleMediumWhite;
6506 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6507 [indicator_ setStyle:style];
6508 [indicator_ startAnimation];
6509 [self addSubview:indicator_];
6511 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6512 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6513 [prompt_ setBackgroundColor:[UIColor clearColor]];
6514 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6515 [self addSubview:prompt_];
6517 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6518 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6519 [progress_ setStyle:0];
6520 [self addSubview:progress_];
6522 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6523 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6524 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6525 [cancel_ setBarStyle:barstyle];
6527 [self positionViews];
6532 [cancel_ removeFromSuperview];
6536 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6537 [progress_ setProgress:0];
6538 [self addSubview:cancel_];
6542 [cancel_ removeFromSuperview];
6545 - (void) setPrompt:(NSString *)prompt {
6546 [prompt_ setText:prompt];
6549 - (void) setProgress:(float)progress {
6550 [progress_ setProgress:progress];
6556 @class CYNavigationController;
6558 /* Cydia Tab Bar Controller {{{ */
6559 @interface CYTabBarController : UITabBarController <
6560 UITabBarControllerDelegate,
6563 _transient Database *database_;
6564 RefreshBar *refreshbar_;
6568 // XXX: ok, "updatedelegate_"?...
6569 _transient NSObject<CydiaDelegate> *updatedelegate_;
6572 UIViewController *remembered_;
6573 _transient UIViewController *transient_;
6576 - (NSArray *) navigationURLCollection;
6577 - (void) dropBar:(BOOL)animated;
6578 - (void) beginUpdate;
6579 - (void) raiseBar:(BOOL)animated;
6584 @implementation CYTabBarController
6586 - (void) setUnselectedViewController:(UIViewController *)transient {
6587 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6588 if (transient != nil) {
6589 if (transient_ == nil)
6590 remembered_ = [[controllers objectAtIndex:0] retain];
6591 transient_ = transient;
6592 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6593 [controllers replaceObjectAtIndex:0 withObject:transient_];
6594 [self setSelectedIndex:0];
6595 [self setViewControllers:controllers];
6596 [self concealTabBarSelection];
6597 } else if (remembered_ != nil) {
6598 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6599 transient_ = transient;
6600 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6601 [remembered_ release];
6603 [self setViewControllers:controllers];
6604 [self revealTabBarSelection];
6608 - (UIViewController *) unselectedViewController {
6612 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6613 if ([self unselectedViewController])
6614 [self setUnselectedViewController:nil];
6617 - (NSArray *) navigationURLCollection {
6618 NSMutableArray *items([NSMutableArray array]);
6620 // XXX: Should this deal with transient view controllers?
6621 for (id navigation in [self viewControllers]) {
6622 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6624 [items addObject:stack];
6630 - (void) reloadData {
6631 for (CYViewController *controller in [self viewControllers])
6632 [controller reloadData];
6634 [(CYNavigationController *)[self unselectedViewController] reloadData];
6638 [refreshbar_ release];
6639 [[NSNotificationCenter defaultCenter] removeObserver:self];
6644 - (id) initWithDatabase:(Database *)database {
6645 if ((self = [super init]) != nil) {
6646 database_ = database;
6647 [self setDelegate:self];
6649 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6650 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6652 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6656 - (void) setUpdate:(NSDate *)date {
6660 - (void) beginUpdate {
6661 [refreshbar_ start];
6664 [updatedelegate_ retainNetworkActivityIndicator];
6668 detachNewThreadSelector:@selector(performUpdate)
6674 - (void) performUpdate { _pooled
6676 status.setDelegate(self);
6677 [database_ updateWithStatus:status];
6680 performSelectorOnMainThread:@selector(completeUpdate)
6686 - (void) stopUpdateWithSelector:(SEL)selector {
6688 [updatedelegate_ releaseNetworkActivityIndicator];
6690 [self raiseBar:YES];
6693 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6696 - (void) completeUpdate {
6699 [self stopUpdateWithSelector:@selector(reloadData)];
6702 - (void) cancelUpdate {
6703 [self stopUpdateWithSelector:@selector(updateData)];
6706 - (void) cancelPressed {
6707 [self cancelUpdate];
6714 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6715 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6718 - (void) startProgress {
6721 - (bool) isCancelling:(size_t)received {
6725 - (void) setProgressTitle:(NSString *)title {
6726 [refreshbar_ setPrompt:title];
6729 - (void) setProgressPercent:(NSNumber *)percent {
6730 [refreshbar_ setProgress:[percent floatValue]];
6733 - (void) addProgressOutput:(NSString *)output {
6736 - (void) setUpdateDelegate:(id)delegate {
6737 updatedelegate_ = delegate;
6740 - (CGFloat) statusBarHeight {
6741 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6742 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6744 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6748 - (UIView *) transitionView {
6749 if ([self respondsToSelector:@selector(_transitionView)])
6750 return [self _transitionView];
6752 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6755 - (void) dropBar:(BOOL)animated {
6760 UIView *transition([self transitionView]);
6761 [[self view] addSubview:refreshbar_];
6763 CGRect barframe([refreshbar_ frame]);
6765 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6766 barframe.origin.y = [self statusBarHeight];
6768 barframe.origin.y = 0;
6770 [refreshbar_ setFrame:barframe];
6773 [UIView beginAnimations:nil context:NULL];
6775 CGRect viewframe = [transition frame];
6776 viewframe.origin.y += barframe.size.height;
6777 viewframe.size.height -= barframe.size.height;
6778 [transition setFrame:viewframe];
6781 [UIView commitAnimations];
6783 // Ensure bar has the proper width for our view, it might have changed
6784 barframe.size.width = viewframe.size.width;
6785 [refreshbar_ setFrame:barframe];
6787 // XXX: fix Apple's layout bug
6788 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6791 - (void) raiseBar:(BOOL)animated {
6796 UIView *transition([self transitionView]);
6797 [refreshbar_ removeFromSuperview];
6799 CGRect barframe([refreshbar_ frame]);
6802 [UIView beginAnimations:nil context:NULL];
6804 CGRect viewframe = [transition frame];
6805 viewframe.origin.y -= barframe.size.height;
6806 viewframe.size.height += barframe.size.height;
6807 [transition setFrame:viewframe];
6810 [UIView commitAnimations];
6812 // XXX: fix Apple's layout bug
6813 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6817 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6818 // XXX: fix Apple's layout bug
6819 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6823 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6824 bool dropped(dropped_);
6829 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6834 // XXX: fix Apple's layout bug
6835 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6838 - (void) statusBarFrameChanged:(NSNotification *)notification {
6847 /* Cydia Navigation Controller {{{ */
6848 @interface CYNavigationController : UINavigationController {
6849 _transient Database *database_;
6850 _transient id<UINavigationControllerDelegate> delegate_;
6853 - (NSArray *) navigationURLCollection;
6854 - (id) initWithDatabase:(Database *)database;
6855 - (void) reloadData;
6860 @implementation CYNavigationController
6862 - (NSArray *) navigationURLCollection {
6863 NSMutableArray *stack([NSMutableArray array]);
6865 for (CYViewController *controller in [self viewControllers]) {
6866 NSString *url = [[controller navigationURL] absoluteString];
6868 [stack addObject:url];
6874 - (void) reloadData {
6875 for (CYViewController *page in [self viewControllers]) {
6876 // Only reload controllers that have already loaded.
6877 // This prevents a page from accidentally loading too
6878 // early if it hasn't been shown on the screen yet.
6879 if ([page hasLoaded])
6884 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6885 delegate_ = delegate;
6888 - (id) initWithDatabase:(Database *)database {
6889 if ((self = [super init]) != nil) {
6890 database_ = database;
6897 /* Cydia:// Protocol {{{ */
6898 @interface CydiaURLProtocol : NSURLProtocol {
6903 @implementation CydiaURLProtocol
6905 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6906 NSURL *url([request URL]);
6909 NSString *scheme([[url scheme] lowercaseString]);
6910 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6915 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6919 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6920 id<NSURLProtocolClient> client([self client]);
6922 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6924 NSData *data(UIImagePNGRepresentation(icon));
6926 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6927 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6928 [client URLProtocol:self didLoadData:data];
6929 [client URLProtocolDidFinishLoading:self];
6933 - (void) startLoading {
6934 id<NSURLProtocolClient> client([self client]);
6935 NSURLRequest *request([self request]);
6937 NSURL *url([request URL]);
6938 NSString *href([url absoluteString]);
6940 NSString *path([href substringFromIndex:8]);
6941 NSRange slash([path rangeOfString:@"/"]);
6944 if (slash.location == NSNotFound) {
6948 command = [path substringToIndex:slash.location];
6949 path = [path substringFromIndex:(slash.location + 1)];
6952 Database *database([Database sharedInstance]);
6954 if ([command isEqualToString:@"package-icon"]) {
6957 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6958 Package *package([database packageWithName:path]);
6961 UIImage *icon([package icon]);
6962 [self _returnPNGWithImage:icon forRequest:request];
6963 } else if ([command isEqualToString:@"source-icon"]) {
6966 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6967 NSString *source(Simplify(path));
6968 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6970 icon = [UIImage applicationImageNamed:@"unknown.png"];
6971 [self _returnPNGWithImage:icon forRequest:request];
6972 } else if ([command isEqualToString:@"uikit-image"]) {
6975 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6976 UIImage *icon(_UIImageWithName(path));
6977 [self _returnPNGWithImage:icon forRequest:request];
6978 } else if ([command isEqualToString:@"section-icon"]) {
6981 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6982 NSString *section(Simplify(path));
6983 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6985 icon = [UIImage applicationImageNamed:@"unknown.png"];
6986 [self _returnPNGWithImage:icon forRequest:request];
6988 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6992 - (void) stopLoading {
6998 /* Section Controller {{{ */
6999 @interface SectionController : FilteredPackageListController {
7003 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7007 @implementation SectionController
7009 - (NSURL *) navigationURL {
7010 NSString *name = section_;
7014 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7017 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7020 title = UCLocalize("ALL_PACKAGES");
7021 else if (![name isEqual:@""])
7022 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7024 title = UCLocalize("NO_SECTION");
7026 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7033 /* Sections Controller {{{ */
7034 @interface SectionsController : CYViewController <
7035 UITableViewDataSource,
7038 _transient Database *database_;
7039 NSMutableArray *sections_;
7040 NSMutableArray *filtered_;
7045 - (id) initWithDatabase:(Database *)database;
7046 - (void) editButtonClicked;
7050 @implementation SectionsController
7053 [self releaseSubviews];
7054 [sections_ release];
7055 [filtered_ release];
7060 - (NSURL *) navigationURL {
7061 return [NSURL URLWithString:@"cydia://sections"];
7064 - (void) updateNavigationItem {
7065 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7066 if ([sections_ count] == 0) {
7067 [[self navigationItem] setRightBarButtonItem:nil];
7069 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7070 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7072 action:@selector(editButtonClicked)
7073 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7077 - (BOOL) isEditing {
7081 - (void) setEditing:(BOOL)editing {
7082 if ((editing_ = editing))
7085 [delegate_ updateData];
7087 [self updateNavigationItem];
7090 - (void) viewDidAppear:(BOOL)animated {
7091 [super viewDidAppear:animated];
7092 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7095 - (void) viewWillDisappear:(BOOL)animated {
7096 [super viewWillDisappear:animated];
7097 if (editing_) [self setEditing:NO];
7100 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7101 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7105 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7106 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7109 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7113 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7114 static NSString *reuseIdentifier = @"SectionCell";
7116 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7118 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7120 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7125 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7129 Section *section = [self sectionAtIndexPath:indexPath];
7131 SectionController *controller = [[[SectionController alloc]
7132 initWithDatabase:database_
7133 section:[section name]
7135 [controller setDelegate:delegate_];
7137 [[self navigationController] pushViewController:controller animated:YES];
7141 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7143 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7144 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7145 [list_ setRowHeight:45.0f];
7146 [list_ setDataSource:self];
7147 [list_ setDelegate:self];
7148 [[self view] addSubview:list_];
7151 - (void) viewDidLoad {
7152 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7155 - (void) releaseSubviews {
7160 - (id) initWithDatabase:(Database *)database {
7161 if ((self = [super init]) != nil) {
7162 database_ = database;
7164 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7165 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7169 - (void) reloadData {
7172 NSArray *packages = [database_ packages];
7174 [sections_ removeAllObjects];
7175 [filtered_ removeAllObjects];
7177 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7180 for (Package *package in packages) {
7181 NSString *name([package section]);
7182 NSString *key(name == nil ? @"" : name);
7186 _profile(SectionsView$reloadData$Section)
7187 section = [sections objectForKey:key];
7188 if (section == nil) {
7189 _profile(SectionsView$reloadData$Section$Allocate)
7190 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7191 [sections setObject:section forKey:key];
7196 [section addToCount];
7198 _profile(SectionsView$reloadData$Filter)
7199 if (![package valid] || ![package visible])
7207 [sections_ addObjectsFromArray:[sections allValues]];
7209 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7211 for (Section *section in sections_) {
7212 size_t count([section row]);
7216 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7217 [section setCount:count];
7218 [filtered_ addObject:section];
7221 [self updateNavigationItem];
7226 - (void) editButtonClicked {
7227 [self setEditing:(!editing_)];
7233 /* Changes Controller {{{ */
7234 @interface ChangesController : CYViewController <
7235 UITableViewDataSource,
7238 _transient Database *database_;
7240 CFMutableArrayRef packages_;
7241 NSMutableArray *sections_;
7244 BOOL hasSentFirstLoad_;
7247 - (id) initWithDatabase:(Database *)database;
7251 @implementation ChangesController
7254 [self releaseSubviews];
7255 CFRelease(packages_);
7256 [sections_ release];
7261 - (NSURL *) navigationURL {
7262 return [NSURL URLWithString:@"cydia://changes"];
7265 - (void) viewWillAppear:(BOOL)animated {
7266 // Loads after it appears, so don't load beforehand.
7268 [super viewWillAppear:animated];
7271 - (void) viewDidAppear:(BOOL)animated {
7272 [super viewDidAppear:animated];
7274 if (!hasSentFirstLoad_) {
7275 hasSentFirstLoad_ = YES;
7276 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7278 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7282 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7283 NSInteger count([sections_ count]);
7284 return count == 0 ? 1 : count;
7287 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7288 if ([sections_ count] == 0)
7290 return [[sections_ objectAtIndex:section] name];
7293 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7294 if ([sections_ count] == 0)
7296 return [[sections_ objectAtIndex:section] count];
7299 - (Package *) packageAtIndex:(NSUInteger)index {
7300 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7303 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7304 @synchronized (database_) {
7305 if ([database_ era] != era_)
7308 NSUInteger sectionIndex([path section]);
7309 if (sectionIndex >= [sections_ count])
7311 Section *section([sections_ objectAtIndex:sectionIndex]);
7312 NSInteger row([path row]);
7313 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7316 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7317 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7319 cell = [[[PackageCell alloc] init] autorelease];
7320 [cell setPackage:[self packageAtIndexPath:path]];
7324 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7325 Package *package([self packageAtIndexPath:path]);
7326 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7327 [view setDelegate:delegate_];
7328 [[self navigationController] pushViewController:view animated:YES];
7332 - (void) refreshButtonClicked {
7333 [delegate_ beginUpdate];
7334 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7337 - (void) upgradeButtonClicked {
7338 [delegate_ distUpgrade];
7342 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7344 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7345 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7346 [list_ setRowHeight:73];
7347 [list_ setDataSource:self];
7348 [list_ setDelegate:self];
7349 [[self view] addSubview:list_];
7352 - (void) viewDidLoad {
7353 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7356 - (void) releaseSubviews {
7361 - (id) initWithDatabase:(Database *)database {
7362 if ((self = [super init]) != nil) {
7363 database_ = database;
7365 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7366 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7370 // this mostly works because reloadData (below) is @synchronized (database_)
7371 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7372 - (void) _reloadPackages:(NSArray *)packages {
7373 CFRelease(packages_);
7374 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7377 _profile(ChangesController$_reloadPackages$Filter)
7378 for (Package *package in packages)
7379 if ([package upgradableAndEssential:YES] || [package visible])
7380 CFArrayAppendValue(packages_, package);
7383 _profile(ChangesController$_reloadPackages$radixSort)
7384 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7389 - (void) reloadData {
7390 @synchronized (database_) {
7391 era_ = [database_ era];
7392 NSArray *packages = [database_ packages];
7394 [sections_ removeAllObjects];
7397 UIProgressHUD *hud([delegate_ addProgressHUD]);
7398 [hud setText:UCLocalize("LOADING")];
7399 //NSLog(@"HUD:%@::%@", delegate_, hud);
7400 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7401 [delegate_ removeProgressHUD:hud];
7403 [self _reloadPackages:packages];
7406 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7407 Section *ignored = nil;
7408 Section *section = nil;
7412 bool unseens = false;
7414 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7416 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7417 Package *package = [self packageAtIndex:offset];
7419 BOOL uae = [package upgradableAndEssential:YES];
7423 time_t seen([package seen]);
7425 if (section == nil || last != seen) {
7429 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7432 _profile(ChangesController$reloadData$Allocate)
7433 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7434 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7435 [sections_ addObject:section];
7439 [section addToCount];
7440 } else if ([package ignored]) {
7441 if (ignored == nil) {
7442 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7444 [ignored addToCount];
7447 [upgradable addToCount];
7452 CFRelease(formatter);
7455 Section *last = [sections_ lastObject];
7456 size_t count = [last count];
7457 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7458 [sections_ removeLastObject];
7461 if ([ignored count] != 0)
7462 [sections_ insertObject:ignored atIndex:0];
7464 [sections_ insertObject:upgradable atIndex:0];
7469 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7470 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7471 style:UIBarButtonItemStylePlain
7473 action:@selector(upgradeButtonClicked)
7476 if (![delegate_ updating])
7477 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7478 initWithTitle:UCLocalize("REFRESH")
7479 style:UIBarButtonItemStylePlain
7481 action:@selector(refreshButtonClicked)
7489 /* Search Controller {{{ */
7490 @interface SearchController : FilteredPackageListController <
7493 UISearchBar *search_;
7497 - (id) initWithDatabase:(Database *)database;
7498 - (void) setSearchTerm:(NSString *)term;
7499 - (void) reloadData;
7503 @implementation SearchController
7510 - (NSURL *) navigationURL {
7511 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7512 return [NSURL URLWithString:@"cydia://search"];
7514 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7517 - (void) setSearchTerm:(NSString *)searchTerm {
7518 [search_ setText:searchTerm];
7522 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7523 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7524 [search_ resignFirstResponder];
7528 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7529 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7533 - (id) initWithDatabase:(Database *)database {
7534 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7535 search_ = [[UISearchBar alloc] init];
7539 - (void) viewDidAppear:(BOOL)animated {
7540 [super viewDidAppear:animated];
7542 if (!searchloaded_) {
7543 searchloaded_ = YES;
7544 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7545 [search_ layoutSubviews];
7546 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7548 UITextField *textField;
7549 if ([search_ respondsToSelector:@selector(searchField)])
7550 textField = [search_ searchField];
7552 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7554 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7555 [search_ setDelegate:self];
7556 [textField setEnablesReturnKeyAutomatically:NO];
7557 [[self navigationItem] setTitleView:textField];
7561 - (void) reloadData {
7562 [self setObject:[search_ text]];
7567 - (void) didSelectPackage:(Package *)package {
7568 [search_ resignFirstResponder];
7569 [super didSelectPackage:package];
7574 /* Package Settings Controller {{{ */
7575 @interface PackageSettingsController : CYViewController <
7576 UITableViewDataSource,
7579 _transient Database *database_;
7582 UITableView *table_;
7583 UISwitch *subscribedSwitch_;
7584 UISwitch *ignoredSwitch_;
7585 UITableViewCell *subscribedCell_;
7586 UITableViewCell *ignoredCell_;
7589 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7593 @implementation PackageSettingsController
7596 [self releaseSubviews];
7603 - (NSURL *) navigationURL {
7604 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7607 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7608 if (package_ == nil)
7611 if ([package_ installed] == nil)
7617 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7618 if (package_ == nil)
7621 // both sections contain just one item right now.
7625 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7629 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7631 return UCLocalize("SHOW_ALL_CHANGES_EX");
7633 return UCLocalize("IGNORE_UPGRADES_EX");
7636 - (void) onSubscribed:(id)control {
7637 bool value([control isOn]);
7638 if (package_ == nil)
7640 if ([package_ setSubscribed:value])
7641 [delegate_ updateData];
7644 - (void) _updateIgnored {
7645 const char *package([name_ UTF8String]);
7646 bool on([ignoredSwitch_ isOn]);
7648 pid_t pid(ExecFork());
7650 FILE *dpkg(popen("dpkg --set-selections", "w"));
7651 fwrite(package, strlen(package), 1, dpkg);
7654 fwrite(" hold\n", 6, 1, dpkg);
7656 fwrite(" install\n", 9, 1, dpkg);
7666 int result(waitpid(pid, &status, 0));
7669 _assert(result == pid);
7675 - (void) onIgnored:(id)control {
7676 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7677 [invocation setTarget:self];
7678 [invocation setSelector:@selector(_updateIgnored)];
7680 [delegate_ reloadDataWithInvocation:invocation];
7683 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7684 if (package_ == nil)
7687 switch ([indexPath section]) {
7688 case 0: return subscribedCell_;
7689 case 1: return ignoredCell_;
7698 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7700 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7701 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7702 [table_ setDataSource:self];
7703 [table_ setDelegate:self];
7704 [[self view] addSubview:table_];
7706 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7707 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7708 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7710 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7711 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7712 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7714 subscribedCell_ = [[UITableViewCell alloc] init];
7715 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7716 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7717 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7719 ignoredCell_ = [[UITableViewCell alloc] init];
7720 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7721 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7722 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7725 - (void) viewDidLoad {
7726 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7729 - (void) releaseSubviews {
7730 [ignoredCell_ release];
7733 [subscribedCell_ release];
7734 subscribedCell_ = nil;
7739 [ignoredSwitch_ release];
7740 ignoredSwitch_ = nil;
7742 [subscribedSwitch_ release];
7743 subscribedSwitch_ = nil;
7746 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7747 if ((self = [super init]) != nil) {
7748 database_ = database;
7749 name_ = [package retain];
7753 - (void) reloadData {
7756 if (package_ != nil)
7757 [package_ autorelease];
7758 package_ = [database_ packageWithName:name_];
7760 if (package_ != nil) {
7761 package_ = [package_ retain];
7762 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7763 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7764 } // XXX: what now, G?
7766 [table_ reloadData];
7772 /* Installed Controller {{{ */
7773 @interface InstalledController : FilteredPackageListController {
7777 - (id) initWithDatabase:(Database *)database;
7779 - (void) updateRoleButton;
7780 - (void) queueStatusDidChange;
7784 @implementation InstalledController
7790 - (NSURL *) navigationURL {
7791 return [NSURL URLWithString:@"cydia://installed"];
7794 - (id) initWithDatabase:(Database *)database {
7795 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7796 [self updateRoleButton];
7797 [self queueStatusDidChange];
7802 - (void) queueButtonClicked {
7807 - (void) queueStatusDidChange {
7811 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7812 initWithTitle:UCLocalize("QUEUE")
7813 style:UIBarButtonItemStyleDone
7815 action:@selector(queueButtonClicked)
7818 [[self navigationItem] setLeftBarButtonItem:nil];
7824 - (void) updateRoleButton {
7825 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7826 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7827 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7828 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7830 action:@selector(roleButtonClicked)
7834 - (void) roleButtonClicked {
7835 [self setObject:[NSNumber numberWithBool:expert_]];
7839 [self updateRoleButton];
7845 /* Source Cell {{{ */
7846 @interface SourceCell : CYTableViewCell <
7854 - (void) setSource:(Source *)source;
7858 @implementation SourceCell
7860 - (void) clearSource {
7870 - (void) setSource:(Source *)source {
7874 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7876 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7877 icon_ = [icon_ retain];
7879 origin_ = [[source name] retain];
7880 label_ = [[source uri] retain];
7882 [content_ setNeedsDisplay];
7890 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7891 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7892 UIView *content([self contentView]);
7893 CGRect bounds([content bounds]);
7895 content_ = [[ContentView alloc] initWithFrame:bounds];
7896 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7897 [content_ setBackgroundColor:[UIColor whiteColor]];
7898 [content addSubview:content_];
7900 [content_ setDelegate:self];
7901 [content_ setOpaque:YES];
7905 - (NSString *) accessibilityLabel {
7909 - (void) drawContentRect:(CGRect)rect {
7910 bool highlighted(highlighted_);
7911 float width(rect.size.width);
7914 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7921 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7925 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7930 /* Source Controller {{{ */
7931 @interface SourceController : FilteredPackageListController {
7932 _transient Source *source_;
7936 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7940 @implementation SourceController
7942 - (NSURL *) navigationURL {
7943 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7946 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7947 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7949 key_ = [[source key] retain];
7953 - (void) reloadData {
7954 source_ = [database_ sourceWithKey:key_];
7956 key_ = [[source_ key] retain];
7957 [self setObject:source_];
7958 [[self navigationItem] setTitle:[source_ label]];
7965 /* Sources Controller {{{ */
7966 @interface SourcesController : CYViewController <
7967 UITableViewDataSource,
7970 _transient Database *database_;
7972 NSMutableArray *sources_;
7976 UIProgressHUD *hud_;
7979 //NSURLConnection *installer_;
7980 NSURLConnection *trivial_;
7981 NSURLConnection *trivial_bz2_;
7982 NSURLConnection *trivial_gz_;
7983 //NSURLConnection *automatic_;
7988 - (id) initWithDatabase:(Database *)database;
7989 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7993 @implementation SourcesController
7995 - (void) _releaseConnection:(NSURLConnection *)connection {
7996 if (connection != nil) {
7997 [connection cancel];
7998 //[connection setDelegate:nil];
7999 [connection release];
8004 [self releaseSubviews];
8010 //[self _releaseConnection:installer_];
8011 [self _releaseConnection:trivial_];
8012 [self _releaseConnection:trivial_gz_];
8013 [self _releaseConnection:trivial_bz2_];
8014 //[self _releaseConnection:automatic_];
8020 - (NSURL *) navigationURL {
8021 return [NSURL URLWithString:@"cydia://sources"];
8024 - (void) viewDidAppear:(BOOL)animated {
8025 [super viewDidAppear:animated];
8026 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8029 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8030 return offset_ == 0 ? 1 : 2;
8033 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8034 switch (section + (offset_ == 0 ? 1 : 0)) {
8035 case 0: return UCLocalize("ENTERED_BY_USER");
8036 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8042 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8043 int count = [sources_ count];
8045 case 0: return (offset_ == 0 ? count : offset_);
8046 case 1: return count - offset_;
8052 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8054 switch (indexPath.section) {
8055 case 0: idx = indexPath.row; break;
8056 case 1: idx = indexPath.row + offset_; break;
8060 return [sources_ objectAtIndex:idx];
8063 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8064 static NSString *cellIdentifier = @"SourceCell";
8066 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8067 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8068 [cell setSource:[self sourceAtIndexPath:indexPath]];
8069 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8074 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8075 Source *source = [self sourceAtIndexPath:indexPath];
8077 SourceController *controller = [[[SourceController alloc]
8078 initWithDatabase:database_
8082 [controller setDelegate:delegate_];
8084 [[self navigationController] pushViewController:controller animated:YES];
8087 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8088 Source *source = [self sourceAtIndexPath:indexPath];
8089 return [source record] != nil;
8092 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8093 Source *source = [self sourceAtIndexPath:indexPath];
8094 [Sources_ removeObjectForKey:[source key]];
8095 [delegate_ syncData];
8099 [delegate_ addTrivialSource:href_];
8100 [delegate_ syncData];
8103 - (NSString *) getWarning {
8104 NSString *href(href_);
8105 NSRange colon([href rangeOfString:@"://"]);
8106 if (colon.location != NSNotFound)
8107 href = [href substringFromIndex:(colon.location + 3)];
8108 href = [href stringByAddingPercentEscapes];
8109 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8110 href = [href stringByCachingURLWithCurrentCDN];
8112 NSURL *url([NSURL URLWithString:href]);
8114 NSStringEncoding encoding;
8115 NSError *error(nil);
8117 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8118 return [warning length] == 0 ? nil : warning;
8122 - (void) _endConnection:(NSURLConnection *)connection {
8123 // XXX: the memory management in this method is horribly awkward
8125 NSURLConnection **field = NULL;
8126 if (connection == trivial_)
8128 else if (connection == trivial_bz2_)
8129 field = &trivial_bz2_;
8130 else if (connection == trivial_gz_)
8131 field = &trivial_gz_;
8132 _assert(field != NULL);
8133 [connection release];
8138 trivial_bz2_ == nil &&
8144 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8147 UIAlertView *alert = [[[UIAlertView alloc]
8148 initWithTitle:UCLocalize("SOURCE_WARNING")
8151 cancelButtonTitle:UCLocalize("CANCEL")
8153 UCLocalize("ADD_ANYWAY"),
8157 [alert setContext:@"warning"];
8158 [alert setNumberOfRows:1];
8162 } else if (error_ != nil) {
8163 UIAlertView *alert = [[[UIAlertView alloc]
8164 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8165 message:[error_ localizedDescription]
8167 cancelButtonTitle:UCLocalize("OK")
8168 otherButtonTitles:nil
8171 [alert setContext:@"urlerror"];
8174 UIAlertView *alert = [[[UIAlertView alloc]
8175 initWithTitle:UCLocalize("NOT_REPOSITORY")
8176 message:UCLocalize("NOT_REPOSITORY_EX")
8178 cancelButtonTitle:UCLocalize("OK")
8179 otherButtonTitles:nil
8182 [alert setContext:@"trivial"];
8186 [delegate_ setStatusBarShowsProgress:NO];
8187 [delegate_ removeProgressHUD:hud_];
8197 if (error_ != nil) {
8204 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8205 switch ([response statusCode]) {
8211 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8212 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8214 error_ = [error retain];
8215 [self _endConnection:connection];
8218 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8219 [self _endConnection:connection];
8222 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8223 NSMutableURLRequest *request = [NSMutableURLRequest
8224 requestWithURL:[NSURL URLWithString:href]
8225 cachePolicy:NSURLRequestUseProtocolCachePolicy
8226 timeoutInterval:120.0
8229 [request setHTTPMethod:method];
8231 if (Machine_ != NULL)
8232 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8233 if (UniqueID_ != nil)
8234 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8236 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8238 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8241 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8242 NSString *context([alert context]);
8244 if ([context isEqualToString:@"source"]) {
8247 NSString *href = [[alert textField] text];
8249 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8251 if (![href hasSuffix:@"/"])
8252 href_ = [href stringByAppendingString:@"/"];
8255 href_ = [href_ retain];
8257 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8258 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8259 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8260 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8264 // XXX: this is stupid
8265 hud_ = [[delegate_ addProgressHUD] retain];
8266 [hud_ setText:UCLocalize("VERIFYING_URL")];
8275 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8276 } else if ([context isEqualToString:@"trivial"])
8277 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8278 else if ([context isEqualToString:@"urlerror"])
8279 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8280 else if ([context isEqualToString:@"warning"]) {
8295 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8300 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8302 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8303 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8304 [list_ setRowHeight:56];
8305 [list_ setDataSource:self];
8306 [list_ setDelegate:self];
8307 [[self view] addSubview:list_];
8310 - (void) viewDidLoad {
8311 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8312 [self updateButtonsForEditingStatus:NO animated:NO];
8315 - (void) releaseSubviews {
8320 - (id) initWithDatabase:(Database *)database {
8321 if ((self = [super init]) != nil) {
8322 database_ = database;
8323 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8327 - (void) reloadData {
8331 if (!list.ReadMainList())
8334 [sources_ removeAllObjects];
8335 [sources_ addObjectsFromArray:[database_ sources]];
8337 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8340 int count([sources_ count]);
8342 for (int i = 0; i != count; i++) {
8343 if ([[sources_ objectAtIndex:i] record] == nil)
8348 [list_ setEditing:NO];
8349 [self updateButtonsForEditingStatus:NO animated:NO];
8353 - (void) showAddSourcePrompt {
8354 UIAlertView *alert = [[[UIAlertView alloc]
8355 initWithTitle:UCLocalize("ENTER_APT_URL")
8358 cancelButtonTitle:UCLocalize("CANCEL")
8360 UCLocalize("ADD_SOURCE"),
8364 [alert setContext:@"source"];
8365 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8367 [alert setNumberOfRows:1];
8368 [alert addTextFieldWithValue:@"http://" label:@""];
8370 UITextInputTraits *traits = [[alert textField] textInputTraits];
8371 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8372 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8373 [traits setKeyboardType:UIKeyboardTypeURL];
8374 // XXX: UIReturnKeyDone
8375 [traits setReturnKeyType:UIReturnKeyNext];
8380 - (void) addButtonClicked {
8381 [self showAddSourcePrompt];
8384 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8385 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8386 initWithTitle:UCLocalize("ADD")
8387 style:UIBarButtonItemStylePlain
8389 action:@selector(addButtonClicked)
8390 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8392 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8393 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8394 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8396 action:@selector(editButtonClicked)
8397 ] autorelease] animated:animated];
8399 if (IsWildcat_ && !editing)
8400 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8401 initWithTitle:UCLocalize("SETTINGS")
8402 style:UIBarButtonItemStylePlain
8404 action:@selector(settingsButtonClicked)
8408 - (void) settingsButtonClicked {
8409 [delegate_ showSettings];
8412 - (void) editButtonClicked {
8413 [list_ setEditing:![list_ isEditing] animated:YES];
8415 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8421 /* Settings Controller {{{ */
8422 @interface SettingsController : CYViewController <
8423 UITableViewDataSource,
8426 _transient Database *database_;
8427 // XXX: ok, "roledelegate_"?...
8428 _transient id roledelegate_;
8429 UITableView *table_;
8430 UISegmentedControl *segment_;
8434 - (void) showDoneButton;
8435 - (void) resizeSegmentedControl;
8439 @implementation SettingsController
8442 [self releaseSubviews];
8448 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8450 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8451 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8452 [table_ setDelegate:self];
8453 [table_ setDataSource:self];
8454 [[self view] addSubview:table_];
8456 NSArray *items = [NSArray arrayWithObjects:
8458 UCLocalize("HACKER"),
8459 UCLocalize("DEVELOPER"),
8461 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8462 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8463 [container_ addSubview:segment_];
8466 - (void) viewDidLoad {
8467 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8470 if ([Role_ isEqualToString:@"User"]) index = 0;
8471 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8472 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8474 [segment_ setSelectedSegmentIndex:index];
8475 [self showDoneButton];
8478 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8479 [self resizeSegmentedControl];
8482 - (void) releaseSubviews {
8489 [container_ release];
8493 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8494 if ((self = [super init]) != nil) {
8495 database_ = database;
8496 roledelegate_ = delegate;
8500 - (void) resizeSegmentedControl {
8501 CGFloat width = [[self view] frame].size.width;
8502 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8505 - (void) viewWillAppear:(BOOL)animated {
8506 [super viewWillAppear:animated];
8508 [self resizeSegmentedControl];
8511 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8512 [self resizeSegmentedControl];
8515 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8516 [self resizeSegmentedControl];
8520 NSString *role(nil);
8522 switch ([segment_ selectedSegmentIndex]) {
8523 case 0: role = @"User"; break;
8524 case 1: role = @"Hacker"; break;
8525 case 2: role = @"Developer"; break;
8530 if (![role isEqualToString:Role_]) {
8531 bool rolling(Role_ == nil);
8534 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8538 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8542 [roledelegate_ loadData];
8544 [roledelegate_ updateData];
8548 - (void) segmentChanged:(UISegmentedControl *)control {
8549 [self showDoneButton];
8552 - (void) saveAndClose {
8555 [[self navigationItem] setRightBarButtonItem:nil];
8556 [[self navigationController] dismissModalViewControllerAnimated:YES];
8559 - (void) doneButtonClicked {
8560 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8561 [spinner startAnimating];
8562 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8563 [[self navigationItem] setRightBarButtonItem:spinItem];
8565 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8568 - (void) showDoneButton {
8569 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8570 initWithTitle:UCLocalize("DONE")
8571 style:UIBarButtonItemStyleDone
8573 action:@selector(doneButtonClicked)
8574 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8577 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8578 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8582 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8586 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8587 return nil; // This method is required by the protocol.
8590 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8592 return UCLocalize("ROLE_EX");
8594 return [NSString stringWithFormat:
8595 @"%@: %@\n%@: %@\n%@: %@",
8596 UCLocalize("USER"), UCLocalize("USER_EX"),
8597 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8598 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8603 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8604 return section == 3 ? 44.0f : 0;
8607 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8608 return section == 3 ? container_ : nil;
8611 - (void) reloadData {
8613 [table_ reloadData];
8618 /* Stash Controller {{{ */
8619 @interface StashController : CYViewController {
8620 UIActivityIndicatorView *spinner_;
8627 @implementation StashController
8630 [self releaseSubviews];
8636 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8637 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8639 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8640 CGRect spinrect = [spinner_ frame];
8641 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8642 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8643 [spinner_ setFrame:spinrect];
8644 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8645 [[self view] addSubview:spinner_];
8646 [spinner_ startAnimating];
8649 captrect.size.width = [[self view] frame].size.width;
8650 captrect.size.height = 40.0f;
8651 captrect.origin.x = 0;
8652 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8653 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8654 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8655 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8656 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8657 [caption_ setTextColor:[UIColor whiteColor]];
8658 [caption_ setBackgroundColor:[UIColor clearColor]];
8659 [caption_ setShadowColor:[UIColor blackColor]];
8660 [caption_ setTextAlignment:UITextAlignmentCenter];
8661 [[self view] addSubview:caption_];
8664 statusrect.size.width = [[self view] frame].size.width;
8665 statusrect.size.height = 30.0f;
8666 statusrect.origin.x = 0;
8667 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8668 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8669 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8670 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8671 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8672 [status_ setTextColor:[UIColor whiteColor]];
8673 [status_ setBackgroundColor:[UIColor clearColor]];
8674 [status_ setShadowColor:[UIColor blackColor]];
8675 [status_ setTextAlignment:UITextAlignmentCenter];
8676 [[self view] addSubview:status_];
8679 - (void) releaseSubviews {
8693 @interface Cydia : UIApplication <
8694 ConfirmationControllerDelegate,
8695 ProgressControllerDelegate,
8697 UINavigationControllerDelegate,
8698 UITabBarControllerDelegate
8700 // XXX: evaluate all fields for _transient
8703 CYTabBarController *tabbar_;
8705 NSMutableArray *essential_;
8706 NSMutableArray *broken_;
8708 Database *database_;
8715 StashController *stash_;
8724 @implementation Cydia
8726 - (void) beginUpdate {
8727 [tabbar_ beginUpdate];
8731 return [tabbar_ updating];
8735 if ([broken_ count] != 0) {
8736 int count = [broken_ count];
8738 UIAlertView *alert = [[[UIAlertView alloc]
8739 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8740 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8742 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8744 UCLocalize("TEMPORARY_IGNORE"),
8748 [alert setContext:@"fixhalf"];
8750 } else if (!Ignored_ && [essential_ count] != 0) {
8751 int count = [essential_ count];
8753 UIAlertView *alert = [[[UIAlertView alloc]
8754 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8755 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8757 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8759 UCLocalize("UPGRADE_ESSENTIAL"),
8760 UCLocalize("COMPLETE_UPGRADE"),
8764 [alert setContext:@"upgrade"];
8769 - (void) _saveConfig {
8775 NSString *error(nil);
8777 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8779 NSError *error(nil);
8780 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8781 NSLog(@"failure to save metadata data: %@", error);
8786 NSLog(@"failure to serialize metadata: %@", error);
8791 // Navigation controller for the queuing badge.
8792 - (CYNavigationController *) queueNavigationController {
8793 NSArray *controllers = [tabbar_ viewControllers];
8794 return [controllers objectAtIndex:3];
8797 - (void) _updateData {
8800 [tabbar_ reloadData];
8802 CYNavigationController *navigation = [self queueNavigationController];
8804 id queuedelegate = nil;
8805 if ([[navigation viewControllers] count] > 0)
8806 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8808 [queuedelegate queueStatusDidChange];
8809 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8812 - (void) _refreshIfPossible:(NSDate *)update {
8813 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8815 bool recently = false;
8816 if (update != nil) {
8817 NSTimeInterval interval([update timeIntervalSinceNow]);
8818 if (interval <= 0 && interval > -(15*60))
8822 // Don't automatic refresh if:
8823 // - We already refreshed recently.
8824 // - We already auto-refreshed this launch.
8825 // - Auto-refresh is disabled.
8826 if (recently || loaded_ || ManualRefresh) {
8827 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8829 // If we are cancelling, we need to make sure it knows it's already loaded.
8833 // We are going to load, so remember that.
8837 SCNetworkReachabilityFlags flags; {
8838 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8839 SCNetworkReachabilityGetFlags(reachability, &flags);
8840 CFRelease(reachability);
8843 // XXX: this elaborate mess is what Apple is using to determine this? :(
8844 // XXX: do we care if the user has to intervene? maybe that's ok?
8846 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8847 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8848 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8849 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8850 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8851 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8855 // If we can reach the server, auto-refresh!
8857 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8862 - (void) refreshIfPossible {
8863 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8866 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8867 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8868 [hud setText:UCLocalize("RELOADING_DATA")];
8870 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8873 [self removeProgressHUD:hud];
8877 [essential_ removeAllObjects];
8878 [broken_ removeAllObjects];
8880 NSArray *packages([database_ packages]);
8881 for (Package *package in packages) {
8883 [broken_ addObject:package];
8884 if ([package upgradableAndEssential:NO]) {
8885 if ([package essential])
8886 [essential_ addObject:package];
8891 NSLog(@"changes:#%u", changes);
8893 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8896 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8897 [changesItem setBadgeValue:badge];
8898 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8899 [self setApplicationIconBadgeNumber:changes];
8902 [changesItem setBadgeValue:nil];
8903 [changesItem setAnimatedBadge:NO];
8904 [self setApplicationIconBadgeNumber:0];
8909 [self refreshIfPossible];
8912 - (void) updateData {
8923 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8924 _assert(file != NULL);
8926 for (NSString *key in [Sources_ allKeys]) {
8927 NSDictionary *source([Sources_ objectForKey:key]);
8929 fprintf(file, "%s %s %s\n",
8930 [[source objectForKey:@"Type"] UTF8String],
8931 [[source objectForKey:@"URI"] UTF8String],
8932 [[source objectForKey:@"Distribution"] UTF8String]
8938 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8939 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8941 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8942 [tabbar_ presentModalViewController:navigation animated:YES];
8945 detachNewThreadSelector:@selector(update_)
8948 title:UCLocalize("UPDATING_SOURCES")
8952 - (void) addTrivialSource:(NSString *)href {
8953 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8956 @"./", @"Distribution",
8957 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8962 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8963 @synchronized (self) {
8964 [self _reloadDataWithInvocation:invocation];
8968 - (void) reloadData {
8969 [self reloadDataWithInvocation:nil];
8973 pkgProblemResolver *resolver = [database_ resolver];
8975 resolver->InstallProtect();
8976 if (!resolver->Resolve(true))
8981 // XXX: this is a really crappy way of doing this.
8982 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8983 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8984 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8985 if ([tabbar_ updating])
8986 [tabbar_ cancelUpdate];
8988 if (![database_ prepare])
8991 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8992 [page setDelegate:self];
8993 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8994 [confirm_ setDelegate:self];
8997 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8998 [tabbar_ presentModalViewController:confirm_ animated:YES];
9004 @synchronized (self) {
9009 - (void) clearPackage:(Package *)package {
9010 @synchronized (self) {
9017 - (void) installPackages:(NSArray *)packages {
9018 @synchronized (self) {
9019 for (Package *package in packages)
9026 - (void) installPackage:(Package *)package {
9027 @synchronized (self) {
9034 - (void) removePackage:(Package *)package {
9035 @synchronized (self) {
9042 - (void) distUpgrade {
9043 @synchronized (self) {
9044 if (![database_ upgrade])
9051 @synchronized (self) {
9052 [self _reloadDataWithInvocation:nil];
9056 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9059 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
9061 if (navigation != nil) {
9062 [navigation pushViewController:progress animated:YES];
9064 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
9066 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9067 [tabbar_ presentModalViewController:navigation animated:YES];
9071 detachNewThreadSelector:@selector(perform)
9074 title:UCLocalize("RUNNING")
9080 - (void) progressControllerIsComplete:(ProgressController *)progress {
9085 - (void) showSettings {
9086 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9087 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9089 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9090 [tabbar_ presentModalViewController:nav animated:YES];
9093 - (void) retainNetworkActivityIndicator {
9094 if (activity_++ == 0)
9095 [self setNetworkActivityIndicatorVisible:YES];
9098 - (void) releaseNetworkActivityIndicator {
9099 if (--activity_ == 0)
9100 [self setNetworkActivityIndicatorVisible:NO];
9103 - (void) cancelAndClear:(bool)clear {
9104 @synchronized (self) {
9116 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9117 NSString *context([alert context]);
9119 if ([context isEqualToString:@"fixhalf"]) {
9120 if (button == [alert cancelButtonIndex]) {
9121 @synchronized (self) {
9122 for (Package *broken in broken_) {
9125 NSString *id = [broken id];
9126 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9127 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9128 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9129 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9135 } else if (button == [alert firstOtherButtonIndex]) {
9136 [broken_ removeAllObjects];
9140 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9141 } else if ([context isEqualToString:@"upgrade"]) {
9142 if (button == [alert firstOtherButtonIndex]) {
9143 @synchronized (self) {
9144 for (Package *essential in essential_)
9145 [essential install];
9150 } else if (button == [alert firstOtherButtonIndex] + 1) {
9152 } else if (button == [alert cancelButtonIndex]) {
9156 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9160 - (void) system:(NSString *)command { _pooled
9162 system([command UTF8String]);
9166 - (void) applicationWillSuspend {
9168 [super applicationWillSuspend];
9171 - (BOOL) isSafeToSuspend {
9172 // Use external process status API internally.
9173 // This is probably a really bad idea.
9174 // XXX: what is the point of this? does this solve anything at all?
9175 uint64_t status = 0;
9177 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9178 notify_get_state(notify_token, &status);
9179 notify_cancel(notify_token);
9182 return locked_ == 0 && status == 0;
9185 - (void) applicationSuspend:(__GSEvent *)event {
9186 if ([self isSafeToSuspend])
9187 [super applicationSuspend:event];
9190 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9191 if ([self isSafeToSuspend])
9192 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9195 - (void) _setSuspended:(BOOL)value {
9196 if ([self isSafeToSuspend])
9197 [super _setSuspended:value];
9200 - (UIProgressHUD *) addProgressHUD {
9201 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9202 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9204 [window_ setUserInteractionEnabled:NO];
9207 UIViewController *target = tabbar_;
9208 while ([target modalViewController] != nil) target = [target modalViewController];
9209 [[target view] addSubview:hud];
9215 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9217 [hud removeFromSuperview];
9218 [window_ setUserInteractionEnabled:YES];
9222 - (CYViewController *) pageForPackage:(NSString *)name {
9223 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9226 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9227 NSString *scheme([[url scheme] lowercaseString]);
9228 if ([[url absoluteString] length] <= [scheme length] + 3)
9230 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9231 NSArray *components([path pathComponents]);
9233 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9234 return [self pageForPackage:[components objectAtIndex:1]];
9236 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9239 NSString *base([components objectAtIndex:0]);
9241 CYViewController *controller = nil;
9243 if ([base isEqualToString:@"url"]) {
9244 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9245 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9246 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9247 } else if (!external && [components count] == 1) {
9248 if ([base isEqualToString:@"manage"]) {
9249 controller = [[[ManageController alloc] init] autorelease];
9252 if ([base isEqualToString:@"sources"]) {
9253 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9256 if ([base isEqualToString:@"home"]) {
9257 controller = [[[HomeController alloc] init] autorelease];
9260 if ([base isEqualToString:@"sections"]) {
9261 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9264 if ([base isEqualToString:@"search"]) {
9265 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9268 if ([base isEqualToString:@"changes"]) {
9269 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9272 if ([base isEqualToString:@"installed"]) {
9273 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9275 } else if ([components count] == 2) {
9276 NSString *argument = [components objectAtIndex:1];
9278 if ([base isEqualToString:@"package"]) {
9279 controller = [self pageForPackage:argument];
9282 if (!external && [base isEqualToString:@"search"]) {
9283 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9284 [(SearchController *)controller setSearchTerm:argument];
9287 if (!external && [base isEqualToString:@"sections"]) {
9288 if ([argument isEqualToString:@"all"])
9290 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9293 if (!external && [base isEqualToString:@"sources"]) {
9294 if ([argument isEqualToString:@"add"]) {
9295 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9296 [(SourcesController *)controller showAddSourcePrompt];
9298 Source *source = [database_ sourceWithKey:argument];
9299 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9303 if (!external && [base isEqualToString:@"launch"]) {
9304 [self launchApplicationWithIdentifier:argument suspended:NO];
9307 } else if (!external && [components count] == 3) {
9308 NSString *arg1 = [components objectAtIndex:1];
9309 NSString *arg2 = [components objectAtIndex:2];
9311 if ([base isEqualToString:@"package"]) {
9312 if ([arg2 isEqualToString:@"settings"]) {
9313 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9314 } else if ([arg2 isEqualToString:@"files"]) {
9315 if (Package *package = [database_ packageWithName:arg1]) {
9316 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9317 [(FileTable *)controller setPackage:package];
9323 [controller setDelegate:self];
9327 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9328 CYViewController *page([self pageForURL:url forExternal:external]);
9331 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9332 [nav setViewControllers:[NSArray arrayWithObject:page]];
9333 [tabbar_ setUnselectedViewController:nav];
9339 - (void) applicationOpenURL:(NSURL *)url {
9340 [super applicationOpenURL:url];
9342 if (!loaded_) starturl_ = [url retain];
9343 else [self openCydiaURL:url forExternal:YES];
9346 - (void) applicationWillResignActive:(UIApplication *)application {
9347 // Stop refreshing if you get a phone call or lock the device.
9348 if ([tabbar_ updating])
9349 [tabbar_ cancelUpdate];
9351 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9352 [super applicationWillResignActive:application];
9355 - (void) applicationWillTerminate:(UIApplication *)application {
9357 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9358 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9359 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9364 - (void) addStashController {
9366 stash_ = [[StashController alloc] init];
9367 [window_ addSubview:[stash_ view]];
9370 - (void) removeStashController {
9371 [[stash_ view] removeFromSuperview];
9377 [self setIdleTimerDisabled:YES];
9379 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9380 [self setStatusBarShowsProgress:YES];
9381 UpdateExternalStatus(1);
9383 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9385 UpdateExternalStatus(0);
9386 [self setStatusBarShowsProgress:NO];
9388 [self removeStashController];
9390 if (ExecFork() == 0) {
9391 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9392 perror("launchctl stop");
9396 - (void) setupViewControllers {
9397 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9399 NSMutableArray *items([NSMutableArray arrayWithObjects:
9400 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9401 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9402 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9403 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9407 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9408 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9410 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9413 NSMutableArray *controllers([NSMutableArray array]);
9414 for (UITabBarItem *item in items) {
9415 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9416 [controller setTabBarItem:item];
9417 [controllers addObject:controller];
9419 [tabbar_ setViewControllers:controllers];
9421 [tabbar_ setUpdateDelegate:self];
9424 - (CYEmulatedLoadingController *) showEmulatedLoadingControllerInView:(UIView *)view {
9425 static CYEmulatedLoadingController *fake = nil;
9429 fake = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9430 [view addSubview:[fake view]];
9432 [[fake view] removeFromSuperview];
9440 - (void) applicationDidFinishLaunching:(id)unused {
9444 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9445 [self setApplicationSupportsShakeToEdit:NO];
9447 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9448 initWithMemoryCapacity:524288
9449 diskCapacity:10485760
9450 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9453 [CYBrowserController _initialize];
9455 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9457 Font12_ = [[UIFont systemFontOfSize:12] retain];
9458 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9459 Font14_ = [[UIFont systemFontOfSize:14] retain];
9460 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9461 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9463 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9464 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9466 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9467 [window_ orderFront:self];
9468 [window_ makeKey:self];
9469 [window_ setHidden:NO];
9472 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9473 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9474 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9475 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9476 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9477 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9478 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9479 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9480 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9483 [self addStashController];
9484 // XXX: this would be much cleaner as a yieldToSelector:
9485 // that way the removeStashController could happen right here inline
9486 // we also could no longer require the useless stash_ field anymore
9487 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9491 database_ = [Database sharedInstance];
9493 [window_ setUserInteractionEnabled:NO];
9494 [self setupViewControllers];
9495 [self showEmulatedLoadingControllerInView:window_];
9497 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9504 [window_ setUserInteractionEnabled:YES];
9506 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9507 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9509 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9510 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9514 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9515 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9516 [window_ setUserInteractionEnabled:NO];
9522 [window_ addSubview:[tabbar_ view]];
9523 [self showEmulatedLoadingControllerInView:nil];
9524 [window_ setUserInteractionEnabled:YES];
9526 int selectedIndex = 0;
9527 NSMutableArray *items = nil;
9529 bool recently = false;
9530 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9531 if (closed != nil) {
9532 NSTimeInterval interval([closed timeIntervalSinceNow]);
9533 // XXX: Is 15 minutes the optimal time here?
9534 if (interval <= 0 && interval > -(15*60))
9538 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9539 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9542 for (NSArray *entry in items)
9543 if ([entry count] <= 0)
9546 if (!recently || !items || !enough) {
9548 items = [NSMutableArray array];
9549 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9550 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9551 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9553 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9555 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9556 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9558 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9561 [tabbar_ setSelectedIndex:selectedIndex];
9562 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9563 NSArray *stack = [items objectAtIndex:tab];
9564 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9565 NSMutableArray *current = [NSMutableArray array];
9567 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9568 NSString *addr = [stack objectAtIndex:nav];
9569 NSURL *url = [NSURL URLWithString:addr];
9570 CYViewController *page = [self pageForURL:url forExternal:NO];
9572 [current addObject:page];
9575 [navigation setViewControllers:current];
9578 // (Try to) show the startup URL.
9579 if (starturl_ != nil) {
9580 [self openCydiaURL:starturl_ forExternal:NO];
9581 [starturl_ release];
9586 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9587 if (item != nil && IsWildcat_) {
9588 [sheet showFromBarButtonItem:item animated:YES];
9590 [sheet showInView:window_];
9597 id Alloc_(id self, SEL selector) {
9598 id object = alloc_(self, selector);
9599 lprintf("[%s]A-%p\n", self->isa->name, object);
9604 id Dealloc_(id self, SEL selector) {
9605 id object = dealloc_(self, selector);
9606 lprintf("[%s]D-%p\n", self->isa->name, object);
9610 Class $WebDefaultUIKitDelegate;
9612 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9613 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9614 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9615 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9618 static NSNumber *shouldPlayKeyboardSounds;
9622 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9624 case 1104: // Keyboard Button Clicked
9625 case 1105: // Keyboard Delete Repeated
9626 if (shouldPlayKeyboardSounds == nil) {
9627 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9628 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9631 if (![shouldPlayKeyboardSounds boolValue])
9635 _UIHardware$_playSystemSound$(self, _cmd, sound);
9639 Class $UIApplication;
9641 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9642 static BOOL initialized = NO;
9643 static BOOL started = NO;
9645 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9646 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9648 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9649 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9650 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9651 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9653 if (initialized && !enabled) {
9655 [bundle performSelector:@selector(_accessibilityStopServer)];
9656 } else if (enabled) {
9660 [bundle performSelector:@selector(_accessibilityStartServer)];
9666 int main(int argc, char *argv[]) { _pooled
9669 UpdateExternalStatus(0);
9671 if (Class $UIDevice = objc_getClass("UIDevice")) {
9672 UIDevice *device([$UIDevice currentDevice]);
9673 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9677 UIScreen *screen([UIScreen mainScreen]);
9678 if ([screen respondsToSelector:@selector(scale)])
9679 ScreenScale_ = [screen scale];
9683 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9684 if (ScreenScale_ > 1)
9685 [parts addObject:@"@2x"];
9686 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9687 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9689 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9691 /* Library Hacks {{{ */
9692 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9694 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9695 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9696 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9697 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9698 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9701 $UIHardware = objc_getClass("UIHardware");
9702 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9703 if (UIHardware$_playSystemSound$ != NULL) {
9704 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9705 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9708 $UIApplication = objc_getClass("UIApplication");
9709 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9710 if (UIApplication$_updateApplicationAccessibility != NULL) {
9711 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9712 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9715 /* Set Locale {{{ */
9716 Locale_ = CFLocaleCopyCurrent();
9717 Languages_ = [NSLocale preferredLanguages];
9718 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9719 //NSLog(@"%@", [Languages_ description]);
9722 if (Languages_ == nil || [Languages_ count] == 0)
9723 // XXX: consider just setting to C and then falling through?
9726 lang = [[Languages_ objectAtIndex:0] UTF8String];
9727 setenv("LANG", lang, true);
9730 //std::setlocale(LC_ALL, lang);
9731 NSLog(@"Setting Language: %s", lang);
9734 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9736 /* Parse Arguments {{{ */
9737 bool substrate(false);
9743 for (int argi(1); argi != argc; ++argi)
9744 if (strcmp(argv[argi], "--") == 0) {
9746 argv[argi] = argv[0];
9752 for (int argi(1); argi != arge; ++argi)
9753 if (strcmp(args[argi], "--substrate") == 0)
9756 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9760 App_ = [[NSBundle mainBundle] bundlePath];
9761 Home_ = NSHomeDirectory();
9767 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9768 alloc_ = alloc->method_imp;
9769 alloc->method_imp = (IMP) &Alloc_;*/
9771 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9772 dealloc_ = dealloc->method_imp;
9773 dealloc->method_imp = (IMP) &Dealloc_;*/
9775 /* System Information {{{ */
9779 size = sizeof(maxproc);
9780 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9781 perror("sysctlbyname(\"kern.maxproc\", ?)");
9782 else if (maxproc < 64) {
9784 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9785 perror("sysctlbyname(\"kern.maxproc\", #)");
9788 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9789 char *osversion = new char[size];
9790 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9791 perror("sysctlbyname(\"kern.osversion\", ?)");
9793 System_ = [NSString stringWithUTF8String:osversion];
9795 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9796 char *machine = new char[size];
9797 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9798 perror("sysctlbyname(\"hw.machine\", ?)");
9802 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9803 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9804 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9805 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9809 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9810 NSData *data((NSData *) ecid);
9811 size_t length([data length]);
9812 uint8_t bytes[length];
9813 [data getBytes:bytes];
9814 char string[length * 2 + 1];
9815 for (size_t i(0); i != length; ++i)
9816 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9817 ChipID_ = [NSString stringWithUTF8String:string];
9821 IOObjectRelease(service);
9825 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9827 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9828 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9829 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9831 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9832 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9833 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9835 if (mcc != NULL && mnc != NULL)
9836 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9843 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9844 Build_ = [system objectForKey:@"ProductBuildVersion"];
9845 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9846 Product_ = [info objectForKey:@"SafariProductVersion"];
9847 Safari_ = [info objectForKey:@"CFBundleVersion"];
9850 /* Load Database {{{ */
9852 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9854 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9856 if (Metadata_ == NULL)
9857 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9859 Settings_ = [Metadata_ objectForKey:@"Settings"];
9861 Packages_ = [Metadata_ objectForKey:@"Packages"];
9862 Sections_ = [Metadata_ objectForKey:@"Sections"];
9863 Sources_ = [Metadata_ objectForKey:@"Sources"];
9865 Token_ = [Metadata_ objectForKey:@"Token"];
9868 if (Settings_ != nil)
9869 Role_ = [Settings_ objectForKey:@"Role"];
9871 if (Sections_ == nil) {
9872 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9873 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9876 if (Sources_ == nil) {
9877 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9878 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9883 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9886 if (Packages_ != nil) {
9888 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9892 [Metadata_ removeObjectForKey:@"Packages"];
9898 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9900 #define MobileSubstrate_(name) \
9901 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) \
9902 dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL);
9904 MobileSubstrate_(Activator)
9905 MobileSubstrate_(libstatusbar)
9906 MobileSubstrate_(SimulatedKeyEvents)
9907 MobileSubstrate_(WinterBoard)
9909 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9910 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9912 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9914 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9915 unlink("/tmp/.cydia.fw");
9917 } else if (access("/User", F_OK) != 0 || version < 2) {
9920 system("/usr/libexec/cydia/firmware.sh");
9924 _assert([[NSFileManager defaultManager]
9925 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9926 withIntermediateDirectories:YES
9931 if (access("/tmp/cydia.chk", F_OK) == 0) {
9932 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9933 _assert(errno == ENOENT);
9934 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9935 _assert(errno == ENOENT);
9938 /* APT Initialization {{{ */
9939 _assert(pkgInitConfig(*_config));
9940 _assert(pkgInitSystem(*_config, _system));
9943 _config->Set("APT::Acquire::Translation", lang);
9945 // XXX: this timeout might be important :(
9946 //_config->Set("Acquire::http::Timeout", 15);
9948 _config->Set("Acquire::http::MaxParallel", 3);
9950 /* Color Choices {{{ */
9951 space_ = CGColorSpaceCreateDeviceRGB();
9953 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9954 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9955 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9956 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9957 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9958 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9959 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9960 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9961 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9963 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9964 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9966 /* UIKit Configuration {{{ */
9967 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9968 if ($GSFontSetUseLegacyFontMetrics != NULL)
9969 $GSFontSetUseLegacyFontMetrics(YES);
9971 // XXX: I have a feeling this was important
9972 //UIKeyboardDisableAutomaticAppearance();
9975 Colon_ = UCLocalize("COLON_DELIMITED");
9976 Elision_ = UCLocalize("ELISION");
9977 Error_ = UCLocalize("ERROR");
9978 Warning_ = UCLocalize("WARNING");
9981 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9983 CGColorSpaceRelease(space_);