1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
122 #include <Cytore.hpp>
124 #include "UICaboodle/BrowserView.h"
125 #include "SDURLCache/SDURLCache.h"
127 #include "substrate.h"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
202 #define CYPoolStart() \
203 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
205 #define CYPoolEnd() \
209 // Hash Functions/Structures {{{
210 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
218 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
220 static _finline NSString *CydiaURL(NSString *path) {
222 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
223 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
224 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
225 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
226 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
227 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
230 static _finline void UpdateExternalStatus(uint64_t newStatus) {
232 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
233 notify_set_state(notify_token, newStatus);
234 notify_cancel(notify_token);
236 notify_post("com.saurik.Cydia.status");
239 /* [NSObject yieldToSelector:(withObject:)] {{{*/
240 @interface NSObject (Cydia)
241 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
242 - (id) yieldToSelector:(SEL)selector;
245 @implementation NSObject (Cydia)
250 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
251 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
252 id object([[context objectAtIndex:1] nonretainedObjectValue]);
253 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
255 /* XXX: deal with exceptions */
256 id value([self performSelector:selector withObject:object]);
258 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
259 [context removeAllObjects];
260 if ([signature methodReturnLength] != 0 && value != nil)
261 [context addObject:value];
266 performSelectorOnMainThread:@selector(doNothing)
272 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
273 volatile bool stopped(false);
275 NSMutableArray *context([NSMutableArray arrayWithObjects:
276 [NSValue valueWithPointer:selector],
277 [NSValue valueWithNonretainedObject:object],
278 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
281 NSThread *thread([[[NSThread alloc]
283 selector:@selector(_yieldToContext:)
289 NSRunLoop *loop([NSRunLoop currentRunLoop]);
290 NSDate *future([NSDate distantFuture]);
292 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
294 return [context count] == 0 ? nil : [context objectAtIndex:0];
297 - (id) yieldToSelector:(SEL)selector {
298 return [self yieldToSelector:selector withObject:nil];
304 /* Cydia Alert View {{{ */
305 @interface CYAlertView : UIAlertView {
309 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
313 @implementation CYAlertView
315 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
316 if ((self = [super init]) != nil) {
317 [self setTitle:title];
318 [self setDelegate:self];
319 for (NSString *button in buttons) [self addButtonWithTitle:button];
320 [self setCancelButtonIndex:index];
324 - (void) _updateFrameForDisplay {
325 [super _updateFrameForDisplay];
326 if ([self cancelButtonIndex] == -1) {
327 NSArray *buttons = [self buttons];
328 if ([buttons count]) {
329 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
330 for (UIThreePartButton *button in buttons)
331 [button setBackground:background forState:0];
336 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
337 button_ = buttonIndex + 1;
341 [self dismissWithClickedButtonIndex:-1 animated:YES];
344 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
345 [self setRunsModal:YES];
354 /* NSForcedOrderingSearch doesn't work on the iPhone */
355 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
356 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
357 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
359 #define lprintf(args...) fprintf(stderr, args)
362 #define TraceLogging (1 && !ForRelease)
363 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
364 #define ProfileTimes (0 && !ForRelease)
365 #define ForSaurik (0 && !ForRelease)
366 #define LogBrowser (0 && !ForRelease)
367 #define TrackResize (0 && !ForRelease)
368 #define ManualRefresh (1 && !ForRelease)
369 #define ShowInternals (0 && !ForRelease)
370 #define AlwaysReload (0 && !ForRelease)
371 #define TryIndexedCollation (0 && !ForRelease)
375 #define _trace(args...)
380 #define _profile(name) {
383 #define PrintTimes() do {} while (false)
387 typedef uint32_t (*SKRadixFunction)(id, void *);
389 @interface NSMutableArray (Radix)
390 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
398 @implementation NSMutableArray (Radix)
400 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
401 size_t count([self count]);
402 struct RadixItem_ *swap(new RadixItem_[count * 2]);
404 for (size_t i(0); i != count; ++i) {
405 RadixItem_ &item(swap[i]);
408 id object([self objectAtIndex:i]);
409 item.key = function(object, argument);
412 struct RadixItem_ *lhs(swap), *rhs(swap + count);
414 static const size_t width = 32;
415 static const size_t bits = 11;
416 static const size_t slots = 1 << bits;
417 static const size_t passes = (width + (bits - 1)) / bits;
419 size_t *hist(new size_t[slots]);
421 for (size_t pass(0); pass != passes; ++pass) {
422 memset(hist, 0, sizeof(size_t) * slots);
424 for (size_t i(0); i != count; ++i) {
425 uint32_t key(lhs[i].key);
427 key &= _not(uint32_t) >> width - bits;
432 for (size_t i(0); i != slots; ++i) {
433 size_t local(offset);
438 for (size_t i(0); i != count; ++i) {
439 uint32_t key(lhs[i].key);
441 key &= _not(uint32_t) >> width - bits;
442 rhs[hist[key]++] = lhs[i];
445 RadixItem_ *tmp(lhs);
452 const void **values(new const void *[count]);
453 for (size_t i(0); i != count; ++i)
454 values[i] = [self objectAtIndex:lhs[i].index];
455 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
463 /* Insertion Sort {{{ */
465 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
466 const char *ptr = (const char *)list;
468 CFIndex half = count / 2;
469 const char *probe = ptr + elementSize * half;
470 CFComparisonResult cr = comparator(element, probe, context);
471 if (0 == cr) return (probe - (const char *)list) / elementSize;
472 ptr = (cr < 0) ? ptr : probe + elementSize;
473 count = (cr < 0) ? half : (half + (count & 1) - 1);
475 return (ptr - (const char *)list) / elementSize;
478 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
479 const char *ptr = (const char *)list;
481 CFIndex half = count / 2;
482 const char *probe = ptr + elementSize * half;
483 CFComparisonResult cr = comparator(element, probe, context);
484 if (0 == cr) return (probe - (const char *)list) / elementSize;
485 ptr = (cr < 0) ? ptr : probe + elementSize;
486 count = (cr < 0) ? half : (half + (count & 1) - 1);
488 return (ptr - (const char *)list) / elementSize;
491 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
492 if (range.length == 0)
494 const void **values(new const void *[range.length]);
495 CFArrayGetValues(array, range, values);
497 #if HistogramInsertionSort > 0
498 uint32_t total(0), *offsets(new uint32_t[range.length]);
501 for (CFIndex index(1); index != range.length; ++index) {
502 const void *value(values[index]);
503 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
504 CFIndex correct(index);
505 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
506 #if HistogramInsertionSort > 1
507 NSLog(@"%@ < %@", value, values[correct - 1]);
512 if (correct != index) {
513 size_t offset(index - correct);
514 #if HistogramInsertionSort
518 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
520 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
521 values[correct] = value;
525 CFArrayReplaceValues(array, range, values, range.length);
528 #if HistogramInsertionSort > 0
529 for (CFIndex index(0); index != range.length; ++index)
530 if (offsets[index] != 0)
531 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
532 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
539 /* Apple Bug Fixes {{{ */
540 @implementation UIWebDocumentView (Cydia)
542 - (void) _setScrollerOffset:(CGPoint)offset {
543 UIScroller *scroller([self _scroller]);
545 CGSize size([scroller contentSize]);
546 CGSize bounds([scroller bounds].size);
549 max.x = size.width - bounds.width;
550 max.y = size.height - bounds.height;
558 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
559 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
561 [scroller setOffset:offset];
567 @implementation WebScriptObject (NSFastEnumeration)
569 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
570 size_t length([self count] - state->state);
573 else if (length > count)
575 for (size_t i(0); i != length; ++i)
576 objects[i] = [self objectAtIndex:state->state++];
577 state->itemsPtr = objects;
578 state->mutationsPtr = (unsigned long *) self;
584 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
585 size_t length([self length] - state->state);
588 else if (length > count)
590 for (size_t i(0); i != length; ++i)
591 objects[i] = [self item:state->state++];
592 state->itemsPtr = objects;
593 state->mutationsPtr = (unsigned long *) self;
597 /* Cydia NSString Additions {{{ */
598 @interface NSString (Cydia)
599 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
600 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
601 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
602 - (NSComparisonResult) compareByPath:(NSString *)other;
603 - (NSString *) stringByCachingURLWithCurrentCDN;
604 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
607 @implementation NSString (Cydia)
609 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
610 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
613 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
614 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
615 memcpy(data, bytes, length);
616 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
619 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
620 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
623 - (NSComparisonResult) compareByPath:(NSString *)other {
624 NSString *prefix = [self commonPrefixWithString:other options:0];
625 size_t length = [prefix length];
627 NSRange lrange = NSMakeRange(length, [self length] - length);
628 NSRange rrange = NSMakeRange(length, [other length] - length);
630 lrange = [self rangeOfString:@"/" options:0 range:lrange];
631 rrange = [other rangeOfString:@"/" options:0 range:rrange];
633 NSComparisonResult value;
635 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
636 value = NSOrderedSame;
637 else if (lrange.location == NSNotFound)
638 value = NSOrderedAscending;
639 else if (rrange.location == NSNotFound)
640 value = NSOrderedDescending;
642 value = NSOrderedSame;
644 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
645 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
646 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
647 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
649 NSComparisonResult result = [lpath compare:rpath];
650 return result == NSOrderedSame ? value : result;
653 - (NSString *) stringByCachingURLWithCurrentCDN {
655 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
656 withString:@"://cache.cydia.saurik.com/"
660 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
661 return [(id)CFURLCreateStringByAddingPercentEscapes(
666 kCFStringEncodingUTF8
673 /* C++ NSString Wrapper Cache {{{ */
674 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
675 return size == 0 ? NULL :
676 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
677 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
680 static _finline CFStringRef CYStringCreate(const char *data) {
681 return CYStringCreate(data, strlen(data));
690 _finline void clear_() {
691 if (cache_ != NULL) {
698 _finline bool empty() const {
702 _finline size_t size() const {
706 _finline char *data() const {
710 _finline void clear() {
715 _finline CYString() :
722 _finline ~CYString() {
726 void operator =(const CYString &rhs) {
730 if (rhs.cache_ == nil)
733 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
736 void copy(apr_pool_t *pool) {
737 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
738 memcpy(temp, data_, size_);
743 void set(apr_pool_t *pool, const char *data, size_t size) {
749 data_ = const_cast<char *>(data);
757 _finline void set(apr_pool_t *pool, const char *data) {
758 set(pool, data, data == NULL ? 0 : strlen(data));
761 _finline void set(apr_pool_t *pool, const std::string &rhs) {
762 set(pool, rhs.data(), rhs.size());
765 bool operator ==(const CYString &rhs) const {
766 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
769 _finline operator CFStringRef() {
771 cache_ = CYStringCreate(data_, size_);
775 _finline operator id() {
776 return (NSString *) static_cast<CFStringRef>(*this);
779 _finline operator const char *() {
780 return reinterpret_cast<const char *>(data_);
784 /* C++ NSString Algorithm Adapters {{{ */
786 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
789 struct NSStringMapHash :
790 std::unary_function<NSString *, size_t>
792 _finline size_t operator ()(NSString *value) const {
793 return CFStringHashNSString((CFStringRef) value);
797 struct NSStringMapLess :
798 std::binary_function<NSString *, NSString *, bool>
800 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
801 return [lhs compare:rhs] == NSOrderedAscending;
805 struct NSStringMapEqual :
806 std::binary_function<NSString *, NSString *, bool>
808 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
809 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
810 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
811 //[lhs isEqualToString:rhs];
816 /* Perl-Compatible RegEx {{{ */
826 Pcre(const char *regex) :
831 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
834 lprintf("%d:%s\n", offset, error);
838 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
839 matches_ = new int[(capture_ + 1) * 3];
847 NSString *operator [](size_t match) {
848 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
851 bool operator ()(NSString *data) {
852 // XXX: length is for characters, not for bytes
853 return operator ()([data UTF8String], [data length]);
856 bool operator ()(const char *data, size_t size) {
858 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
862 /* Mime Addresses {{{ */
863 @interface Address : NSObject {
869 - (NSString *) address;
871 - (void) setAddress:(NSString *)address;
873 + (Address *) addressWithString:(NSString *)string;
874 - (Address *) initWithString:(NSString *)string;
878 @implementation Address
887 - (NSString *) name {
891 - (NSString *) address {
895 - (void) setAddress:(NSString *)address {
897 [address_ autorelease];
901 address_ = [address retain];
904 + (Address *) addressWithString:(NSString *)string {
905 return [[[Address alloc] initWithString:string] autorelease];
908 + (NSArray *) _attributeKeys {
909 return [NSArray arrayWithObjects:
915 - (NSArray *) attributeKeys {
916 return [[self class] _attributeKeys];
919 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
920 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
923 - (Address *) initWithString:(NSString *)string {
924 if ((self = [super init]) != nil) {
925 const char *data = [string UTF8String];
926 size_t size = [string length];
928 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
930 if (address_r(data, size)) {
931 name_ = [address_r[1] retain];
932 address_ = [address_r[2] retain];
934 name_ = [string retain];
942 /* CoreGraphics Primitives {{{ */
947 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
948 CGFloat color[] = {red, green, blue, alpha};
949 return CGColorCreate(space, color);
958 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
959 color_(Create_(space, red, green, blue, alpha))
961 Set(space, red, green, blue, alpha);
966 CGColorRelease(color_);
973 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
975 color_ = Create_(space, red, green, blue, alpha);
978 operator CGColorRef() {
984 /* Random Global Variables {{{ */
985 static const int PulseInterval_ = 50000;
987 static const NSString *UI_;
990 static NSArray *Finishes_;
992 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
993 #define NotifyConfig_ "/etc/notify.conf"
995 static bool Queuing_;
997 static CYColor Blue_;
998 static CYColor Blueish_;
999 static CYColor Black_;
1000 static CYColor Off_;
1001 static CYColor White_;
1002 static CYColor Gray_;
1003 static CYColor Green_;
1004 static CYColor Purple_;
1005 static CYColor Purplish_;
1007 static UIColor *InstallingColor_;
1008 static UIColor *RemovingColor_;
1010 static NSString *App_;
1011 static NSString *Home_;
1013 static BOOL Advanced_;
1014 static BOOL Ignored_;
1016 static UIFont *Font12_;
1017 static UIFont *Font12Bold_;
1018 static UIFont *Font14_;
1019 static UIFont *Font18Bold_;
1020 static UIFont *Font22Bold_;
1022 static const char *Machine_ = NULL;
1023 static NSString *System_ = nil;
1024 static NSString *SerialNumber_ = nil;
1025 static NSString *ChipID_ = nil;
1026 static NSString *Token_ = nil;
1027 static NSString *UniqueID_ = nil;
1028 static NSString *PLMN_ = nil;
1029 static NSString *Build_ = nil;
1030 static NSString *Product_ = nil;
1031 static NSString *Safari_ = nil;
1033 static CFLocaleRef Locale_;
1034 static NSArray *Languages_;
1035 static CGColorSpaceRef space_;
1037 static NSDictionary *SectionMap_;
1038 static NSMutableDictionary *Metadata_;
1039 static _transient NSMutableDictionary *Settings_;
1040 static _transient NSString *Role_;
1041 static _transient NSMutableDictionary *Packages_;
1042 static _transient NSMutableDictionary *Sections_;
1043 static _transient NSMutableDictionary *Sources_;
1044 static bool Changed_;
1048 static CGFloat ScreenScale_;
1051 /* Display Helpers {{{ */
1052 inline float Interpolate(float begin, float end, float fraction) {
1053 return (end - begin) * fraction + begin;
1056 static _finline const char *StripVersion_(const char *version) {
1057 const char *colon(strchr(version, ':'));
1058 return colon == NULL ? version : colon + 1;
1061 NSString *LocalizeSection(NSString *section) {
1062 static Pcre title_r("^(.*?) \\((.*)\\)$");
1063 if (title_r(section)) {
1064 NSString *parent(title_r[1]);
1065 NSString *child(title_r[2]);
1067 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1068 LocalizeSection(parent),
1069 LocalizeSection(child)
1073 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1076 NSString *Simplify(NSString *title) {
1077 const char *data = [title UTF8String];
1078 size_t size = [title length];
1080 static Pcre square_r("^\\[(.*)\\]$");
1081 if (square_r(data, size))
1082 return Simplify(square_r[1]);
1084 static Pcre paren_r("^\\((.*)\\)$");
1085 if (paren_r(data, size))
1086 return Simplify(paren_r[1]);
1088 static Pcre title_r("^(.*?) \\((.*)\\)$");
1089 if (title_r(data, size))
1090 return Simplify(title_r[1]);
1096 NSString *GetLastUpdate() {
1097 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1100 return UCLocalize("NEVER_OR_UNKNOWN");
1102 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1103 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1105 CFRelease(formatter);
1107 return [(NSString *) formatted autorelease];
1110 bool isSectionVisible(NSString *section) {
1111 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1112 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1113 return hidden == nil || ![hidden boolValue];
1118 /* Delegate Prototypes {{{ */
1122 @interface NSObject (ProgressDelegate)
1125 @protocol ProgressDelegate
1126 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1127 - (void) setProgressTitle:(NSString *)title;
1128 - (void) setProgressPercent:(NSNumber *)percent;
1129 - (void) startProgress;
1130 - (void) addProgressOutput:(NSString *)output;
1131 - (bool) isCancelling:(size_t)received;
1134 @protocol ConfigurationDelegate
1135 - (void) repairWithSelector:(SEL)selector;
1136 - (void) setConfigurationData:(NSString *)data;
1139 @class CYPackageController;
1141 @protocol CydiaDelegate
1142 - (void) retainNetworkActivityIndicator;
1143 - (void) releaseNetworkActivityIndicator;
1144 - (void) clearPackage:(Package *)package;
1145 - (void) installPackage:(Package *)package;
1146 - (void) installPackages:(NSArray *)packages;
1147 - (void) removePackage:(Package *)package;
1148 - (void) beginUpdate;
1150 - (void) distUpgrade;
1152 - (void) updateData;
1154 - (void) addTrivialSource:(NSString *)href;
1155 - (void) showSettings;
1156 - (UIProgressHUD *) addProgressHUD;
1157 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1158 - (CYViewController *) pageForPackage:(NSString *)name;
1159 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1160 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1163 static id<CydiaDelegate> CydiaApp;
1166 /* Status Delegation {{{ */
1168 public pkgAcquireStatus
1171 _transient NSObject<ProgressDelegate> *delegate_;
1179 void setDelegate(id delegate) {
1180 delegate_ = delegate;
1183 NSObject<ProgressDelegate> *getDelegate() const {
1187 virtual bool MediaChange(std::string media, std::string drive) {
1191 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1194 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1195 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1197 performSelectorOnMainThread:@selector(setProgressTitle:)
1198 withObject:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]
1203 virtual void Done(pkgAcquire::ItemDesc &item) {
1206 virtual void Fail(pkgAcquire::ItemDesc &item) {
1208 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1209 item.Owner->Status == pkgAcquire::Item::StatDone
1213 std::string &error(item.Owner->ErrorText);
1217 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1218 NSArray *fields([description componentsSeparatedByString:@" "]);
1219 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1221 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1222 withObject:[NSArray arrayWithObjects:
1223 [NSString stringWithUTF8String:error.c_str()],
1230 virtual bool Pulse(pkgAcquire *Owner) {
1231 bool value = pkgAcquireStatus::Pulse(Owner);
1234 double(CurrentBytes + CurrentItems) /
1235 double(TotalBytes + TotalItems)
1238 [delegate_ setProgressPercent:[NSNumber numberWithFloat:percent]];
1239 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1242 virtual void Start() {
1243 [delegate_ startProgress];
1246 virtual void Stop() {
1250 /* Progress Delegation {{{ */
1255 _transient id<ProgressDelegate> delegate_;
1259 virtual void Update() {
1260 /*if (abs(Percent - percent_) > 2)
1261 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1265 //[delegate_ performSelectorOnMainThread:@selector(setProgressTitle:) withObject:[NSString stringWithUTF8String:Op.c_str()] waitUntilDone:YES];
1266 //[delegate_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(Percent / 100)] waitUntilDone:YES];
1276 void setDelegate(id delegate) {
1277 delegate_ = delegate;
1280 id getDelegate() const {
1284 virtual void Done() {
1286 //[delegate_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:1] waitUntilDone:YES];
1291 /* Database Interface {{{ */
1292 typedef std::map< unsigned long, _H<Source> > SourceMap;
1294 @interface Database : NSObject {
1300 pkgCacheFile cache_;
1301 pkgDepCache::Policy *policy_;
1302 pkgRecords *records_;
1303 pkgProblemResolver *resolver_;
1304 pkgAcquire *fetcher_;
1306 SPtr<pkgPackageManager> manager_;
1307 pkgSourceList *list_;
1309 SourceMap sourceMap_;
1310 NSMutableArray *sourceList_;
1312 CFMutableArrayRef packages_;
1314 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1322 std::map<const char *, _H<NSString> > sections_;
1325 + (Database *) sharedInstance;
1328 - (void) _readCydia:(NSNumber *)fd;
1329 - (void) _readStatus:(NSNumber *)fd;
1330 - (void) _readOutput:(NSNumber *)fd;
1334 - (Package *) packageWithName:(NSString *)name;
1336 - (pkgCacheFile &) cache;
1337 - (pkgDepCache::Policy *) policy;
1338 - (pkgRecords *) records;
1339 - (pkgProblemResolver *) resolver;
1340 - (pkgAcquire &) fetcher;
1341 - (pkgSourceList &) list;
1342 - (NSArray *) packages;
1343 - (NSArray *) sources;
1344 - (Source *) sourceWithKey:(NSString *)key;
1345 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1353 - (void) updateWithStatus:(Status &)status;
1355 - (void) setDelegate:(id)delegate;
1356 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1358 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1362 /* Delegate Helpers {{{ */
1363 @implementation NSObject (ProgressDelegate)
1365 - (void) _setProgressErrorPackage:(NSArray *)args {
1366 [self performSelector:@selector(setProgressError:forPackage:)
1367 withObject:[args objectAtIndex:0]
1368 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1372 - (void) _setProgressErrorTitle:(NSArray *)args {
1373 [self performSelector:@selector(setProgressError:withTitle:)
1374 withObject:[args objectAtIndex:0]
1375 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1379 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1380 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1381 withObject:[NSArray arrayWithObjects:error, title, nil]
1386 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1387 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1389 [self performSelector:@selector(setProgressError:withTitle:)
1391 withObject:(package == nil ? id : [package name])
1398 // Cytore Definitions {{{
1399 struct PackageValue :
1402 Cytore::Offset<PackageValue> next_;
1404 uint32_t index_ : 23;
1405 uint32_t subscribed_ : 1;
1422 Cytore::Offset<PackageValue> packages_[1 << 16];
1425 static Cytore::File<MetaValue> MetaFile_;
1427 // Cytore Helper Functions {{{
1428 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1429 SplitHash nhash = { hashlittle(name, length) };
1431 PackageValue *metadata;
1433 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1434 offset: if (offset->IsNull()) {
1435 *offset = MetaFile_.New<PackageValue>(length + 1);
1436 metadata = &MetaFile_.Get(*offset);
1438 if (metadata == NULL) {
1442 metadata = new PackageValue();
1443 memset(metadata, 0, sizeof(*metadata));
1446 memcpy(metadata->name_, name, length + 1);
1447 metadata->nhash_ = nhash.u16[1];
1449 metadata = &MetaFile_.Get(*offset);
1451 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1452 offset = &metadata->next_;
1460 static void PackageImport(const void *key, const void *value, void *context) {
1461 bool &fail(*reinterpret_cast<bool *>(context));
1464 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1465 NSLog(@"failed to import package %@", key);
1469 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1470 NSDictionary *package((NSDictionary *) value);
1472 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1473 if ([subscribed boolValue] && !metadata->subscribed_)
1474 metadata->subscribed_ = true;
1476 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1477 time_t time([date timeIntervalSince1970]);
1478 if (metadata->first_ > time || metadata->first_ == 0)
1479 metadata->first_ = time;
1482 NSDate *date([package objectForKey:@"LastSeen"]);
1483 NSString *version([package objectForKey:@"LastVersion"]);
1485 if (date != nil && version != nil) {
1486 time_t time([date timeIntervalSince1970]);
1487 if (metadata->last_ < time || metadata->last_ == 0)
1488 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1489 size_t length(strlen(buffer));
1490 uint16_t vhash(hashlittle(buffer, length));
1492 size_t capped(std::min<size_t>(8, length));
1493 char *latest(buffer + length - capped);
1495 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1496 metadata->vhash_ = vhash;
1498 metadata->last_ = time;
1504 /* Source Class {{{ */
1505 @interface Source : NSObject {
1506 CYString depiction_;
1507 CYString description_;
1513 CYString distribution_;
1518 NSString *authority_;
1520 CYString defaultIcon_;
1522 NSDictionary *record_;
1526 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1528 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1530 - (NSString *) depictionForPackage:(NSString *)package;
1531 - (NSString *) supportForPackage:(NSString *)package;
1533 - (NSDictionary *) record;
1537 - (NSString *) distribution;
1538 - (NSString *) type;
1540 - (NSString *) host;
1542 - (NSString *) name;
1543 - (NSString *) description;
1544 - (NSString *) label;
1545 - (NSString *) origin;
1546 - (NSString *) version;
1548 - (NSString *) defaultIcon;
1552 @implementation Source
1556 distribution_.clear();
1559 description_.clear();
1565 defaultIcon_.clear();
1567 if (record_ != nil) {
1577 if (authority_ != nil) {
1578 [authority_ release];
1584 // XXX: this is a very inefficient way to call these deconstructors
1589 + (NSArray *) _attributeKeys {
1590 return [NSArray arrayWithObjects:
1605 - (NSArray *) attributeKeys {
1606 return [[self class] _attributeKeys];
1609 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1610 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1613 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1616 trusted_ = index->IsTrusted();
1618 uri_.set(pool, index->GetURI());
1619 distribution_.set(pool, index->GetDist());
1620 type_.set(pool, index->GetType());
1622 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1623 if (dindex != NULL) {
1625 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1628 pkgTagFile tags(&fd);
1630 pkgTagSection section;
1637 {"default-icon", &defaultIcon_},
1638 {"depiction", &depiction_},
1639 {"description", &description_},
1641 {"origin", &origin_},
1642 {"support", &support_},
1643 {"version", &version_},
1646 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1647 const char *start, *end;
1649 if (section.Find(names[i].name_, start, end)) {
1650 CYString &value(*names[i].value_);
1651 value.set(pool, start, end - start);
1657 record_ = [Sources_ objectForKey:[self key]];
1659 record_ = [record_ retain];
1661 NSURL *url([NSURL URLWithString:uri_]);
1665 host_ = [[host_ lowercaseString] retain];
1670 authority_ = [url path];
1672 if (authority_ != nil)
1673 authority_ = [authority_ retain];
1676 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1677 if ((self = [super init]) != nil) {
1678 [self setMetaIndex:index inPool:pool];
1682 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1683 NSDictionary *lhr = [self record];
1684 NSDictionary *rhr = [source record];
1687 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1689 NSString *lhs = [self name];
1690 NSString *rhs = [source name];
1692 if ([lhs length] != 0 && [rhs length] != 0) {
1693 unichar lhc = [lhs characterAtIndex:0];
1694 unichar rhc = [rhs characterAtIndex:0];
1696 if (isalpha(lhc) && !isalpha(rhc))
1697 return NSOrderedAscending;
1698 else if (!isalpha(lhc) && isalpha(rhc))
1699 return NSOrderedDescending;
1702 return [lhs compare:rhs options:LaxCompareOptions_];
1705 - (NSString *) depictionForPackage:(NSString *)package {
1706 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1709 - (NSString *) supportForPackage:(NSString *)package {
1710 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1713 - (NSDictionary *) record {
1721 - (NSString *) uri {
1725 - (NSString *) distribution {
1726 return distribution_;
1729 - (NSString *) type {
1733 - (NSString *) key {
1734 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1737 - (NSString *) host {
1741 - (NSString *) name {
1742 return origin_.empty() ? authority_ : origin_;
1745 - (NSString *) description {
1746 return description_;
1749 - (NSString *) label {
1750 return label_.empty() ? authority_ : label_;
1753 - (NSString *) origin {
1757 - (NSString *) version {
1761 - (NSString *) defaultIcon {
1762 return defaultIcon_;
1767 /* CydiaOperation Class {{{ */
1768 @interface CydiaOperation : NSObject {
1769 NSString *operator_;
1773 - (NSString *) operator;
1774 - (NSString *) value;
1778 @implementation CydiaOperation
1781 [operator_ release];
1786 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1787 if ((self = [super init]) != nil) {
1788 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1789 value_ = [[NSString alloc] initWithUTF8String:value];
1793 + (NSArray *) _attributeKeys {
1794 return [NSArray arrayWithObjects:
1800 - (NSArray *) attributeKeys {
1801 return [[self class] _attributeKeys];
1804 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1805 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1808 - (NSString *) operator {
1812 - (NSString *) value {
1818 /* CydiaClause Class {{{ */
1819 @interface CydiaClause : NSObject {
1821 CydiaOperation *version_;
1824 - (NSString *) package;
1825 - (CydiaOperation *) version;
1829 @implementation CydiaClause
1837 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1838 if ((self = [super init]) != nil) {
1839 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1841 if (const char *version = dep.TargetVer())
1842 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1844 version_ = [[NSNull null] retain];
1848 + (NSArray *) _attributeKeys {
1849 return [NSArray arrayWithObjects:
1855 - (NSArray *) attributeKeys {
1856 return [[self class] _attributeKeys];
1859 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1860 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1863 - (NSString *) package {
1867 - (CydiaOperation *) version {
1873 /* CydiaRelation Class {{{ */
1874 @interface CydiaRelation : NSObject {
1875 NSString *relationship_;
1876 NSMutableArray *clauses_;
1879 - (NSString *) relationship;
1880 - (NSArray *) clauses;
1884 @implementation CydiaRelation
1887 [relationship_ release];
1892 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1893 if ((self = [super init]) != nil) {
1894 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1895 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1897 pkgCache::DepIterator start;
1898 pkgCache::DepIterator end;
1899 dep.GlobOr(start, end); // ++dep
1902 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1904 // yes, seriously. (wtf?)
1912 + (NSArray *) _attributeKeys {
1913 return [NSArray arrayWithObjects:
1919 - (NSArray *) attributeKeys {
1920 return [[self class] _attributeKeys];
1923 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1924 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1927 - (NSString *) relationship {
1928 return relationship_;
1931 - (NSArray *) clauses {
1935 - (void) addClause:(CydiaClause *)clause {
1936 [clauses_ addObject:clause];
1941 /* Package Class {{{ */
1942 struct ParsedPackage {
1947 CYString depiction_;
1957 @interface Package : NSObject {
1960 uint32_t essential_ : 1;
1961 uint32_t obsolete_ : 1;
1962 uint32_t ignored_ : 1;
1966 _transient Database *database_;
1968 pkgCache::VerIterator version_;
1969 pkgCache::PkgIterator iterator_;
1970 pkgCache::VerFileIterator file_;
1976 CYString installed_;
1978 const char *section_;
1979 _transient NSString *section$_;
1983 PackageValue *metadata_;
1984 ParsedPackage *parsed_;
1986 NSMutableArray *tags_;
1989 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1990 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1992 - (pkgCache::PkgIterator) iterator;
1995 - (NSString *) section;
1996 - (NSString *) simpleSection;
1998 - (NSString *) longSection;
1999 - (NSString *) shortSection;
2003 - (Address *) maintainer;
2005 - (NSString *) longDescription;
2006 - (NSString *) shortDescription;
2009 - (PackageValue *) metadata;
2012 - (bool) subscribed;
2013 - (bool) setSubscribed:(bool)subscribed;
2017 - (NSString *) latest;
2018 - (NSString *) installed;
2019 - (BOOL) uninstalled;
2022 - (BOOL) upgradableAndEssential:(BOOL)essential;
2025 - (BOOL) unfiltered;
2029 - (BOOL) halfConfigured;
2030 - (BOOL) halfInstalled;
2032 - (NSString *) mode;
2035 - (NSString *) name;
2037 - (NSString *) homepage;
2038 - (NSString *) depiction;
2039 - (Address *) author;
2041 - (NSString *) support;
2043 - (NSArray *) files;
2044 - (NSArray *) warnings;
2045 - (NSArray *) applications;
2047 - (Source *) source;
2049 - (BOOL) matches:(NSString *)text;
2051 - (bool) hasSupportingRole;
2052 - (BOOL) hasTag:(NSString *)tag;
2053 - (NSString *) primaryPurpose;
2054 - (NSArray *) purposes;
2055 - (bool) isCommercial;
2057 - (void) setIndex:(size_t)index;
2059 - (CYString &) cyname;
2061 - (uint32_t) compareBySection:(NSArray *)sections;
2066 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2067 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2068 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2069 - (bool) isVisibleInSection:(NSString *)section;
2070 - (bool) isVisibleInSource:(Source *)source;
2074 uint32_t PackageChangesRadix(Package *self, void *) {
2079 uint32_t timestamp : 30;
2080 uint32_t ignored : 1;
2081 uint32_t upgradable : 1;
2085 bool upgradable([self upgradableAndEssential:YES]);
2086 value.bits.upgradable = upgradable ? 1 : 0;
2089 value.bits.timestamp = 0;
2090 value.bits.ignored = [self ignored] ? 0 : 1;
2091 value.bits.upgradable = 1;
2093 value.bits.timestamp = [self seen] >> 2;
2094 value.bits.ignored = 0;
2095 value.bits.upgradable = 0;
2098 return _not(uint32_t) - value.key;
2101 uint32_t PackagePrefixRadix(Package *self, void *context) {
2102 size_t offset(reinterpret_cast<size_t>(context));
2103 CYString &name([self cyname]);
2105 size_t size(name.size());
2108 char *text(name.data());
2111 if (!isdigit(text[0]))
2115 while (size != digits && isdigit(text[digits]))
2123 if (offset == 0 && zeros != 0) {
2124 memset(data, '0', zeros);
2125 memcpy(data + zeros, text, 4 - zeros);
2127 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2128 if (size <= offset - zeros)
2131 text += offset - zeros;
2132 size -= offset - zeros;
2135 memcpy(data, text, 4);
2137 memcpy(data, text, size);
2138 memset(data + size, 0, 4 - size);
2141 for (size_t i(0); i != 4; ++i)
2142 if (isalpha(data[i]))
2150 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2152 /* XXX: ntohl may be more honest */
2153 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2156 CYString &(*PackageName)(Package *self, SEL sel);
2158 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2159 _profile(PackageNameCompare)
2160 CYString &lhi(PackageName(lhs, @selector(cyname)));
2161 CYString &rhi(PackageName(rhs, @selector(cyname)));
2162 CFStringRef lhn(lhi), rhn(rhi);
2165 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2166 else if (rhn == NULL)
2167 return NSOrderedDescending;
2169 _profile(PackageNameCompare$NumbersLast)
2170 if (!lhi.empty() && !rhi.empty()) {
2171 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2172 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2173 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2174 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2175 return lha ? NSOrderedAscending : NSOrderedDescending;
2179 CFIndex length = CFStringGetLength(lhn);
2181 _profile(PackageNameCompare$Compare)
2182 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2187 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2188 return PackageNameCompare(*lhs, *rhs, context);
2191 struct PackageNameOrdering :
2192 std::binary_function<Package *, Package *, bool>
2194 _finline bool operator ()(Package *lhs, Package *rhs) const {
2195 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2199 @implementation Package
2201 - (NSString *) description {
2202 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2206 if (parsed_ != NULL)
2215 + (NSString *) webScriptNameForSelector:(SEL)selector {
2217 else if (selector == @selector(clear))
2219 else if (selector == @selector(hasTag:))
2221 else if (selector == @selector(install))
2223 else if (selector == @selector(remove))
2229 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2230 return [self webScriptNameForSelector:selector] == nil;
2233 + (NSArray *) _attributeKeys {
2234 return [NSArray arrayWithObjects:
2252 @"shortDescription",
2263 - (NSArray *) attributeKeys {
2264 return [[self class] _attributeKeys];
2267 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2268 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2271 - (NSArray *) relations {
2272 @synchronized (database_) {
2273 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2274 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2275 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2280 if (parsed_ != NULL)
2282 @synchronized (database_) {
2283 if ([database_ era] != era_ || file_.end())
2286 ParsedPackage *parsed(new ParsedPackage);
2289 _profile(Package$parse)
2290 pkgRecords::Parser *parser;
2292 _profile(Package$parse$Lookup)
2293 parser = &[database_ records]->Lookup(file_);
2298 _profile(Package$parse$Find)
2303 {"icon", &parsed->icon_},
2304 {"depiction", &parsed->depiction_},
2305 {"homepage", &parsed->homepage_},
2306 {"website", &website},
2307 {"bugs", &parsed->bugs_},
2308 {"support", &parsed->support_},
2309 {"sponsor", &parsed->sponsor_},
2310 {"author", &parsed->author_},
2313 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2314 const char *start, *end;
2316 if (parser->Find(names[i].name_, start, end)) {
2317 CYString &value(*names[i].value_);
2318 _profile(Package$parse$Value)
2319 value.set(pool_, start, end - start);
2325 _profile(Package$parse$Tagline)
2326 const char *start, *end;
2327 if (parser->ShortDesc(start, end)) {
2328 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2331 while (stop != start && stop[-1] == '\r')
2333 parsed->tagline_.set(pool_, start, stop - start);
2337 _profile(Package$parse$Retain)
2338 if (parsed->homepage_.empty())
2339 parsed->homepage_ = website;
2340 if (parsed->homepage_ == parsed->depiction_)
2341 parsed->homepage_.clear();
2346 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2347 if ((self = [super init]) != nil) {
2348 _profile(Package$initWithVersion)
2351 database_ = database;
2352 era_ = [database era];
2356 pkgCache::PkgIterator iterator(version.ParentPkg());
2357 iterator_ = iterator;
2359 _profile(Package$initWithVersion$Version)
2360 if (!version_.end())
2361 file_ = version_.FileList();
2363 pkgCache &cache([database_ cache]);
2364 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2368 _profile(Package$initWithVersion$Cache)
2369 name_.set(NULL, iterator.Display());
2371 latest_.set(NULL, StripVersion_(version_.VerStr()));
2373 pkgCache::VerIterator current(iterator.CurrentVer());
2375 installed_.set(NULL, StripVersion_(current.VerStr()));
2378 _profile(Package$initWithVersion$Tags)
2379 pkgCache::TagIterator tag(iterator.TagList());
2381 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2383 const char *name(tag.Name());
2384 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2386 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2387 if (strcmp(name + 6, "enduser") == 0)
2389 else if (strcmp(name + 6, "hacker") == 0)
2391 else if (strcmp(name + 6, "developer") == 0)
2393 else if (strcmp(name + 6, "cydia") == 0)
2399 if (strncmp(name, "cydia::", 7) == 0) {
2400 if (strcmp(name + 7, "essential") == 0)
2402 else if (strcmp(name + 7, "obsolete") == 0)
2407 } while (!tag.end());
2411 _profile(Package$initWithVersion$Metadata)
2412 const char *mixed(iterator.Name());
2413 size_t size(strlen(mixed));
2414 char lower[size + 1];
2416 for (size_t i(0); i != size; ++i)
2417 lower[i] = mixed[i] | 0x20;
2420 PackageValue *metadata(PackageFind(lower, size));
2421 metadata_ = metadata;
2423 id_.set(NULL, metadata->name_, size);
2425 const char *latest(version_.VerStr());
2426 size_t length(strlen(latest));
2428 uint16_t vhash(hashlittle(latest, length));
2430 size_t capped(std::min<size_t>(8, length));
2431 latest = latest + length - capped;
2433 if (metadata->first_ == 0)
2434 metadata->first_ = now_;
2436 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2437 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2438 metadata->vhash_ = vhash;
2439 metadata->last_ = now_;
2440 } else if (metadata->last_ == 0)
2441 metadata->last_ = metadata->first_;
2444 _profile(Package$initWithVersion$Section)
2445 section_ = iterator.Section();
2448 _profile(Package$initWithVersion$Flags)
2449 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2450 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2455 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2456 pkgCache::VerIterator version;
2458 _profile(Package$packageWithIterator$GetCandidateVer)
2459 version = [database policy]->GetCandidateVer(iterator);
2467 _profile(Package$packageWithIterator$Allocate)
2468 package = [Package allocWithZone:zone];
2471 _profile(Package$packageWithIterator$Initialize)
2473 initWithVersion:version
2480 _profile(Package$packageWithIterator$Autorelease)
2481 package = [package autorelease];
2487 - (pkgCache::PkgIterator) iterator {
2491 - (NSString *) section {
2492 if (section$_ == nil) {
2493 if (section_ == NULL)
2496 _profile(Package$section$mappedSectionForPointer)
2497 section$_ = [database_ mappedSectionForPointer:section_];
2502 - (NSString *) simpleSection {
2503 if (NSString *section = [self section])
2504 return Simplify(section);
2509 - (NSString *) longSection {
2510 return LocalizeSection([self section]);
2513 - (NSString *) shortSection {
2514 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2517 - (NSString *) uri {
2520 pkgIndexFile *index;
2521 pkgCache::PkgFileIterator file(file_.File());
2522 if (![database_ list].FindIndex(file, index))
2524 return [NSString stringWithUTF8String:iterator_->Path];
2525 //return [NSString stringWithUTF8String:file.Site()];
2526 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2530 - (Address *) maintainer {
2531 @synchronized (database_) {
2532 if ([database_ era] != era_ || file_.end())
2535 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2536 const std::string &maintainer(parser->Maintainer());
2537 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2541 @synchronized (database_) {
2542 if ([database_ era] != era_ || version_.end())
2545 return version_->InstalledSize;
2548 - (NSString *) longDescription {
2549 @synchronized (database_) {
2550 if ([database_ era] != era_ || file_.end())
2553 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2554 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2556 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2557 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2558 if ([lines count] < 2)
2561 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2562 for (size_t i(1), e([lines count]); i != e; ++i) {
2563 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2564 [trimmed addObject:trim];
2567 return [trimmed componentsJoinedByString:@"\n"];
2570 - (NSString *) shortDescription {
2571 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2575 _profile(Package$index)
2576 CFStringRef name((CFStringRef) [self name]);
2577 if (CFStringGetLength(name) == 0)
2579 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2580 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2582 return toupper(character);
2586 - (PackageValue *) metadata {
2591 PackageValue *metadata([self metadata]);
2592 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2595 - (bool) subscribed {
2596 return [self metadata]->subscribed_;
2599 - (bool) setSubscribed:(bool)subscribed {
2600 PackageValue *metadata([self metadata]);
2601 if (metadata->subscribed_ == subscribed)
2603 metadata->subscribed_ = subscribed;
2611 - (NSString *) latest {
2615 - (NSString *) installed {
2619 - (BOOL) uninstalled {
2620 return installed_.empty();
2624 return !version_.end();
2627 - (BOOL) upgradableAndEssential:(BOOL)essential {
2628 _profile(Package$upgradableAndEssential)
2629 pkgCache::VerIterator current(iterator_.CurrentVer());
2631 return essential && essential_;
2633 return !version_.end() && version_ != current;
2637 - (BOOL) essential {
2642 return [database_ cache][iterator_].InstBroken();
2645 - (BOOL) unfiltered {
2646 _profile(Package$unfiltered$obsolete)
2647 if (_unlikely(obsolete_))
2651 _profile(Package$unfiltered$hasSupportingRole)
2652 if (_unlikely(![self hasSupportingRole]))
2660 if (![self unfiltered])
2665 _profile(Package$visible$section)
2666 section = [self section];
2669 _profile(Package$visible$isSectionVisible)
2670 if (!isSectionVisible(section))
2678 unsigned char current(iterator_->CurrentState);
2679 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2682 - (BOOL) halfConfigured {
2683 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2686 - (BOOL) halfInstalled {
2687 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2691 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2692 return state.Mode != pkgDepCache::ModeKeep;
2695 - (NSString *) mode {
2696 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2698 switch (state.Mode) {
2699 case pkgDepCache::ModeDelete:
2700 if ((state.iFlags & pkgDepCache::Purge) != 0)
2704 case pkgDepCache::ModeKeep:
2705 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2706 return @"REINSTALL";
2707 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2711 case pkgDepCache::ModeInstall:
2712 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2713 return @"REINSTALL";
2714 else*/ switch (state.Status) {
2716 return @"DOWNGRADE";
2722 return @"NEW_INSTALL";
2733 - (NSString *) name {
2734 return name_.empty() ? id_ : name_;
2737 - (UIImage *) icon {
2738 NSString *section = [self simpleSection];
2741 if (parsed_ != NULL)
2742 if (NSString *href = parsed_->icon_)
2743 if ([href hasPrefix:@"file:///"])
2744 // XXX: correct escaping
2745 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2746 if (icon == nil) if (section != nil)
2747 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2748 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2749 if ([dicon hasPrefix:@"file:///"])
2750 // XXX: correct escaping
2751 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2753 icon = [UIImage applicationImageNamed:@"unknown.png"];
2757 - (NSString *) homepage {
2758 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2761 - (NSString *) depiction {
2762 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2765 - (Address *) sponsor {
2766 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2769 - (Address *) author {
2770 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2773 - (NSString *) support {
2774 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2777 - (NSArray *) files {
2778 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2779 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2782 fin.open([path UTF8String]);
2787 while (std::getline(fin, line))
2788 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2793 - (NSArray *) warnings {
2794 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2795 const char *name(iterator_.Name());
2797 size_t length(strlen(name));
2798 if (length < 2) invalid:
2799 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2800 else for (size_t i(0); i != length; ++i)
2802 /* XXX: technically this is not allowed */
2803 (name[i] < 'A' || name[i] > 'Z') &&
2804 (name[i] < 'a' || name[i] > 'z') &&
2805 (name[i] < '0' || name[i] > '9') &&
2806 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2809 if (strcmp(name, "cydia") != 0) {
2812 bool _private = false;
2815 bool repository = [[self section] isEqualToString:@"Repositories"];
2817 if (NSArray *files = [self files])
2818 for (NSString *file in files)
2819 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2821 else if (!user && [file isEqualToString:@"/User"])
2823 else if (!_private && [file isEqualToString:@"/private"])
2825 else if (!stash && [file isEqualToString:@"/var/stash"])
2828 /* XXX: this is not sensitive enough. only some folders are valid. */
2829 if (cydia && !repository)
2830 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2832 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2834 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2836 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2839 return [warnings count] == 0 ? nil : warnings;
2842 - (NSArray *) applications {
2843 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2845 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2847 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2848 if (NSArray *files = [self files])
2849 for (NSString *file in files)
2850 if (application_r(file)) {
2851 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2852 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2853 if ([id isEqualToString:me])
2856 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2858 display = application_r[1];
2860 NSString *bundle([file stringByDeletingLastPathComponent]);
2861 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2862 if (icon == nil || [icon length] == 0)
2864 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2866 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2867 [applications addObject:application];
2869 [application addObject:id];
2870 [application addObject:display];
2871 [application addObject:url];
2874 return [applications count] == 0 ? nil : applications;
2877 - (Source *) source {
2878 if (source_ == nil) {
2879 @synchronized (database_) {
2880 if ([database_ era] != era_ || file_.end())
2881 source_ = (Source *) [NSNull null];
2883 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2887 return source_ == (Source *) [NSNull null] ? nil : source_;
2890 - (BOOL) matches:(NSString *)text {
2896 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2897 if (range.location != NSNotFound)
2900 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2901 if (range.location != NSNotFound)
2906 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2907 if (range.location != NSNotFound)
2913 - (bool) hasSupportingRole {
2918 if ([Role_ isEqualToString:@"User"])
2922 if ([Role_ isEqualToString:@"Hacker"])
2926 if ([Role_ isEqualToString:@"Developer"])
2931 - (BOOL) hasTag:(NSString *)tag {
2932 return tags_ == nil ? NO : [tags_ containsObject:tag];
2935 - (NSString *) primaryPurpose {
2936 for (NSString *tag in tags_)
2937 if ([tag hasPrefix:@"purpose::"])
2938 return [tag substringFromIndex:9];
2942 - (NSArray *) purposes {
2943 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2944 for (NSString *tag in tags_)
2945 if ([tag hasPrefix:@"purpose::"])
2946 [purposes addObject:[tag substringFromIndex:9]];
2947 return [purposes count] == 0 ? nil : purposes;
2950 - (bool) isCommercial {
2951 return [self hasTag:@"cydia::commercial"];
2954 - (void) setIndex:(size_t)index {
2955 if (metadata_->index_ != index)
2956 metadata_->index_ = index;
2959 - (CYString &) cyname {
2960 return name_.empty() ? id_ : name_;
2963 - (uint32_t) compareBySection:(NSArray *)sections {
2964 NSString *section([self section]);
2965 for (size_t i(0), e([sections count]); i != e; ++i) {
2966 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2970 return _not(uint32_t);
2974 @synchronized (database_) {
2975 pkgProblemResolver *resolver = [database_ resolver];
2976 resolver->Clear(iterator_);
2978 pkgCacheFile &cache([database_ cache]);
2979 cache->SetReInstall(iterator_, false);
2980 cache->MarkKeep(iterator_, false);
2984 @synchronized (database_) {
2985 pkgProblemResolver *resolver = [database_ resolver];
2986 resolver->Clear(iterator_);
2987 resolver->Protect(iterator_);
2989 pkgCacheFile &cache([database_ cache]);
2990 cache->SetReInstall(iterator_, false);
2991 cache->MarkInstall(iterator_, false);
2993 pkgDepCache::StateCache &state((*cache)[iterator_]);
2994 if (!state.Install())
2995 cache->SetReInstall(iterator_, true);
2999 @synchronized (database_) {
3000 pkgProblemResolver *resolver = [database_ resolver];
3001 resolver->Clear(iterator_);
3002 resolver->Remove(iterator_);
3003 resolver->Protect(iterator_);
3005 pkgCacheFile &cache([database_ cache]);
3006 cache->SetReInstall(iterator_, false);
3007 cache->MarkDelete(iterator_, true);
3010 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3011 _profile(Package$isUnfilteredAndSearchedForBy)
3014 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3015 value &= [self unfiltered];
3018 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3019 value &= [self matches:search];
3026 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3027 if ([search length] == 0)
3030 _profile(Package$isUnfilteredAndSelectedForBy)
3033 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3034 value &= [self unfiltered];
3037 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3038 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3045 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3046 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3049 - (bool) isVisibleInSection:(NSString *)name {
3050 NSString *section([self section]);
3054 section == nil && [name length] == 0 ||
3055 [name isEqualToString:section]
3056 ) && [self visible];
3059 - (bool) isVisibleInSource:(Source *)source {
3060 return [self source] == source && [self visible];
3065 /* Section Class {{{ */
3066 @interface Section : NSObject {
3071 NSString *localized_;
3074 - (NSComparisonResult) compareByLocalized:(Section *)section;
3075 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3076 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3077 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3078 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3079 - (NSString *) name;
3086 - (void) addToCount;
3088 - (void) setCount:(size_t)count;
3089 - (NSString *) localized;
3093 @implementation Section
3097 if (localized_ != nil)
3098 [localized_ release];
3102 - (NSComparisonResult) compareByLocalized:(Section *)section {
3103 NSString *lhs(localized_);
3104 NSString *rhs([section localized]);
3106 /*if ([lhs length] != 0 && [rhs length] != 0) {
3107 unichar lhc = [lhs characterAtIndex:0];
3108 unichar rhc = [rhs characterAtIndex:0];
3110 if (isalpha(lhc) && !isalpha(rhc))
3111 return NSOrderedAscending;
3112 else if (!isalpha(lhc) && isalpha(rhc))
3113 return NSOrderedDescending;
3116 return [lhs compare:rhs options:LaxCompareOptions_];
3119 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3120 if ((self = [self initWithName:name localize:NO]) != nil) {
3121 if (localized != nil)
3122 localized_ = [localized retain];
3126 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3127 return [self initWithName:name row:0 localize:localize];
3130 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3131 if ((self = [super init]) != nil) {
3132 name_ = [name retain];
3136 localized_ = [LocalizeSection(name_) retain];
3140 /* XXX: localize the index thingees */
3141 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3142 if ((self = [super init]) != nil) {
3143 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3149 - (NSString *) name {
3169 - (void) addToCount {
3173 - (void) setCount:(size_t)count {
3177 - (NSString *) localized {
3184 static NSString *Colon_;
3185 static NSString *Elision_;
3186 static NSString *Error_;
3187 static NSString *Warning_;
3189 /* Database Implementation {{{ */
3190 @implementation Database
3192 + (Database *) sharedInstance {
3193 static Database *instance;
3194 if (instance == nil)
3195 instance = [[Database alloc] init];
3203 - (void) releasePackages {
3204 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3205 CFArrayRemoveAllValues(packages_);
3209 // XXX: actually implement this thing
3211 [sourceList_ release];
3212 [self releasePackages];
3213 apr_pool_destroy(pool_);
3214 NSRecycleZone(zone_);
3218 - (void) _readCydia:(NSNumber *)fd { _pooled
3219 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3220 std::istream is(&ib);
3223 static Pcre finish_r("^finish:([^:]*)$");
3225 while (std::getline(is, line)) {
3226 const char *data(line.c_str());
3227 size_t size = line.size();
3228 lprintf("C:%s\n", data);
3230 if (finish_r(data, size)) {
3231 NSString *finish = finish_r[1];
3232 int index = [Finishes_ indexOfObject:finish];
3233 if (index != INT_MAX && index > Finish_)
3241 - (void) _readStatus:(NSNumber *)fd { _pooled
3242 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3243 std::istream is(&ib);
3246 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3247 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3249 while (std::getline(is, line)) {
3250 const char *data(line.c_str());
3251 size_t size(line.size());
3252 lprintf("S:%s\n", data);
3254 if (conffile_r(data, size))
3255 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3256 else if (strncmp(data, "status: ", 8) == 0)
3257 [delegate_ performSelectorOnMainThread:@selector(setProgressTitle:) withObject:[NSString stringWithUTF8String:(data + 8)] waitUntilDone:YES];
3258 else if (pmstatus_r(data, size)) {
3259 std::string type([pmstatus_r[1] UTF8String]);
3260 NSString *id = pmstatus_r[2];
3262 float percent([pmstatus_r[3] floatValue]);
3263 [delegate_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3265 NSString *string = pmstatus_r[4];
3267 if (type == "pmerror")
3268 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3269 withObject:[NSArray arrayWithObjects:string, id, nil]
3272 else if (type == "pmstatus")
3273 [delegate_ performSelectorOnMainThread:@selector(setProgressTitle:) withObject:string waitUntilDone:YES];
3274 else if (type == "pmconffile")
3275 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3277 lprintf("E:unknown pmstatus\n");
3279 lprintf("E:unknown status\n");
3285 - (void) _readOutput:(NSNumber *)fd { _pooled
3286 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3287 std::istream is(&ib);
3290 while (std::getline(is, line)) {
3291 lprintf("O:%s\n", line.c_str());
3293 [delegate_ performSelectorOnMainThread:@selector(addProgressOutput:) withObject:[NSString stringWithUTF8String:line.c_str()] waitUntilDone:YES];
3303 - (Package *) packageWithName:(NSString *)name {
3304 @synchronized (self) {
3305 if (static_cast<pkgDepCache *>(cache_) == NULL)
3307 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3308 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3312 if ((self = [super init]) != nil) {
3319 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3320 apr_pool_create(&pool_, NULL);
3322 size_t capacity(MetaFile_->active_);
3328 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3329 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3333 _assert(pipe(fds) != -1);
3336 _config->Set("APT::Keep-Fds::", cydiafd_);
3337 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3340 detachNewThreadSelector:@selector(_readCydia:)
3342 withObject:[NSNumber numberWithInt:fds[0]]
3345 _assert(pipe(fds) != -1);
3349 detachNewThreadSelector:@selector(_readStatus:)
3351 withObject:[NSNumber numberWithInt:fds[0]]
3354 _assert(pipe(fds) != -1);
3355 _assert(dup2(fds[0], 0) != -1);
3356 _assert(close(fds[0]) != -1);
3358 input_ = fdopen(fds[1], "a");
3360 _assert(pipe(fds) != -1);
3361 _assert(dup2(fds[1], 1) != -1);
3362 _assert(close(fds[1]) != -1);
3365 detachNewThreadSelector:@selector(_readOutput:)
3367 withObject:[NSNumber numberWithInt:fds[0]]
3372 - (pkgCacheFile &) cache {
3376 - (pkgDepCache::Policy *) policy {
3380 - (pkgRecords *) records {
3384 - (pkgProblemResolver *) resolver {
3388 - (pkgAcquire &) fetcher {
3392 - (pkgSourceList &) list {
3396 - (NSArray *) packages {
3397 return (NSArray *) packages_;
3400 - (NSArray *) sources {
3404 - (Source *) sourceWithKey:(NSString *)key {
3405 for (Source *source in [self sources]) {
3406 if ([[source key] isEqualToString:key])
3411 - (bool) popErrorWithTitle:(NSString *)title {
3413 std::string message;
3415 while (!_error->empty()) {
3417 bool warning(!_error->PopMessage(error));
3421 size_t size(error.size());
3422 if (size == 0 || error[size - 1] != '\n')
3424 error.resize(size - 1);
3426 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3428 if (!message.empty())
3433 if (fatal && !message.empty())
3434 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3439 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3440 return [self popErrorWithTitle:title] || !success;
3443 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3444 @synchronized (self) {
3447 [self releasePackages];
3450 [sourceList_ removeAllObjects];
3470 apr_pool_clear(pool_);
3472 NSRecycleZone(zone_);
3473 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3475 int chk(creat("/tmp/cydia.chk", 0644));
3479 if (invocation != nil)
3480 [invocation invoke];
3482 NSString *title(UCLocalize("DATABASE"));
3485 while (!cache_.Open(progress_, true)) { pop:
3487 bool warning(!_error->PopMessage(error));
3488 lprintf("cache_.Open():[%s]\n", error.c_str());
3490 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3491 [delegate_ repairWithSelector:@selector(configure)];
3492 else if (error == "The package lists or status file could not be parsed or opened.")
3493 [delegate_ repairWithSelector:@selector(update)];
3494 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3495 else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3496 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, Error_, title]];
3497 // else if (error == "The list of sources could not be read.")
3499 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3509 unlink("/tmp/cydia.chk");
3511 now_ = [[NSDate date] timeIntervalSince1970];
3513 policy_ = new pkgDepCache::Policy();
3514 records_ = new pkgRecords(cache_);
3515 resolver_ = new pkgProblemResolver(cache_);
3516 fetcher_ = new pkgAcquire(&status_);
3519 list_ = new pkgSourceList();
3520 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3523 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3524 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3528 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3531 if (cache_->BrokenCount() != 0) {
3532 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3535 if (cache_->BrokenCount() != 0) {
3536 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3540 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3544 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3545 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3546 [sourceList_ addObject:object];
3548 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3549 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3550 // XXX: this could be more intelligent
3551 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3552 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3554 sourceMap_[cached->ID] = object;
3559 /*std::vector<Package *> packages;
3560 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3561 [packages_ release];
3566 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3567 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3568 //packages.push_back(package);
3569 CFArrayAppendValue(packages_, [package retain]);
3573 /*if (packages.empty())
3574 packages_ = [[NSArray alloc] init];
3576 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3579 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3580 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3581 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3589 /*if (!packages.empty())
3590 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3591 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3593 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3595 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3597 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3601 size_t count(CFArrayGetCount(packages_));
3602 MetaFile_->active_ = count;
3604 for (size_t index(0); index != count; ++index)
3605 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3609 } } CYPoolEnd() _trace(); }
3612 @synchronized (self) {
3614 resolver_ = new pkgProblemResolver(cache_);
3616 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3617 if (!cache_[iterator].Keep())
3618 cache_->MarkKeep(iterator, false);
3619 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3620 cache_->SetReInstall(iterator, false);
3623 - (void) configure {
3624 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3626 system([dpkg UTF8String]);
3631 // XXX: I don't remember this condition
3636 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3638 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3640 if ([self popErrorWithTitle:title])
3644 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3647 public pkgArchiveCleaner
3650 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3655 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3662 fetcher_->Shutdown();
3664 pkgRecords records(cache_);
3666 lock_ = new FileFd();
3667 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3669 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3671 if ([self popErrorWithTitle:title])
3675 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3678 manager_ = (_system->CreatePM(cache_));
3679 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3686 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3688 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3690 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3692 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3693 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3696 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3701 [(id)CydiaApp performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3703 bool failed = false;
3704 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3705 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3707 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3710 std::string uri = (*item)->DescURI();
3711 std::string error = (*item)->ErrorText;
3713 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3716 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3717 withObject:[NSArray arrayWithObjects:
3718 [NSString stringWithUTF8String:error.c_str()],
3724 [(id)CydiaApp performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3732 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3734 if (_error->PendingError()) {
3739 if (result == pkgPackageManager::Failed) {
3744 if (result != pkgPackageManager::Completed) {
3749 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3751 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3753 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3754 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3757 if (![before isEqualToArray:after])
3762 NSString *title(UCLocalize("UPGRADE"));
3763 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3769 [self updateWithStatus:status_];
3772 - (void) updateWithStatus:(Status &)status {
3773 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3774 NSString *title(UCLocalize("REFRESHING_DATA"));
3777 if (!list.ReadMainList())
3778 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3781 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3782 if ([self popErrorWithTitle:title])
3785 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3786 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3787 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3789 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3793 - (void) setDelegate:(id)delegate {
3794 delegate_ = delegate;
3795 status_.setDelegate(delegate);
3796 progress_.setDelegate(delegate);
3799 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3800 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3801 return i == sourceMap_.end() ? nil : i->second;
3804 - (NSString *) mappedSectionForPointer:(const char *)section {
3805 _H<NSString> *mapped;
3807 _profile(Database$mappedSectionForPointer$Cache)
3808 mapped = §ions_[section];
3811 if (*mapped == NULL) {
3812 size_t length(strlen(section));
3813 char spaced[length + 1];
3815 _profile(Database$mappedSectionForPointer$Replace)
3816 for (size_t index(0); index != length; ++index)
3817 spaced[index] = section[index] == '_' ? ' ' : section[index];
3818 spaced[length] = '\0';
3823 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3824 string = [NSString stringWithUTF8String:spaced];
3827 _profile(Database$mappedSectionForPointer$Map)
3828 string = [SectionMap_ objectForKey:string] ?: string;
3838 /* Web Scripting {{{ */
3839 @interface CydiaObject : NSObject {
3841 _transient id delegate_;
3844 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3848 @implementation CydiaObject
3851 [indirect_ release];
3855 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3856 if ((self = [super init]) != nil) {
3857 indirect_ = [indirect retain];
3861 - (void) setDelegate:(id)delegate {
3862 delegate_ = delegate;
3865 + (NSArray *) _attributeKeys {
3866 return [NSArray arrayWithObjects:
3876 - (NSArray *) attributeKeys {
3877 return [[self class] _attributeKeys];
3880 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3881 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3884 - (NSString *) device {
3885 return [[UIDevice currentDevice] uniqueIdentifier];
3888 - (NSString *) plmn {
3892 - (NSString *) ecid {
3896 - (NSString *) serial {
3897 return SerialNumber_;
3900 - (NSString *) role {
3904 - (NSString *) model {
3905 return [NSString stringWithUTF8String:Machine_];
3908 + (NSString *) webScriptNameForSelector:(SEL)selector {
3910 else if (selector == @selector(addTrivialSource:))
3911 return @"addTrivialSource";
3912 else if (selector == @selector(close))
3914 else if (selector == @selector(du:))
3916 else if (selector == @selector(stringWithFormat:arguments:))
3918 else if (selector == @selector(getAllSources))
3919 return @"getAllSourcs";
3920 else if (selector == @selector(getKernelNumber:))
3921 return @"getKernelNumber";
3922 else if (selector == @selector(getKernelString:))
3923 return @"getKernelString";
3924 else if (selector == @selector(getInstalledPackages))
3925 return @"getInstalledPackages";
3926 else if (selector == @selector(getPackageById:))
3927 return @"getPackageById";
3928 else if (selector == @selector(installPackages:))
3929 return @"installPackages";
3930 else if (selector == @selector(localizedStringForKey:value:table:))
3932 else if (selector == @selector(refreshSources))
3933 return @"refreshSources";
3934 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3935 return @"setButtonImage";
3936 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3937 return @"setButtonTitle";
3938 else if (selector == @selector(setPopupHook:))
3939 return @"setPopupHook";
3940 else if (selector == @selector(setToken:))
3942 else if (selector == @selector(setViewportWidth:))
3943 return @"setViewportWidth";
3944 else if (selector == @selector(statfs:))
3946 else if (selector == @selector(supports:))
3952 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3953 return [self webScriptNameForSelector:selector] == nil;
3956 - (BOOL) supports:(NSString *)feature {
3957 return [feature isEqualToString:@"window.open"];
3960 - (NSNumber *) getKernelNumber:(NSString *)name {
3961 const char *string([name UTF8String]);
3964 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3965 return (id) [NSNull null];
3967 if (size != sizeof(int))
3968 return (id) [NSNull null];
3971 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3972 return (id) [NSNull null];
3974 return [NSNumber numberWithInt:value];
3977 - (NSString *) getKernelString:(NSString *)name {
3978 const char *string([name UTF8String]);
3981 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3982 return (id) [NSNull null];
3984 char value[size + 1];
3985 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3986 return (id) [NSNull null];
3988 // XXX: just in case you request something ludicrous
3991 return [NSString stringWithCString:value];
3994 - (void) addTrivialSource:(NSString *)href {
3995 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
3998 - (void) refreshSources {
3999 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4002 - (NSArray *) getAllSources {
4003 return [[Database sharedInstance] sources];
4006 - (NSArray *) getInstalledPackages {
4007 Database *database([Database sharedInstance]);
4008 @synchronized (database) {
4009 NSArray *packages([database packages]);
4010 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4011 for (Package *package in packages)
4012 if (![package uninstalled])
4013 [installed addObject:package];
4017 - (Package *) getPackageById:(NSString *)id {
4018 Package *package([[Database sharedInstance] packageWithName:id]);
4023 - (NSArray *) statfs:(NSString *)path {
4026 if (path == nil || statfs([path UTF8String], &stat) == -1)
4029 return [NSArray arrayWithObjects:
4030 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4031 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4032 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4036 - (NSNumber *) du:(NSString *)path {
4037 NSNumber *value(nil);
4040 _assert(pipe(fds) != -1);
4042 pid_t pid(ExecFork());
4044 _assert(dup2(fds[1], 1) != -1);
4045 _assert(close(fds[0]) != -1);
4046 _assert(close(fds[1]) != -1);
4047 /* XXX: this should probably not use du */
4048 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4053 _assert(close(fds[1]) != -1);
4055 if (FILE *du = fdopen(fds[0], "r")) {
4057 while (fgets(line, sizeof(line), du) != NULL) {
4058 size_t length(strlen(line));
4059 while (length != 0 && line[length - 1] == '\n')
4060 line[--length] = '\0';
4061 if (char *tab = strchr(line, '\t')) {
4063 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4068 } else _assert(close(fds[0]));
4072 if (waitpid(pid, &status, 0) == -1)
4075 else _assert(false);
4081 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4084 - (void) installPackages:(NSArray *)packages {
4085 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4088 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4089 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4092 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4093 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4096 - (void) _setToken:(NSString *)token {
4099 Token_ = [token retain];
4101 [Metadata_ setObject:Token_ forKey:@"Token"];
4105 - (void) setToken:(NSString *)token {
4106 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4109 - (void) setPopupHook:(id)function {
4110 [indirect_ setPopupHook:function];
4113 - (void) setViewportWidth:(float)width {
4114 [indirect_ setViewportWidthOnMainThread:width];
4117 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4118 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4119 unsigned count([arguments count]);
4121 for (unsigned i(0); i != count; ++i)
4122 values[i] = [arguments objectAtIndex:i];
4123 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4126 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4127 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4129 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4131 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4137 /* @ Loading... Indicator {{{ */
4138 @interface CYLoadingIndicator : UIView {
4139 UIActivityIndicatorView *spinner_;
4144 @property (readonly, nonatomic) UILabel *label;
4145 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4149 @implementation CYLoadingIndicator
4151 - (id) initWithFrame:(CGRect)frame {
4152 if ((self = [super initWithFrame:frame]) != nil) {
4153 container_ = [[[UIView alloc] init] autorelease];
4154 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4156 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4157 [spinner_ startAnimating];
4158 [container_ addSubview:spinner_];
4160 label_ = [[[UILabel alloc] init] autorelease];
4161 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4162 [label_ setBackgroundColor:[UIColor clearColor]];
4163 [label_ setTextColor:[UIColor blackColor]];
4164 [label_ setShadowColor:[UIColor whiteColor]];
4165 [label_ setShadowOffset:CGSizeMake(0, 1)];
4166 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4167 [container_ addSubview:label_];
4169 CGSize viewsize = frame.size;
4170 CGSize spinnersize = [spinner_ bounds].size;
4171 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4172 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4174 CGRect containrect = {
4175 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4176 CGSizeMake(bothwidth, spinnersize.height)
4179 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4187 [container_ setFrame:containrect];
4188 [spinner_ setFrame:spinrect];
4189 [label_ setFrame:textrect];
4190 [self addSubview:container_];
4194 - (UILabel *) label {
4198 - (UIActivityIndicatorView *) activityIndicatorView {
4204 /* Emulated Loading Controller {{{ */
4205 @interface CYEmulatedLoadingController : CYViewController <
4207 ConfigurationDelegate
4209 _transient Database *database_;
4210 CYLoadingIndicator *indicator_;
4212 UINavigationBar *navbar_;
4217 @implementation CYEmulatedLoadingController
4220 [self releaseSubviews];
4221 [database_ setDelegate:nil];
4226 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4227 CYAlertView *sheet([[[CYAlertView alloc]
4229 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4230 defaultButtonIndex:0
4233 [sheet setMessage:error];
4234 [sheet yieldToPopupAlertAnimated:YES];
4238 - (void) setProgressTitle:(NSString *)title { }
4239 - (void) setProgressPercent:(NSNumber *)percent { }
4240 - (void) startProgress { }
4241 - (void) addProgressOutput:(NSString *)output { }
4242 - (bool) isCancelling:(size_t)received { return NO; }
4243 - (void) setConfigurationData:(NSString *)data { }
4245 - (void) repairWithSelector:(SEL)selector {
4246 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("REPAIRING"), nil] waitUntilDone:YES];
4247 [database_ performSelector:selector];
4249 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil] waitUntilDone:YES];
4252 - (id) initWithDatabase:(Database *)database {
4253 if ((self = [super init]) != nil) {
4254 database_ = database;
4255 [database_ setDelegate:self];
4260 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4261 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4263 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4264 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4265 [[self view] addSubview:indicator_];
4267 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4268 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4269 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4270 [[self view] addSubview:tabbar_];
4272 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4273 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4274 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4275 [[self view] addSubview:navbar_];
4278 - (void) releaseSubviews {
4279 [indicator_ release];
4292 /* Cydia Browser Controller {{{ */
4293 @interface CYBrowserController : BrowserController {
4294 CydiaObject *cydia_;
4299 @implementation CYBrowserController
4306 - (NSURL *) navigationURL {
4307 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4310 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4313 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4314 [super webView:view didClearWindowObject:window forFrame:frame];
4316 WebDataSource *source([frame dataSource]);
4317 NSURLResponse *response([source response]);
4319 NSURL *url([response URL]);
4320 NSString *scheme([url scheme]);
4321 NSString *host([url host]);
4323 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4324 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4325 NSDictionary *headers([http allHeaderFields]);
4326 [self setHeaders:headers forHost:host];
4330 [host isEqualToString:@"cydia.saurik.com"] ||
4331 [host hasSuffix:@".cydia.saurik.com"] ||
4332 [scheme isEqualToString:@"file"]
4334 [window setValue:cydia_ forKey:@"cydia"];
4337 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4338 if (System_ != NULL)
4339 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4340 if (Machine_ != NULL)
4341 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4343 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4345 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4348 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4349 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4350 [self _setMoreHeaders:copy];
4354 - (void) setDelegate:(id)delegate {
4355 [super setDelegate:delegate];
4356 [cydia_ setDelegate:delegate];
4360 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4361 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4363 WebView *webview([[webview_ _documentView] webView]);
4365 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4367 NSString *application = package == nil ? @"Cydia" : [NSString
4368 stringWithFormat:@"Cydia/%@",
4373 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4375 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4376 if (Product_ != nil)
4377 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4379 [webview setApplicationNameForUserAgent:application];
4387 @interface NSObject (CydiaScript)
4388 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4391 @implementation NSObject (CydiaScript)
4393 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4399 @implementation NSArray (CydiaScript)
4401 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4402 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4403 for (size_t i(0), e([self count]); i != e; ++i)
4404 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4410 @implementation NSDictionary (CydiaScript)
4412 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4413 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4415 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4422 /* Confirmation Controller {{{ */
4423 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4424 if (!iterator.end())
4425 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4426 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4428 pkgCache::PkgIterator package(dep.TargetPkg());
4431 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4438 @protocol ConfirmationControllerDelegate
4439 - (void) cancelAndClear:(bool)clear;
4440 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4444 @interface ConfirmationController : CYBrowserController {
4445 _transient Database *database_;
4447 UIAlertView *essential_;
4449 NSDictionary *changes_;
4450 NSMutableArray *issues_;
4451 NSDictionary *sizes_;
4456 - (id) initWithDatabase:(Database *)database;
4460 @implementation ConfirmationController
4467 if (essential_ != nil)
4468 [essential_ release];
4473 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4474 NSString *context([alert context]);
4476 if ([context isEqualToString:@"remove"]) {
4477 if (button == [alert cancelButtonIndex]) {
4478 [self dismissModalViewControllerAnimated:YES];
4479 } else if (button == [alert firstOtherButtonIndex]) {
4482 [delegate_ confirmWithNavigationController:[self navigationController]];
4485 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4486 } else if ([context isEqualToString:@"unable"]) {
4487 [self dismissModalViewControllerAnimated:YES];
4488 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4490 [super alertView:alert clickedButtonAtIndex:button];
4494 - (void) _doContinue {
4495 [self dismissModalViewControllerAnimated:YES];
4496 [delegate_ cancelAndClear:NO];
4499 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4500 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4504 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4505 [super webView:view didClearWindowObject:window forFrame:frame];
4507 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4508 changes_, @"changes",
4512 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4515 - (id) initWithDatabase:(Database *)database {
4516 if ((self = [super init]) != nil) {
4517 database_ = database;
4519 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4520 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4521 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4522 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4523 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4527 pkgCacheFile &cache([database_ cache]);
4528 NSArray *packages([database_ packages]);
4529 pkgDepCache::Policy *policy([database_ policy]);
4531 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4533 for (Package *package in packages) {
4534 pkgCache::PkgIterator iterator([package iterator]);
4535 NSString *name([package id]);
4537 if ([package broken]) {
4538 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4540 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4542 reasons, @"reasons",
4545 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4549 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4550 pkgCache::DepIterator start;
4551 pkgCache::DepIterator end;
4552 dep.GlobOr(start, end); // ++dep
4554 if (!cache->IsImportantDep(end))
4556 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4559 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4561 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4562 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4563 clauses, @"clauses",
4567 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4569 pkgCache::PkgIterator target(start.TargetPkg());
4570 if (target->ProvidesList != 0)
4571 reason = @"missing";
4573 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4575 reason = @"installed";
4576 installed = [NSString stringWithUTF8String:ver.VerStr()];
4577 } else if (!cache[target].CandidateVerIter(cache).end())
4578 reason = @"uninstalled";
4579 else if (target->ProvidesList == 0)
4580 reason = @"uninstallable";
4582 reason = @"virtual";
4585 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4586 [NSString stringWithUTF8String:start.CompType()], @"operator",
4587 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4590 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4591 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4592 version, @"version",
4594 installed, @"installed",
4597 // yes, seriously. (wtf?)
4605 pkgDepCache::StateCache &state(cache[iterator]);
4607 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4609 if (state.NewInstall())
4610 [installs addObject:name];
4611 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4612 [reinstalls addObject:name];
4613 else if (state.Upgrade())
4614 [upgrades addObject:name];
4615 else if (state.Downgrade())
4616 [downgrades addObject:name];
4617 else if (!state.Delete())
4619 else if (special_r(name))
4620 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4621 [NSNull null], @"package",
4622 [NSArray arrayWithObjects:
4623 [NSDictionary dictionaryWithObjectsAndKeys:
4624 @"Conflicts", @"relationship",
4625 [NSArray arrayWithObjects:
4626 [NSDictionary dictionaryWithObjectsAndKeys:
4628 [NSNull null], @"version",
4629 @"installed", @"reason",
4636 if ([package essential])
4638 [removes addObject:name];
4641 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4642 substrate_ |= DepSubstrate(iterator.CurrentVer());
4647 else if (Advanced_) {
4648 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4650 essential_ = [[UIAlertView alloc]
4651 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4652 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4654 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4656 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4660 [essential_ setContext:@"remove"];
4662 essential_ = [[UIAlertView alloc]
4663 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4664 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4666 cancelButtonTitle:UCLocalize("OKAY")
4667 otherButtonTitles:nil
4670 [essential_ setContext:@"unable"];
4673 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4674 installs, @"installs",
4675 reinstalls, @"reinstalls",
4676 upgrades, @"upgrades",
4677 downgrades, @"downgrades",
4678 removes, @"removes",
4681 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4682 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4683 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4686 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4688 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4689 initWithTitle:UCLocalize("CANCEL")
4690 style:UIBarButtonItemStylePlain
4692 action:@selector(cancelButtonClicked)
4698 - (void) applyRightButton {
4699 if ([issues_ count] == 0 && ![self isLoading])
4700 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4701 initWithTitle:UCLocalize("CONFIRM")
4702 style:UIBarButtonItemStyleDone
4704 action:@selector(confirmButtonClicked)
4707 [[self navigationItem] setRightBarButtonItem:nil];
4711 - (void) cancelButtonClicked {
4712 [self dismissModalViewControllerAnimated:YES];
4713 [delegate_ cancelAndClear:YES];
4717 - (void) confirmButtonClicked {
4718 if (essential_ != nil)
4723 [delegate_ confirmWithNavigationController:[self navigationController]];
4731 /* Progress Data {{{ */
4732 @interface ProgressData : NSObject {
4734 // XXX: should these really both be _transient?
4735 _transient id target_;
4736 _transient id object_;
4739 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4747 @implementation ProgressData
4749 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4750 if ((self = [super init]) != nil) {
4751 selector_ = selector;
4771 /* Progress Controller {{{ */
4772 @interface ProgressController : CYViewController <
4773 ConfigurationDelegate,
4776 _transient Database *database_;
4777 UIProgressBar *progress_;
4778 UITextView *output_;
4779 UITextLabel *status_;
4780 UIPushButton *close_;
4782 SHA1SumValue springlist_;
4783 SHA1SumValue notifyconf_;
4787 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4789 - (void) _retachThread;
4790 - (void) _detachNewThreadData:(ProgressData *)data;
4791 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4797 @protocol ProgressControllerDelegate
4798 - (void) progressControllerIsComplete:(ProgressController *)sender;
4801 @implementation ProgressController
4804 [database_ setDelegate:nil];
4805 [progress_ release];
4814 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4815 if ((self = [super init]) != nil) {
4816 database_ = database;
4817 [database_ setDelegate:self];
4818 delegate_ = delegate;
4820 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4822 progress_ = [[UIProgressBar alloc] init];
4823 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4824 [progress_ setStyle:0];
4826 status_ = [[UITextLabel alloc] init];
4827 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4828 [status_ setColor:[UIColor whiteColor]];
4829 [status_ setBackgroundColor:[UIColor clearColor]];
4830 [status_ setCentersHorizontally:YES];
4831 //[status_ setFont:font];
4833 output_ = [[UITextView alloc] init];
4834 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4835 //[output_ setTextFont:@"Courier New"];
4836 [output_ setFont:[[output_ font] fontWithSize:12]];
4837 [output_ setTextColor:[UIColor whiteColor]];
4838 [output_ setBackgroundColor:[UIColor clearColor]];
4839 [output_ setMarginTop:0];
4840 [output_ setAllowsRubberBanding:YES];
4841 [output_ setEditable:NO];
4842 [[self view] addSubview:output_];
4844 close_ = [[UIPushButton alloc] init];
4845 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4846 [close_ setAutosizesToFit:NO];
4847 [close_ setDrawsShadow:YES];
4848 [close_ setStretchBackground:YES];
4849 [close_ setEnabled:YES];
4850 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4851 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4852 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4853 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4857 - (void) positionViews {
4858 CGRect bounds = [[self view] bounds];
4859 CGSize prgsize = [UIProgressBar defaultSize];
4862 (bounds.size.width - prgsize.width) / 2,
4863 bounds.size.height - prgsize.height - 20
4866 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4868 [progress_ setFrame:prgrect];
4869 [status_ setFrame:CGRectMake(
4871 bounds.size.height - prgsize.height - 50,
4872 bounds.size.width - 20,
4875 [output_ setFrame:CGRectMake(
4878 bounds.size.width - 20,
4879 bounds.size.height - 96
4881 [close_ setFrame:CGRectMake(
4882 (bounds.size.width - closewidth) / 2,
4883 bounds.size.height - prgsize.height - 50,
4889 - (void) viewWillAppear:(BOOL)animated {
4890 [super viewDidAppear:animated];
4891 [[self navigationItem] setHidesBackButton:YES];
4892 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4894 [self positionViews];
4897 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4898 [self positionViews];
4901 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4902 NSString *context([alert context]);
4904 if ([context isEqualToString:@"conffile"]) {
4905 FILE *input = [database_ input];
4906 if (button == [alert cancelButtonIndex])
4907 fprintf(input, "N\n");
4908 else if (button == [alert firstOtherButtonIndex])
4909 fprintf(input, "Y\n");
4914 - (void) closeButtonPushed {
4917 UpdateExternalStatus(0);
4921 [self dismissModalViewControllerAnimated:YES];
4925 [delegate_ terminateWithSuccess];
4926 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4927 [delegate_ suspendWithAnimation:YES];
4929 [delegate_ suspend];*/
4941 system("/usr/bin/sbreload");
4947 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4948 SBReboot(SBSSpringBoardServerPort());
4950 reboot2(RB_AUTOBOOT);
4955 - (void) _retachThread {
4956 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4958 [[self view] addSubview:close_];
4959 [progress_ removeFromSuperview];
4960 [status_ removeFromSuperview];
4962 [database_ popErrorWithTitle:title_];
4963 [delegate_ progressControllerIsComplete:self];
4967 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4970 MMap mmap(file, MMap::ReadOnly);
4972 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4973 if (!(notifyconf_ == sha1.Result()))
4980 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4983 MMap mmap(file, MMap::ReadOnly);
4985 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4986 if (!(springlist_ == sha1.Result()))
4992 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4993 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4994 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4995 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4996 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
5000 system("su -c /usr/bin/uicache mobile");
5003 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
5005 [delegate_ setStatusBarShowsProgress:NO];
5008 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
5009 [[data target] performSelector:[data selector] withObject:[data object]];
5010 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
5013 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
5014 UpdateExternalStatus(1);
5021 title_ = [title retain];
5023 [[self navigationItem] setTitle:title_];
5025 [status_ setText:nil];
5026 [output_ setText:@""];
5027 [progress_ setProgress:0];
5029 [close_ removeFromSuperview];
5030 [[self view] addSubview:progress_];
5031 [[self view] addSubview:status_];
5033 [delegate_ setStatusBarShowsProgress:YES];
5038 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5041 MMap mmap(file, MMap::ReadOnly);
5043 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5044 notifyconf_ = sha1.Result();
5050 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5053 MMap mmap(file, MMap::ReadOnly);
5055 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5056 springlist_ = sha1.Result();
5061 detachNewThreadSelector:@selector(_detachNewThreadData:)
5063 withObject:[[[ProgressData alloc]
5064 initWithSelector:selector
5071 - (void) repairWithSelector:(SEL)selector {
5073 detachNewThreadSelector:selector
5076 title:UCLocalize("REPAIRING")
5080 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
5081 CYAlertView *sheet([[[CYAlertView alloc]
5083 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
5084 defaultButtonIndex:0
5087 [sheet setMessage:error];
5088 [sheet yieldToPopupAlertAnimated:YES];
5092 - (void) startProgress {
5095 - (bool) isCancelling:(size_t)received {
5099 - (void) setConfigurationData:(NSString *)data {
5100 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
5102 if (!conffile_r(data)) {
5103 lprintf("E:invalid conffile\n");
5107 NSString *ofile = conffile_r[1];
5108 //NSString *nfile = conffile_r[2];
5110 UIAlertView *alert = [[[UIAlertView alloc]
5111 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
5112 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
5114 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
5116 UCLocalize("ACCEPT_NEW_COPY"),
5117 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
5121 [alert setContext:@"conffile"];
5125 - (void) setProgressTitle:(NSString *)title {
5126 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
5127 for (size_t i(0), e([words count]); i != e; ++i) {
5128 NSString *word([words objectAtIndex:i]);
5129 if (Package *package = [database_ packageWithName:word])
5130 [words replaceObjectAtIndex:i withObject:[package name]];
5133 [status_ setText:[words componentsJoinedByString:@" "]];
5136 - (void) setProgressPercent:(NSNumber *)percent {
5137 [progress_ setProgress:[percent floatValue]];
5140 - (void) addProgressOutput:(NSString *)output {
5141 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
5142 CGSize size = [output_ contentSize];
5143 CGPoint offset = [output_ contentOffset];
5144 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
5145 CGRect rect = {{0, size.height-1}, {size.width, 1}};
5146 [output_ scrollRectToVisible:rect animated:YES];
5150 - (BOOL) isRunning {
5157 /* Cell Content View {{{ */
5158 @protocol ContentDelegate
5159 - (void) drawContentRect:(CGRect)rect;
5162 @interface ContentView : UIView {
5163 _transient id<ContentDelegate> delegate_;
5168 @implementation ContentView
5170 - (id) initWithFrame:(CGRect)frame {
5171 if ((self = [super initWithFrame:frame]) != nil) {
5172 [self setNeedsDisplayOnBoundsChange:YES];
5176 - (void) setDelegate:(id<ContentDelegate>)delegate {
5177 delegate_ = delegate;
5180 - (void) drawRect:(CGRect)rect {
5181 [super drawRect:rect];
5182 [delegate_ drawContentRect:rect];
5187 /* Cydia TableView Cell {{{ */
5188 @interface CYTableViewCell : UITableViewCell {
5189 ContentView *content_;
5195 @implementation CYTableViewCell
5202 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5203 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5205 if (view == content_) {
5206 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5207 highlighted_ = highlighted;
5210 [super _updateHighlightColorsForView:view highlighted:highlighted];
5213 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5214 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5215 highlighted_ = selected;
5217 [super setSelected:selected animated:animated];
5218 [content_ setNeedsDisplay];
5224 /* Package Cell {{{ */
5225 @interface PackageCell : CYTableViewCell <
5230 NSString *description_;
5238 - (PackageCell *) init;
5239 - (void) setPackage:(Package *)package;
5241 - (void) drawContentRect:(CGRect)rect;
5245 @implementation PackageCell
5247 - (void) clearPackage {
5258 if (description_ != nil) {
5259 [description_ release];
5263 if (source_ != nil) {
5268 if (badge_ != nil) {
5273 if (placard_ != nil) {
5283 [self clearPackage];
5287 - (PackageCell *) init {
5288 CGRect frame(CGRectMake(0, 0, 320, 74));
5289 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5290 UIView *content([self contentView]);
5291 CGRect bounds([content bounds]);
5293 content_ = [[ContentView alloc] initWithFrame:bounds];
5294 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5295 [content addSubview:content_];
5297 [content_ setDelegate:self];
5298 [content_ setOpaque:YES];
5302 - (NSString *) accessibilityLabel {
5303 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5306 - (void) setPackage:(Package *)package {
5307 [self clearPackage];
5310 Source *source = [package source];
5312 icon_ = [[package icon] retain];
5313 name_ = [[package name] retain];
5316 description_ = [package longDescription];
5317 if (description_ == nil)
5318 description_ = [package shortDescription];
5319 if (description_ != nil)
5320 description_ = [description_ retain];
5322 commercial_ = [package isCommercial];
5324 package_ = [package retain];
5326 NSString *label = nil;
5327 bool trusted = false;
5329 if (source != nil) {
5330 label = [source label];
5331 trusted = [source trusted];
5332 } else if ([[package id] isEqualToString:@"firmware"])
5333 label = UCLocalize("APPLE");
5335 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5337 NSString *from(label);
5339 NSString *section = [package simpleSection];
5340 if (section != nil && ![section isEqualToString:label]) {
5341 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5342 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5345 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5346 source_ = [from retain];
5348 if (NSString *purpose = [package primaryPurpose])
5349 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5350 badge_ = [badge_ retain];
5355 if (NSString *mode = [package_ mode]) {
5356 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5357 color = RemovingColor_;
5358 //placard = @"removing";
5360 color = InstallingColor_;
5361 //placard = @"installing";
5364 // XXX: the removing/installing placards are not @2x
5367 color = [UIColor whiteColor];
5369 if ([package installed] != nil)
5370 placard = @"installed";
5375 [content_ setBackgroundColor:color];
5378 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5379 placard_ = [placard_ retain];
5381 [self setNeedsDisplay];
5382 [content_ setNeedsDisplay];
5385 - (void) drawContentRect:(CGRect)rect {
5386 bool highlighted(highlighted_);
5387 float width([self bounds].size.width);
5390 CGContextRef context(UIGraphicsGetCurrentContext());
5391 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5392 CGContextFillRect(context, rect);
5397 rect.size = [icon_ size];
5399 rect.size.width /= 2;
5400 rect.size.height /= 2;
5402 rect.origin.x = 25 - rect.size.width / 2;
5403 rect.origin.y = 25 - rect.size.height / 2;
5405 [icon_ drawInRect:rect];
5408 if (badge_ != nil) {
5410 rect.size = [badge_ size];
5412 rect.size.width /= 2;
5413 rect.size.height /= 2;
5415 rect.origin.x = 36 - rect.size.width / 2;
5416 rect.origin.y = 36 - rect.size.height / 2;
5418 [badge_ drawInRect:rect];
5425 UISetColor(commercial_ ? Purple_ : Black_);
5426 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5427 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5430 UISetColor(commercial_ ? Purplish_ : Gray_);
5431 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5433 if (placard_ != nil)
5434 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5439 /* Section Cell {{{ */
5440 @interface SectionCell : CYTableViewCell <
5452 - (void) setSection:(Section *)section editing:(BOOL)editing;
5456 @implementation SectionCell
5458 - (void) clearSection {
5459 if (basic_ != nil) {
5464 if (section_ != nil) {
5474 if (count_ != nil) {
5481 [self clearSection];
5487 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5488 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5489 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5490 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5491 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5493 UIView *content([self contentView]);
5494 CGRect bounds([content bounds]);
5496 content_ = [[ContentView alloc] initWithFrame:bounds];
5497 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5498 [content addSubview:content_];
5499 [content_ setBackgroundColor:[UIColor whiteColor]];
5501 [content_ setDelegate:self];
5505 - (void) onSwitch:(id)sender {
5506 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5507 if (metadata == nil) {
5508 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5509 [Sections_ setObject:metadata forKey:basic_];
5512 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5516 - (void) setSection:(Section *)section editing:(BOOL)editing {
5517 if (editing != editing_) {
5519 [switch_ removeFromSuperview];
5521 [self addSubview:switch_];
5525 [self clearSection];
5527 if (section == nil) {
5528 name_ = [UCLocalize("ALL_PACKAGES") retain];
5531 basic_ = [section name];
5533 basic_ = [basic_ retain];
5535 section_ = [section localized];
5536 if (section_ != nil)
5537 section_ = [section_ retain];
5539 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5540 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5543 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5546 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5547 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5549 [content_ setNeedsDisplay];
5552 - (void) setFrame:(CGRect)frame {
5553 [super setFrame:frame];
5555 CGRect rect([switch_ frame]);
5556 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5559 - (NSString *) accessibilityLabel {
5563 - (void) drawContentRect:(CGRect)rect {
5564 bool highlighted(highlighted_ && !editing_);
5566 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5571 float width(rect.size.width);
5577 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5579 CGSize size = [count_ sizeWithFont:Font14_];
5583 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5589 /* File Table {{{ */
5590 @interface FileTable : CYViewController <
5591 UITableViewDataSource,
5594 _transient Database *database_;
5597 NSMutableArray *files_;
5601 - (id) initWithDatabase:(Database *)database;
5602 - (void) setPackage:(Package *)package;
5606 @implementation FileTable
5609 [self releaseSubviews];
5618 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5619 return files_ == nil ? 0 : [files_ count];
5622 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5626 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5627 static NSString *reuseIdentifier = @"Cell";
5629 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5631 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5632 [cell setFont:[UIFont systemFontOfSize:16]];
5634 [cell setText:[files_ objectAtIndex:indexPath.row]];
5635 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5640 - (NSURL *) navigationURL {
5641 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5645 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5647 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5648 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5649 [list_ setRowHeight:24.0f];
5650 [list_ setDataSource:self];
5651 [list_ setDelegate:self];
5652 [[self view] addSubview:list_];
5655 - (void) viewDidLoad {
5656 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5659 - (void) releaseSubviews {
5664 - (id) initWithDatabase:(Database *)database {
5665 if ((self = [super init]) != nil) {
5666 database_ = database;
5668 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5672 - (void) setPackage:(Package *)package {
5673 if (package_ != nil) {
5674 [package_ autorelease];
5683 [files_ removeAllObjects];
5685 if (package != nil) {
5686 package_ = [package retain];
5687 name_ = [[package id] retain];
5689 if (NSArray *files = [package files])
5690 [files_ addObjectsFromArray:files];
5692 if ([files_ count] != 0) {
5693 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5694 [files_ removeObjectAtIndex:0];
5695 [files_ sortUsingSelector:@selector(compareByPath:)];
5697 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5698 [stack addObject:@"/"];
5700 for (int i(0), e([files_ count]); i != e; ++i) {
5701 NSString *file = [files_ objectAtIndex:i];
5702 while (![file hasPrefix:[stack lastObject]])
5703 [stack removeLastObject];
5704 NSString *directory = [stack lastObject];
5705 [stack addObject:[file stringByAppendingString:@"/"]];
5706 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5707 ([stack count] - 2) * 3, "",
5708 [file substringFromIndex:[directory length]]
5717 - (void) reloadData {
5720 [self setPackage:[database_ packageWithName:name_]];
5725 /* Package Controller {{{ */
5726 @interface CYPackageController : CYBrowserController <
5727 UIActionSheetDelegate
5729 _transient Database *database_;
5733 NSMutableArray *buttons_;
5734 UIBarButtonItem *button_;
5737 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5741 @implementation CYPackageController
5744 if (package_ != nil)
5757 - (NSURL *) navigationURL {
5758 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5761 /* XXX: this is not safe at all... localization of /fail/ */
5762 - (void) _clickButtonWithName:(NSString *)name {
5763 if ([name isEqualToString:UCLocalize("CLEAR")])
5764 [delegate_ clearPackage:package_];
5765 else if ([name isEqualToString:UCLocalize("INSTALL")])
5766 [delegate_ installPackage:package_];
5767 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5768 [delegate_ installPackage:package_];
5769 else if ([name isEqualToString:UCLocalize("REMOVE")])
5770 [delegate_ removePackage:package_];
5771 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5772 [delegate_ installPackage:package_];
5773 else _assert(false);
5776 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5777 NSString *context([sheet context]);
5779 if ([context isEqualToString:@"modify"]) {
5780 if (button != [sheet cancelButtonIndex]) {
5781 NSString *buttonName = [buttons_ objectAtIndex:button];
5782 [self _clickButtonWithName:buttonName];
5785 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5789 - (bool) _allowJavaScriptPanel {
5794 - (void) _customButtonClicked {
5795 int count([buttons_ count]);
5800 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5802 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5803 [buttons addObjectsFromArray:buttons_];
5805 UIActionSheet *sheet = [[[UIActionSheet alloc]
5808 cancelButtonTitle:nil
5809 destructiveButtonTitle:nil
5810 otherButtonTitles:nil
5813 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5815 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5816 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5818 [sheet setContext:@"modify"];
5820 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5824 // We don't want to allow non-commercial packages to do custom things to the install button,
5825 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5826 - (void) customButtonClicked {
5828 [super customButtonClicked];
5830 [self _customButtonClicked];
5833 - (void) reloadButtonClicked {
5834 // Don't reload a commerical package by tapping the loading button,
5835 // but if it's not an Install button, we should forward it on.
5836 if (![package_ uninstalled])
5837 [self _customButtonClicked];
5840 - (void) applyLoadingTitle {
5841 // Don't show "Loading" as the title. Ever.
5844 - (UIBarButtonItem *) rightButton {
5849 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5850 if ((self = [super init]) != nil) {
5851 database_ = database;
5852 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5853 name_ = [[NSString alloc] initWithString:name];
5854 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5858 - (void) reloadData {
5859 if (package_ != nil)
5860 [package_ autorelease];
5861 package_ = [database_ packageWithName:name_];
5863 [buttons_ removeAllObjects];
5865 if (package_ != nil) {
5868 package_ = [package_ retain];
5869 commercial_ = [package_ isCommercial];
5871 if ([package_ mode] != nil)
5872 [buttons_ addObject:UCLocalize("CLEAR")];
5873 if ([package_ source] == nil);
5874 else if ([package_ upgradableAndEssential:NO])
5875 [buttons_ addObject:UCLocalize("UPGRADE")];
5876 else if ([package_ uninstalled])
5877 [buttons_ addObject:UCLocalize("INSTALL")];
5879 [buttons_ addObject:UCLocalize("REINSTALL")];
5880 if (![package_ uninstalled])
5881 [buttons_ addObject:UCLocalize("REMOVE")];
5888 switch ([buttons_ count]) {
5889 case 0: title = nil; break;
5890 case 1: title = [buttons_ objectAtIndex:0]; break;
5891 default: title = UCLocalize("MODIFY"); break;
5894 button_ = [[UIBarButtonItem alloc]
5896 style:UIBarButtonItemStylePlain
5898 action:@selector(customButtonClicked)
5904 - (bool) isLoading {
5905 return commercial_ ? [super isLoading] : false;
5911 /* Package List Controller {{{ */
5912 @interface PackageListController : CYViewController <
5913 UITableViewDataSource,
5916 _transient Database *database_;
5918 NSMutableArray *packages_;
5919 NSMutableArray *sections_;
5921 NSMutableArray *index_;
5922 NSMutableDictionary *indices_;
5926 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5927 - (void) setDelegate:(id)delegate;
5928 - (void) resetCursor;
5932 @implementation PackageListController
5935 [packages_ release];
5936 [sections_ release];
5945 - (void) deselectWithAnimation:(BOOL)animated {
5946 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5949 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5950 CGRect base = [[self view] bounds];
5951 base.size.height -= bounds.size.height;
5952 base.origin = [list_ frame].origin;
5954 [UIView beginAnimations:nil context:NULL];
5955 [UIView setAnimationBeginsFromCurrentState:YES];
5956 [UIView setAnimationCurve:curve];
5957 [UIView setAnimationDuration:duration];
5958 [list_ setFrame:base];
5959 [UIView commitAnimations];
5962 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5963 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5966 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5967 [self resizeForKeyboardBounds:bounds duration:0];
5970 - (void) keyboardWillShow:(NSNotification *)notification {
5973 NSTimeInterval duration;
5974 UIViewAnimationCurve curve;
5975 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5976 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5977 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5978 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5980 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);
5981 UIViewController *base = self;
5982 while ([base parentViewController] != nil)
5983 base = [base parentViewController];
5984 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5985 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5987 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5990 - (void) keyboardWillHide:(NSNotification *)notification {
5991 NSTimeInterval duration;
5992 UIViewAnimationCurve curve;
5993 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5994 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5996 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5999 - (void) viewWillAppear:(BOOL)animated {
6000 [super viewWillAppear:animated];
6002 [self resizeForKeyboardBounds:CGRectZero];
6003 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6004 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6007 - (void) viewWillDisappear:(BOOL)animated {
6008 [super viewWillDisappear:animated];
6010 [self resizeForKeyboardBounds:CGRectZero];
6011 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6012 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6015 - (void) viewDidAppear:(BOOL)animated {
6016 [super viewDidAppear:animated];
6017 [self deselectWithAnimation:animated];
6020 - (void) didSelectPackage:(Package *)package {
6021 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6022 [view setDelegate:delegate_];
6023 [[self navigationController] pushViewController:view animated:YES];
6026 #if TryIndexedCollation
6027 + (BOOL) hasIndexedCollation {
6028 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6032 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6033 NSInteger count([sections_ count]);
6034 return count == 0 ? 1 : count;
6037 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6038 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6040 return [[sections_ objectAtIndex:section] name];
6043 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6044 if ([sections_ count] == 0)
6046 return [[sections_ objectAtIndex:section] count];
6049 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6050 @synchronized (database_) {
6051 if ([database_ era] != era_)
6054 Section *section([sections_ objectAtIndex:[path section]]);
6055 NSInteger row([path row]);
6056 Package *package([packages_ objectAtIndex:([section row] + row)]);
6057 return [[package retain] autorelease];
6060 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6061 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6063 cell = [[[PackageCell alloc] init] autorelease];
6064 [cell setPackage:[self packageAtIndexPath:path]];
6068 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6069 Package *package([self packageAtIndexPath:path]);
6070 package = [database_ packageWithName:[package id]];
6071 [self didSelectPackage:package];
6074 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6075 // XXX: is 20 the most optimal number here?
6076 return [packages_ count] > 20 ? index_ : nil;
6079 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6080 #if TryIndexedCollation
6081 if ([[self class] hasIndexedCollation]) {
6082 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6089 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6090 if ((self = [super init]) != nil) {
6091 database_ = database;
6092 title_ = [title copy];
6093 [[self navigationItem] setTitle:title_];
6095 #if TryIndexedCollation
6096 if ([[self class] hasIndexedCollation])
6097 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6100 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6102 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6104 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6105 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6107 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6108 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6109 [list_ setRowHeight:73];
6110 [[self view] addSubview:list_];
6112 [list_ setDataSource:self];
6113 [list_ setDelegate:self];
6117 - (void) setDelegate:(id)delegate {
6118 delegate_ = delegate;
6121 - (bool) hasPackage:(Package *)package {
6125 - (void) reloadData {
6128 era_ = [database_ era];
6129 NSArray *packages = [database_ packages];
6131 [packages_ removeAllObjects];
6132 [sections_ removeAllObjects];
6134 _profile(PackageTable$reloadData$Filter)
6135 for (Package *package in packages)
6136 if ([self hasPackage:package])
6137 [packages_ addObject:package];
6140 [indices_ removeAllObjects];
6142 Section *section = nil;
6144 #if TryIndexedCollation
6145 if ([[self class] hasIndexedCollation]) {
6146 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6147 NSArray *titles = [collation sectionIndexTitles];
6150 _profile(PackageTable$reloadData$Section)
6151 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6155 _profile(PackageTable$reloadData$Section$Package)
6156 package = [packages_ objectAtIndex:offset];
6157 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6160 while (secidx < index) {
6163 _profile(PackageTable$reloadData$Section$Allocate)
6164 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6167 _profile(PackageTable$reloadData$Section$Add)
6168 [sections_ addObject:section];
6172 [section addToCount];
6178 [index_ removeAllObjects];
6180 _profile(PackageTable$reloadData$Section)
6181 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6185 _profile(PackageTable$reloadData$Section$Package)
6186 package = [packages_ objectAtIndex:offset];
6187 index = [package index];
6190 if (section == nil || [section index] != index) {
6191 _profile(PackageTable$reloadData$Section$Allocate)
6192 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6195 [index_ addObject:[section name]];
6196 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6198 _profile(PackageTable$reloadData$Section$Add)
6199 [sections_ addObject:section];
6203 [section addToCount];
6208 _profile(PackageTable$reloadData$List)
6213 - (void) resetCursor {
6214 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6219 /* Filtered Package List Controller {{{ */
6220 @interface FilteredPackageListController : PackageListController {
6226 - (void) setObject:(id)object;
6227 - (void) setObject:(id)object forFilter:(SEL)filter;
6229 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6233 @implementation FilteredPackageListController
6241 - (void) setFilter:(SEL)filter {
6244 /* XXX: this is an unsafe optimization of doomy hell */
6245 Method method(class_getInstanceMethod([Package class], filter));
6246 _assert(method != NULL);
6247 imp_ = method_getImplementation(method);
6248 _assert(imp_ != NULL);
6251 - (void) setObject:(id)object {
6257 object_ = [object retain];
6260 - (void) setObject:(id)object forFilter:(SEL)filter {
6261 [self setFilter:filter];
6262 [self setObject:object];
6265 - (bool) hasPackage:(Package *)package {
6266 _profile(FilteredPackageTable$hasPackage)
6267 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6271 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6272 if ((self = [super initWithDatabase:database title:title]) != nil) {
6273 [self setFilter:filter];
6274 [self setObject:object];
6281 /* Home Controller {{{ */
6282 @interface HomeController : CYBrowserController {
6287 @implementation HomeController
6289 + (BOOL) shouldHideNavigationBar {
6293 - (NSURL *) navigationURL {
6294 return [NSURL URLWithString:@"cydia://home"];
6297 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6298 [super _setMoreHeaders:request];
6301 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6302 if (UniqueID_ != nil)
6303 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6305 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6308 - (void) aboutButtonClicked {
6309 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6311 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6312 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6313 [alert setCancelButtonIndex:0];
6316 @"Copyright (C) 2008-2011\n"
6317 "Jay Freeman (saurik)\n"
6318 "saurik@saurik.com\n"
6319 "http://www.saurik.com/"
6325 - (void) viewWillDisappear:(BOOL)animated {
6326 [super viewWillDisappear:animated];
6328 if ([[self class] shouldHideNavigationBar])
6329 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6332 - (void) viewWillAppear:(BOOL)animated {
6333 if (![self hasLoaded])
6334 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6336 [super viewWillAppear:animated];
6338 if ([[self class] shouldHideNavigationBar])
6339 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6342 - (void) viewDidLoad {
6343 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6344 initWithTitle:UCLocalize("ABOUT")
6345 style:UIBarButtonItemStylePlain
6347 action:@selector(aboutButtonClicked)
6353 /* Manage Controller {{{ */
6354 @interface ManageController : CYBrowserController {
6357 - (void) queueStatusDidChange;
6361 @implementation ManageController
6363 - (NSURL *) navigationURL {
6364 return [NSURL URLWithString:@"cydia://manage"];
6367 - (void) viewWillAppear:(BOOL)animated {
6368 if (![self hasLoaded])
6369 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6371 [super viewWillAppear:animated];
6374 - (void) viewDidLoad {
6375 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6376 initWithTitle:UCLocalize("SETTINGS")
6377 style:UIBarButtonItemStylePlain
6379 action:@selector(settingsButtonClicked)
6382 [self queueStatusDidChange];
6385 - (void) settingsButtonClicked {
6386 [delegate_ showSettings];
6390 - (void) queueButtonClicked {
6394 - (void) applyLoadingTitle {
6395 // Disable "Loading" title.
6398 - (void) applyRightButton {
6399 // Disable right button.
6403 - (void) queueStatusDidChange {
6405 if (!IsWildcat_ && Queuing_) {
6406 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6407 initWithTitle:UCLocalize("QUEUE")
6408 style:UIBarButtonItemStyleDone
6410 action:@selector(queueButtonClicked)
6413 [[self navigationItem] setRightBarButtonItem:nil];
6418 - (bool) isLoading {
6419 // Never show as loading.
6426 /* Refresh Bar {{{ */
6427 @interface RefreshBar : UINavigationBar {
6428 UIProgressIndicator *indicator_;
6429 UITextLabel *prompt_;
6430 UIProgressBar *progress_;
6431 UINavigationButton *cancel_;
6436 @implementation RefreshBar
6439 [indicator_ release];
6441 [progress_ release];
6446 - (void) positionViews {
6447 CGRect frame = [cancel_ frame];
6448 frame.size = [cancel_ sizeThatFits:frame.size];
6449 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6450 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6451 [cancel_ setFrame:frame];
6453 CGSize prgsize = {75, 100};
6455 [self frame].size.width - prgsize.width - 10,
6456 ([self frame].size.height - prgsize.height) / 2
6458 [progress_ setFrame:prgrect];
6460 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6461 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6462 CGRect indrect = {{indoffset, indoffset}, indsize};
6463 [indicator_ setFrame:indrect];
6465 CGSize prmsize = {215, indsize.height + 4};
6467 indoffset * 2 + indsize.width,
6468 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6470 [prompt_ setFrame:prmrect];
6473 - (void) setFrame:(CGRect)frame {
6474 [super setFrame:frame];
6475 [self positionViews];
6478 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6479 if ((self = [super initWithFrame:frame]) != nil) {
6480 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6482 [self setBarStyle:UIBarStyleBlack];
6484 UIBarStyle barstyle([self _barStyle:NO]);
6485 bool ugly(barstyle == UIBarStyleDefault);
6487 UIProgressIndicatorStyle style = ugly ?
6488 UIProgressIndicatorStyleMediumBrown :
6489 UIProgressIndicatorStyleMediumWhite;
6491 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6492 [indicator_ setStyle:style];
6493 [indicator_ startAnimation];
6494 [self addSubview:indicator_];
6496 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6497 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6498 [prompt_ setBackgroundColor:[UIColor clearColor]];
6499 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6500 [self addSubview:prompt_];
6502 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6503 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6504 [progress_ setStyle:0];
6505 [self addSubview:progress_];
6507 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6508 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6509 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6510 [cancel_ setBarStyle:barstyle];
6512 [self positionViews];
6517 [cancel_ removeFromSuperview];
6521 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6522 [progress_ setProgress:0];
6523 [self addSubview:cancel_];
6527 [cancel_ removeFromSuperview];
6530 - (void) setPrompt:(NSString *)prompt {
6531 [prompt_ setText:prompt];
6534 - (void) setProgress:(float)progress {
6535 [progress_ setProgress:progress];
6541 @class CYNavigationController;
6543 /* Cydia Tab Bar Controller {{{ */
6544 @interface CYTabBarController : UITabBarController <
6545 UITabBarControllerDelegate,
6548 _transient Database *database_;
6549 RefreshBar *refreshbar_;
6553 // XXX: ok, "updatedelegate_"?...
6554 _transient NSObject<CydiaDelegate> *updatedelegate_;
6557 UIViewController *remembered_;
6558 _transient UIViewController *transient_;
6561 - (NSArray *) navigationURLCollection;
6562 - (void) dropBar:(BOOL)animated;
6563 - (void) beginUpdate;
6564 - (void) raiseBar:(BOOL)animated;
6569 @implementation CYTabBarController
6571 - (void) setUnselectedViewController:(UIViewController *)transient {
6572 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6573 if (transient != nil) {
6574 if (transient_ == nil)
6575 remembered_ = [[controllers objectAtIndex:0] retain];
6576 transient_ = transient;
6577 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6578 [controllers replaceObjectAtIndex:0 withObject:transient_];
6579 [self setSelectedIndex:0];
6580 [self setViewControllers:controllers];
6581 [self concealTabBarSelection];
6582 } else if (remembered_ != nil) {
6583 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6584 transient_ = transient;
6585 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6586 [remembered_ release];
6588 [self setViewControllers:controllers];
6589 [self revealTabBarSelection];
6593 - (UIViewController *) unselectedViewController {
6597 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6598 if ([self unselectedViewController])
6599 [self setUnselectedViewController:nil];
6602 - (NSArray *) navigationURLCollection {
6603 NSMutableArray *items([NSMutableArray array]);
6605 // XXX: Should this deal with transient view controllers?
6606 for (id navigation in [self viewControllers]) {
6607 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6609 [items addObject:stack];
6615 - (void) reloadData {
6616 for (CYViewController *controller in [self viewControllers])
6617 [controller reloadData];
6619 [(CYNavigationController *)[self unselectedViewController] reloadData];
6623 [refreshbar_ release];
6624 [[NSNotificationCenter defaultCenter] removeObserver:self];
6629 - (id) initWithDatabase:(Database *)database {
6630 if ((self = [super init]) != nil) {
6631 database_ = database;
6632 [self setDelegate:self];
6634 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6635 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6637 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6641 - (void) setUpdate:(NSDate *)date {
6645 - (void) beginUpdate {
6646 [refreshbar_ start];
6649 [updatedelegate_ retainNetworkActivityIndicator];
6653 detachNewThreadSelector:@selector(performUpdate)
6659 - (void) performUpdate { _pooled
6661 status.setDelegate(self);
6662 [database_ updateWithStatus:status];
6665 performSelectorOnMainThread:@selector(completeUpdate)
6671 - (void) stopUpdateWithSelector:(SEL)selector {
6673 [updatedelegate_ releaseNetworkActivityIndicator];
6675 [self raiseBar:YES];
6678 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6681 - (void) completeUpdate {
6684 [self stopUpdateWithSelector:@selector(reloadData)];
6687 - (void) cancelUpdate {
6688 [self stopUpdateWithSelector:@selector(updateData)];
6691 - (void) cancelPressed {
6692 [self cancelUpdate];
6699 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6700 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6703 - (void) startProgress {
6706 - (bool) isCancelling:(size_t)received {
6710 - (void) setProgressTitle:(NSString *)title {
6711 [refreshbar_ setPrompt:title];
6714 - (void) setProgressPercent:(NSNumber *)percent {
6715 [refreshbar_ setProgress:[percent floatValue]];
6718 - (void) addProgressOutput:(NSString *)output {
6721 - (void) setUpdateDelegate:(id)delegate {
6722 updatedelegate_ = delegate;
6725 - (CGFloat) statusBarHeight {
6726 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6727 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6729 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6733 - (UIView *) transitionView {
6734 if ([self respondsToSelector:@selector(_transitionView)])
6735 return [self _transitionView];
6737 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6740 - (void) dropBar:(BOOL)animated {
6745 UIView *transition([self transitionView]);
6746 [[self view] addSubview:refreshbar_];
6748 CGRect barframe([refreshbar_ frame]);
6750 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6751 barframe.origin.y = [self statusBarHeight];
6753 barframe.origin.y = 0;
6755 [refreshbar_ setFrame:barframe];
6758 [UIView beginAnimations:nil context:NULL];
6760 CGRect viewframe = [transition frame];
6761 viewframe.origin.y += barframe.size.height;
6762 viewframe.size.height -= barframe.size.height;
6763 [transition setFrame:viewframe];
6766 [UIView commitAnimations];
6768 // Ensure bar has the proper width for our view, it might have changed
6769 barframe.size.width = viewframe.size.width;
6770 [refreshbar_ setFrame:barframe];
6772 // XXX: fix Apple's layout bug
6773 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6776 - (void) raiseBar:(BOOL)animated {
6781 UIView *transition([self transitionView]);
6782 [refreshbar_ removeFromSuperview];
6784 CGRect barframe([refreshbar_ frame]);
6787 [UIView beginAnimations:nil context:NULL];
6789 CGRect viewframe = [transition frame];
6790 viewframe.origin.y -= barframe.size.height;
6791 viewframe.size.height += barframe.size.height;
6792 [transition setFrame:viewframe];
6795 [UIView commitAnimations];
6797 // XXX: fix Apple's layout bug
6798 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6802 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6803 // XXX: fix Apple's layout bug
6804 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6808 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6809 bool dropped(dropped_);
6814 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6819 // XXX: fix Apple's layout bug
6820 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6823 - (void) statusBarFrameChanged:(NSNotification *)notification {
6832 /* Cydia Navigation Controller {{{ */
6833 @interface CYNavigationController : UINavigationController {
6834 _transient Database *database_;
6835 _transient id<UINavigationControllerDelegate> delegate_;
6838 - (NSArray *) navigationURLCollection;
6839 - (id) initWithDatabase:(Database *)database;
6840 - (void) reloadData;
6845 @implementation CYNavigationController
6847 - (NSArray *) navigationURLCollection {
6848 NSMutableArray *stack([NSMutableArray array]);
6850 for (CYViewController *controller in [self viewControllers]) {
6851 NSString *url = [[controller navigationURL] absoluteString];
6853 [stack addObject:url];
6859 - (void) reloadData {
6860 for (CYViewController *page in [self viewControllers]) {
6861 // Only reload controllers that have already loaded.
6862 // This prevents a page from accidentally loading too
6863 // early if it hasn't been shown on the screen yet.
6864 if ([page hasLoaded])
6869 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6870 delegate_ = delegate;
6873 - (id) initWithDatabase:(Database *)database {
6874 if ((self = [super init]) != nil) {
6875 database_ = database;
6882 /* Cydia:// Protocol {{{ */
6883 @interface CydiaURLProtocol : NSURLProtocol {
6888 @implementation CydiaURLProtocol
6890 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6891 NSURL *url([request URL]);
6894 NSString *scheme([[url scheme] lowercaseString]);
6895 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6900 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6904 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6905 id<NSURLProtocolClient> client([self client]);
6907 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6909 NSData *data(UIImagePNGRepresentation(icon));
6911 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6912 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6913 [client URLProtocol:self didLoadData:data];
6914 [client URLProtocolDidFinishLoading:self];
6918 - (void) startLoading {
6919 id<NSURLProtocolClient> client([self client]);
6920 NSURLRequest *request([self request]);
6922 NSURL *url([request URL]);
6923 NSString *href([url absoluteString]);
6925 NSString *path([href substringFromIndex:8]);
6926 NSRange slash([path rangeOfString:@"/"]);
6929 if (slash.location == NSNotFound) {
6933 command = [path substringToIndex:slash.location];
6934 path = [path substringFromIndex:(slash.location + 1)];
6937 Database *database([Database sharedInstance]);
6939 if ([command isEqualToString:@"package-icon"]) {
6942 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6943 Package *package([database packageWithName:path]);
6946 UIImage *icon([package icon]);
6947 [self _returnPNGWithImage:icon forRequest:request];
6948 } else if ([command isEqualToString:@"source-icon"]) {
6951 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6952 NSString *source(Simplify(path));
6953 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6955 icon = [UIImage applicationImageNamed:@"unknown.png"];
6956 [self _returnPNGWithImage:icon forRequest:request];
6957 } else if ([command isEqualToString:@"uikit-image"]) {
6960 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6961 UIImage *icon(_UIImageWithName(path));
6962 [self _returnPNGWithImage:icon forRequest:request];
6963 } else if ([command isEqualToString:@"section-icon"]) {
6966 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6967 NSString *section(Simplify(path));
6968 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6970 icon = [UIImage applicationImageNamed:@"unknown.png"];
6971 [self _returnPNGWithImage:icon forRequest:request];
6973 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6977 - (void) stopLoading {
6983 /* Section Controller {{{ */
6984 @interface SectionController : FilteredPackageListController {
6988 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6992 @implementation SectionController
6994 - (NSURL *) navigationURL {
6995 NSString *name = section_;
6999 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7002 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7005 title = UCLocalize("ALL_PACKAGES");
7006 else if (![name isEqual:@""])
7007 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7009 title = UCLocalize("NO_SECTION");
7011 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7018 /* Sections Controller {{{ */
7019 @interface SectionsController : CYViewController <
7020 UITableViewDataSource,
7023 _transient Database *database_;
7024 NSMutableArray *sections_;
7025 NSMutableArray *filtered_;
7030 - (id) initWithDatabase:(Database *)database;
7031 - (void) editButtonClicked;
7035 @implementation SectionsController
7038 [self releaseSubviews];
7039 [sections_ release];
7040 [filtered_ release];
7045 - (NSURL *) navigationURL {
7046 return [NSURL URLWithString:@"cydia://sections"];
7049 - (void) updateNavigationItem {
7050 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7051 if ([sections_ count] == 0) {
7052 [[self navigationItem] setRightBarButtonItem:nil];
7054 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7055 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7057 action:@selector(editButtonClicked)
7058 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7062 - (BOOL) isEditing {
7066 - (void) setEditing:(BOOL)editing {
7067 if ((editing_ = editing))
7070 [delegate_ updateData];
7072 [self updateNavigationItem];
7075 - (void) viewDidAppear:(BOOL)animated {
7076 [super viewDidAppear:animated];
7077 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7080 - (void) viewWillDisappear:(BOOL)animated {
7081 [super viewWillDisappear:animated];
7082 if (editing_) [self setEditing:NO];
7085 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7086 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7090 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7091 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7094 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7098 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7099 static NSString *reuseIdentifier = @"SectionCell";
7101 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7103 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7105 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7110 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7114 Section *section = [self sectionAtIndexPath:indexPath];
7116 SectionController *controller = [[[SectionController alloc]
7117 initWithDatabase:database_
7118 section:[section name]
7120 [controller setDelegate:delegate_];
7122 [[self navigationController] pushViewController:controller animated:YES];
7126 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7128 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7129 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7130 [list_ setRowHeight:45.0f];
7131 [list_ setDataSource:self];
7132 [list_ setDelegate:self];
7133 [[self view] addSubview:list_];
7136 - (void) viewDidLoad {
7137 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7140 - (void) releaseSubviews {
7145 - (id) initWithDatabase:(Database *)database {
7146 if ((self = [super init]) != nil) {
7147 database_ = database;
7149 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7150 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7154 - (void) reloadData {
7157 NSArray *packages = [database_ packages];
7159 [sections_ removeAllObjects];
7160 [filtered_ removeAllObjects];
7162 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7165 for (Package *package in packages) {
7166 NSString *name([package section]);
7167 NSString *key(name == nil ? @"" : name);
7171 _profile(SectionsView$reloadData$Section)
7172 section = [sections objectForKey:key];
7173 if (section == nil) {
7174 _profile(SectionsView$reloadData$Section$Allocate)
7175 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7176 [sections setObject:section forKey:key];
7181 [section addToCount];
7183 _profile(SectionsView$reloadData$Filter)
7184 if (![package valid] || ![package visible])
7192 [sections_ addObjectsFromArray:[sections allValues]];
7194 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7196 for (Section *section in sections_) {
7197 size_t count([section row]);
7201 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7202 [section setCount:count];
7203 [filtered_ addObject:section];
7206 [self updateNavigationItem];
7211 - (void) editButtonClicked {
7212 [self setEditing:(!editing_)];
7218 /* Changes Controller {{{ */
7219 @interface ChangesController : CYViewController <
7220 UITableViewDataSource,
7223 _transient Database *database_;
7225 CFMutableArrayRef packages_;
7226 NSMutableArray *sections_;
7229 BOOL hasSentFirstLoad_;
7232 - (id) initWithDatabase:(Database *)database;
7236 @implementation ChangesController
7239 [self releaseSubviews];
7240 CFRelease(packages_);
7241 [sections_ release];
7246 - (NSURL *) navigationURL {
7247 return [NSURL URLWithString:@"cydia://changes"];
7250 - (void) viewWillAppear:(BOOL)animated {
7251 // Loads after it appears, so don't load beforehand.
7253 [super viewWillAppear:animated];
7256 - (void) viewDidAppear:(BOOL)animated {
7257 [super viewDidAppear:animated];
7259 if (!hasSentFirstLoad_) {
7260 hasSentFirstLoad_ = YES;
7261 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7263 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7267 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7268 NSInteger count([sections_ count]);
7269 return count == 0 ? 1 : count;
7272 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7273 if ([sections_ count] == 0)
7275 return [[sections_ objectAtIndex:section] name];
7278 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7279 if ([sections_ count] == 0)
7281 return [[sections_ objectAtIndex:section] count];
7284 - (Package *) packageAtIndex:(NSUInteger)index {
7285 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7288 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7289 @synchronized (database_) {
7290 if ([database_ era] != era_)
7293 NSUInteger sectionIndex([path section]);
7294 if (sectionIndex >= [sections_ count])
7296 Section *section([sections_ objectAtIndex:sectionIndex]);
7297 NSInteger row([path row]);
7298 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7301 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7302 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7304 cell = [[[PackageCell alloc] init] autorelease];
7305 [cell setPackage:[self packageAtIndexPath:path]];
7309 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7310 Package *package([self packageAtIndexPath:path]);
7311 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7312 [view setDelegate:delegate_];
7313 [[self navigationController] pushViewController:view animated:YES];
7317 - (void) refreshButtonClicked {
7318 [delegate_ beginUpdate];
7319 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7322 - (void) upgradeButtonClicked {
7323 [delegate_ distUpgrade];
7327 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7329 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7330 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7331 [list_ setRowHeight:73];
7332 [list_ setDataSource:self];
7333 [list_ setDelegate:self];
7334 [[self view] addSubview:list_];
7337 - (void) viewDidLoad {
7338 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7341 - (void) releaseSubviews {
7346 - (id) initWithDatabase:(Database *)database {
7347 if ((self = [super init]) != nil) {
7348 database_ = database;
7350 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7351 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7355 // this mostly works because reloadData (below) is @synchronized (database_)
7356 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7357 - (void) _reloadPackages:(NSArray *)packages {
7358 CFRelease(packages_);
7359 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7362 _profile(ChangesController$_reloadPackages$Filter)
7363 for (Package *package in packages)
7364 if ([package upgradableAndEssential:YES] || [package visible])
7365 CFArrayAppendValue(packages_, package);
7368 _profile(ChangesController$_reloadPackages$radixSort)
7369 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7374 - (void) reloadData {
7375 @synchronized (database_) {
7376 era_ = [database_ era];
7377 NSArray *packages = [database_ packages];
7379 [sections_ removeAllObjects];
7382 UIProgressHUD *hud([delegate_ addProgressHUD]);
7383 [hud setText:UCLocalize("LOADING")];
7384 //NSLog(@"HUD:%@::%@", delegate_, hud);
7385 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7386 [delegate_ removeProgressHUD:hud];
7388 [self _reloadPackages:packages];
7391 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7392 Section *ignored = nil;
7393 Section *section = nil;
7397 bool unseens = false;
7399 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7401 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7402 Package *package = [self packageAtIndex:offset];
7404 BOOL uae = [package upgradableAndEssential:YES];
7408 time_t seen([package seen]);
7410 if (section == nil || last != seen) {
7414 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7417 _profile(ChangesController$reloadData$Allocate)
7418 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7419 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7420 [sections_ addObject:section];
7424 [section addToCount];
7425 } else if ([package ignored]) {
7426 if (ignored == nil) {
7427 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7429 [ignored addToCount];
7432 [upgradable addToCount];
7437 CFRelease(formatter);
7440 Section *last = [sections_ lastObject];
7441 size_t count = [last count];
7442 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7443 [sections_ removeLastObject];
7446 if ([ignored count] != 0)
7447 [sections_ insertObject:ignored atIndex:0];
7449 [sections_ insertObject:upgradable atIndex:0];
7454 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7455 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7456 style:UIBarButtonItemStylePlain
7458 action:@selector(upgradeButtonClicked)
7461 if (![delegate_ updating])
7462 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7463 initWithTitle:UCLocalize("REFRESH")
7464 style:UIBarButtonItemStylePlain
7466 action:@selector(refreshButtonClicked)
7474 /* Search Controller {{{ */
7475 @interface SearchController : FilteredPackageListController <
7478 UISearchBar *search_;
7482 - (id) initWithDatabase:(Database *)database;
7483 - (void) setSearchTerm:(NSString *)term;
7484 - (void) reloadData;
7488 @implementation SearchController
7495 - (NSURL *) navigationURL {
7496 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7497 return [NSURL URLWithString:@"cydia://search"];
7499 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7502 - (void) setSearchTerm:(NSString *)searchTerm {
7503 [search_ setText:searchTerm];
7507 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7508 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7509 [search_ resignFirstResponder];
7513 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7514 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7518 - (id) initWithDatabase:(Database *)database {
7519 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7520 search_ = [[UISearchBar alloc] init];
7524 - (void) viewDidAppear:(BOOL)animated {
7525 [super viewDidAppear:animated];
7527 if (!searchloaded_) {
7528 searchloaded_ = YES;
7529 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7530 [search_ layoutSubviews];
7531 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7533 UITextField *textField;
7534 if ([search_ respondsToSelector:@selector(searchField)])
7535 textField = [search_ searchField];
7537 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7539 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7540 [search_ setDelegate:self];
7541 [textField setEnablesReturnKeyAutomatically:NO];
7542 [[self navigationItem] setTitleView:textField];
7546 - (void) reloadData {
7547 [self setObject:[search_ text]];
7552 - (void) didSelectPackage:(Package *)package {
7553 [search_ resignFirstResponder];
7554 [super didSelectPackage:package];
7559 /* Package Settings Controller {{{ */
7560 @interface PackageSettingsController : CYViewController <
7561 UITableViewDataSource,
7564 _transient Database *database_;
7567 UITableView *table_;
7568 UISwitch *subscribedSwitch_;
7569 UISwitch *ignoredSwitch_;
7570 UITableViewCell *subscribedCell_;
7571 UITableViewCell *ignoredCell_;
7574 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7578 @implementation PackageSettingsController
7581 [self releaseSubviews];
7588 - (NSURL *) navigationURL {
7589 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7592 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7593 if (package_ == nil)
7596 if ([package_ installed] == nil)
7602 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7603 if (package_ == nil)
7606 // both sections contain just one item right now.
7610 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7614 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7616 return UCLocalize("SHOW_ALL_CHANGES_EX");
7618 return UCLocalize("IGNORE_UPGRADES_EX");
7621 - (void) onSubscribed:(id)control {
7622 bool value([control isOn]);
7623 if (package_ == nil)
7625 if ([package_ setSubscribed:value])
7626 [delegate_ updateData];
7629 - (void) _updateIgnored {
7630 const char *package([name_ UTF8String]);
7631 bool on([ignoredSwitch_ isOn]);
7633 pid_t pid(ExecFork());
7635 FILE *dpkg(popen("dpkg --set-selections", "w"));
7636 fwrite(package, strlen(package), 1, dpkg);
7639 fwrite(" hold\n", 6, 1, dpkg);
7641 fwrite(" install\n", 9, 1, dpkg);
7651 int result(waitpid(pid, &status, 0));
7654 _assert(result == pid);
7660 - (void) onIgnored:(id)control {
7661 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7662 [invocation setTarget:self];
7663 [invocation setSelector:@selector(_updateIgnored)];
7665 [delegate_ reloadDataWithInvocation:invocation];
7668 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7669 if (package_ == nil)
7672 switch ([indexPath section]) {
7673 case 0: return subscribedCell_;
7674 case 1: return ignoredCell_;
7683 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7685 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7686 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7687 [table_ setDataSource:self];
7688 [table_ setDelegate:self];
7689 [[self view] addSubview:table_];
7691 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7692 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7693 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7695 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7696 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7697 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7699 subscribedCell_ = [[UITableViewCell alloc] init];
7700 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7701 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7702 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7704 ignoredCell_ = [[UITableViewCell alloc] init];
7705 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7706 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7707 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7710 - (void) viewDidLoad {
7711 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7714 - (void) releaseSubviews {
7715 [ignoredCell_ release];
7718 [subscribedCell_ release];
7719 subscribedCell_ = nil;
7724 [ignoredSwitch_ release];
7725 ignoredSwitch_ = nil;
7727 [subscribedSwitch_ release];
7728 subscribedSwitch_ = nil;
7731 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7732 if ((self = [super init]) != nil) {
7733 database_ = database;
7734 name_ = [package retain];
7738 - (void) reloadData {
7741 if (package_ != nil)
7742 [package_ autorelease];
7743 package_ = [database_ packageWithName:name_];
7745 if (package_ != nil) {
7746 package_ = [package_ retain];
7747 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7748 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7749 } // XXX: what now, G?
7751 [table_ reloadData];
7757 /* Installed Controller {{{ */
7758 @interface InstalledController : FilteredPackageListController {
7762 - (id) initWithDatabase:(Database *)database;
7764 - (void) updateRoleButton;
7765 - (void) queueStatusDidChange;
7769 @implementation InstalledController
7775 - (NSURL *) navigationURL {
7776 return [NSURL URLWithString:@"cydia://installed"];
7779 - (id) initWithDatabase:(Database *)database {
7780 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7781 [self updateRoleButton];
7782 [self queueStatusDidChange];
7787 - (void) queueButtonClicked {
7792 - (void) queueStatusDidChange {
7796 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7797 initWithTitle:UCLocalize("QUEUE")
7798 style:UIBarButtonItemStyleDone
7800 action:@selector(queueButtonClicked)
7803 [[self navigationItem] setLeftBarButtonItem:nil];
7809 - (void) updateRoleButton {
7810 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7811 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7812 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7813 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7815 action:@selector(roleButtonClicked)
7819 - (void) roleButtonClicked {
7820 [self setObject:[NSNumber numberWithBool:expert_]];
7824 [self updateRoleButton];
7830 /* Source Cell {{{ */
7831 @interface SourceCell : CYTableViewCell <
7839 - (void) setSource:(Source *)source;
7843 @implementation SourceCell
7845 - (void) clearSource {
7855 - (void) setSource:(Source *)source {
7859 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7861 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7862 icon_ = [icon_ retain];
7864 origin_ = [[source name] retain];
7865 label_ = [[source uri] retain];
7867 [content_ setNeedsDisplay];
7875 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7876 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7877 UIView *content([self contentView]);
7878 CGRect bounds([content bounds]);
7880 content_ = [[ContentView alloc] initWithFrame:bounds];
7881 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7882 [content_ setBackgroundColor:[UIColor whiteColor]];
7883 [content addSubview:content_];
7885 [content_ setDelegate:self];
7886 [content_ setOpaque:YES];
7890 - (NSString *) accessibilityLabel {
7894 - (void) drawContentRect:(CGRect)rect {
7895 bool highlighted(highlighted_);
7896 float width(rect.size.width);
7899 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7906 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7910 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7915 /* Source Controller {{{ */
7916 @interface SourceController : FilteredPackageListController {
7917 _transient Source *source_;
7921 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7925 @implementation SourceController
7927 - (NSURL *) navigationURL {
7928 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7931 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7932 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7934 key_ = [[source key] retain];
7938 - (void) reloadData {
7939 source_ = [database_ sourceWithKey:key_];
7941 key_ = [[source_ key] retain];
7942 [self setObject:source_];
7943 [[self navigationItem] setTitle:[source_ label]];
7950 /* Sources Controller {{{ */
7951 @interface SourcesController : CYViewController <
7952 UITableViewDataSource,
7955 _transient Database *database_;
7957 NSMutableArray *sources_;
7961 UIProgressHUD *hud_;
7964 //NSURLConnection *installer_;
7965 NSURLConnection *trivial_;
7966 NSURLConnection *trivial_bz2_;
7967 NSURLConnection *trivial_gz_;
7968 //NSURLConnection *automatic_;
7973 - (id) initWithDatabase:(Database *)database;
7974 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7978 @implementation SourcesController
7980 - (void) _releaseConnection:(NSURLConnection *)connection {
7981 if (connection != nil) {
7982 [connection cancel];
7983 //[connection setDelegate:nil];
7984 [connection release];
7989 [self releaseSubviews];
7995 //[self _releaseConnection:installer_];
7996 [self _releaseConnection:trivial_];
7997 [self _releaseConnection:trivial_gz_];
7998 [self _releaseConnection:trivial_bz2_];
7999 //[self _releaseConnection:automatic_];
8005 - (NSURL *) navigationURL {
8006 return [NSURL URLWithString:@"cydia://sources"];
8009 - (void) viewDidAppear:(BOOL)animated {
8010 [super viewDidAppear:animated];
8011 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8014 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8015 return offset_ == 0 ? 1 : 2;
8018 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8019 switch (section + (offset_ == 0 ? 1 : 0)) {
8020 case 0: return UCLocalize("ENTERED_BY_USER");
8021 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8027 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8028 int count = [sources_ count];
8030 case 0: return (offset_ == 0 ? count : offset_);
8031 case 1: return count - offset_;
8037 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8039 switch (indexPath.section) {
8040 case 0: idx = indexPath.row; break;
8041 case 1: idx = indexPath.row + offset_; break;
8045 return [sources_ objectAtIndex:idx];
8048 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8049 static NSString *cellIdentifier = @"SourceCell";
8051 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8052 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8053 [cell setSource:[self sourceAtIndexPath:indexPath]];
8054 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8059 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8060 Source *source = [self sourceAtIndexPath:indexPath];
8062 SourceController *controller = [[[SourceController alloc]
8063 initWithDatabase:database_
8067 [controller setDelegate:delegate_];
8069 [[self navigationController] pushViewController:controller animated:YES];
8072 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8073 Source *source = [self sourceAtIndexPath:indexPath];
8074 return [source record] != nil;
8077 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8078 Source *source = [self sourceAtIndexPath:indexPath];
8079 [Sources_ removeObjectForKey:[source key]];
8080 [delegate_ syncData];
8084 [delegate_ addTrivialSource:href_];
8085 [delegate_ syncData];
8088 - (NSString *) getWarning {
8089 NSString *href(href_);
8090 NSRange colon([href rangeOfString:@"://"]);
8091 if (colon.location != NSNotFound)
8092 href = [href substringFromIndex:(colon.location + 3)];
8093 href = [href stringByAddingPercentEscapes];
8094 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8095 href = [href stringByCachingURLWithCurrentCDN];
8097 NSURL *url([NSURL URLWithString:href]);
8099 NSStringEncoding encoding;
8100 NSError *error(nil);
8102 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8103 return [warning length] == 0 ? nil : warning;
8107 - (void) _endConnection:(NSURLConnection *)connection {
8108 // XXX: the memory management in this method is horribly awkward
8110 NSURLConnection **field = NULL;
8111 if (connection == trivial_)
8113 else if (connection == trivial_bz2_)
8114 field = &trivial_bz2_;
8115 else if (connection == trivial_gz_)
8116 field = &trivial_gz_;
8117 _assert(field != NULL);
8118 [connection release];
8123 trivial_bz2_ == nil &&
8129 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8132 UIAlertView *alert = [[[UIAlertView alloc]
8133 initWithTitle:UCLocalize("SOURCE_WARNING")
8136 cancelButtonTitle:UCLocalize("CANCEL")
8138 UCLocalize("ADD_ANYWAY"),
8142 [alert setContext:@"warning"];
8143 [alert setNumberOfRows:1];
8147 } else if (error_ != nil) {
8148 UIAlertView *alert = [[[UIAlertView alloc]
8149 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8150 message:[error_ localizedDescription]
8152 cancelButtonTitle:UCLocalize("OK")
8153 otherButtonTitles:nil
8156 [alert setContext:@"urlerror"];
8159 UIAlertView *alert = [[[UIAlertView alloc]
8160 initWithTitle:UCLocalize("NOT_REPOSITORY")
8161 message:UCLocalize("NOT_REPOSITORY_EX")
8163 cancelButtonTitle:UCLocalize("OK")
8164 otherButtonTitles:nil
8167 [alert setContext:@"trivial"];
8171 [delegate_ setStatusBarShowsProgress:NO];
8172 [delegate_ removeProgressHUD:hud_];
8182 if (error_ != nil) {
8189 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8190 switch ([response statusCode]) {
8196 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8197 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8199 error_ = [error retain];
8200 [self _endConnection:connection];
8203 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8204 [self _endConnection:connection];
8207 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8208 NSMutableURLRequest *request = [NSMutableURLRequest
8209 requestWithURL:[NSURL URLWithString:href]
8210 cachePolicy:NSURLRequestUseProtocolCachePolicy
8211 timeoutInterval:120.0
8214 [request setHTTPMethod:method];
8216 if (Machine_ != NULL)
8217 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8218 if (UniqueID_ != nil)
8219 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8221 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8223 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8226 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8227 NSString *context([alert context]);
8229 if ([context isEqualToString:@"source"]) {
8232 NSString *href = [[alert textField] text];
8234 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8236 if (![href hasSuffix:@"/"])
8237 href_ = [href stringByAppendingString:@"/"];
8240 href_ = [href_ retain];
8242 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8243 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8244 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8245 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8249 // XXX: this is stupid
8250 hud_ = [[delegate_ addProgressHUD] retain];
8251 [hud_ setText:UCLocalize("VERIFYING_URL")];
8260 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8261 } else if ([context isEqualToString:@"trivial"])
8262 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8263 else if ([context isEqualToString:@"urlerror"])
8264 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8265 else if ([context isEqualToString:@"warning"]) {
8280 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8285 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8287 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8288 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8289 [list_ setRowHeight:56];
8290 [list_ setDataSource:self];
8291 [list_ setDelegate:self];
8292 [[self view] addSubview:list_];
8295 - (void) viewDidLoad {
8296 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8297 [self updateButtonsForEditingStatus:NO animated:NO];
8300 - (void) releaseSubviews {
8305 - (id) initWithDatabase:(Database *)database {
8306 if ((self = [super init]) != nil) {
8307 database_ = database;
8308 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8312 - (void) reloadData {
8316 if (!list.ReadMainList())
8319 [sources_ removeAllObjects];
8320 [sources_ addObjectsFromArray:[database_ sources]];
8322 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8325 int count([sources_ count]);
8327 for (int i = 0; i != count; i++) {
8328 if ([[sources_ objectAtIndex:i] record] == nil)
8333 [list_ setEditing:NO];
8334 [self updateButtonsForEditingStatus:NO animated:NO];
8338 - (void) showAddSourcePrompt {
8339 UIAlertView *alert = [[[UIAlertView alloc]
8340 initWithTitle:UCLocalize("ENTER_APT_URL")
8343 cancelButtonTitle:UCLocalize("CANCEL")
8345 UCLocalize("ADD_SOURCE"),
8349 [alert setContext:@"source"];
8350 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8352 [alert setNumberOfRows:1];
8353 [alert addTextFieldWithValue:@"http://" label:@""];
8355 UITextInputTraits *traits = [[alert textField] textInputTraits];
8356 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8357 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8358 [traits setKeyboardType:UIKeyboardTypeURL];
8359 // XXX: UIReturnKeyDone
8360 [traits setReturnKeyType:UIReturnKeyNext];
8365 - (void) addButtonClicked {
8366 [self showAddSourcePrompt];
8369 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8370 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8371 initWithTitle:UCLocalize("ADD")
8372 style:UIBarButtonItemStylePlain
8374 action:@selector(addButtonClicked)
8375 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8377 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8378 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8379 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8381 action:@selector(editButtonClicked)
8382 ] autorelease] animated:animated];
8384 if (IsWildcat_ && !editing)
8385 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8386 initWithTitle:UCLocalize("SETTINGS")
8387 style:UIBarButtonItemStylePlain
8389 action:@selector(settingsButtonClicked)
8393 - (void) settingsButtonClicked {
8394 [delegate_ showSettings];
8397 - (void) editButtonClicked {
8398 [list_ setEditing:![list_ isEditing] animated:YES];
8400 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8406 /* Settings Controller {{{ */
8407 @interface SettingsController : CYViewController <
8408 UITableViewDataSource,
8411 _transient Database *database_;
8412 // XXX: ok, "roledelegate_"?...
8413 _transient id roledelegate_;
8414 UITableView *table_;
8415 UISegmentedControl *segment_;
8419 - (void) showDoneButton;
8420 - (void) resizeSegmentedControl;
8424 @implementation SettingsController
8427 [self releaseSubviews];
8433 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8435 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8436 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8437 [table_ setDelegate:self];
8438 [table_ setDataSource:self];
8439 [[self view] addSubview:table_];
8441 NSArray *items = [NSArray arrayWithObjects:
8443 UCLocalize("HACKER"),
8444 UCLocalize("DEVELOPER"),
8446 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8447 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8448 [container_ addSubview:segment_];
8451 - (void) viewDidLoad {
8452 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8455 if ([Role_ isEqualToString:@"User"]) index = 0;
8456 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8457 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8459 [segment_ setSelectedSegmentIndex:index];
8460 [self showDoneButton];
8463 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8464 [self resizeSegmentedControl];
8467 - (void) releaseSubviews {
8474 [container_ release];
8478 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8479 if ((self = [super init]) != nil) {
8480 database_ = database;
8481 roledelegate_ = delegate;
8485 - (void) resizeSegmentedControl {
8486 CGFloat width = [[self view] frame].size.width;
8487 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8490 - (void) viewWillAppear:(BOOL)animated {
8491 [super viewWillAppear:animated];
8493 [self resizeSegmentedControl];
8496 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8497 [self resizeSegmentedControl];
8500 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8501 [self resizeSegmentedControl];
8505 NSString *role(nil);
8507 switch ([segment_ selectedSegmentIndex]) {
8508 case 0: role = @"User"; break;
8509 case 1: role = @"Hacker"; break;
8510 case 2: role = @"Developer"; break;
8515 if (![role isEqualToString:Role_]) {
8516 bool rolling(Role_ == nil);
8519 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8523 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8527 [roledelegate_ loadData];
8529 [roledelegate_ updateData];
8533 - (void) segmentChanged:(UISegmentedControl *)control {
8534 [self showDoneButton];
8537 - (void) saveAndClose {
8540 [[self navigationItem] setRightBarButtonItem:nil];
8541 [[self navigationController] dismissModalViewControllerAnimated:YES];
8544 - (void) doneButtonClicked {
8545 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8546 [spinner startAnimating];
8547 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8548 [[self navigationItem] setRightBarButtonItem:spinItem];
8550 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8553 - (void) showDoneButton {
8554 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8555 initWithTitle:UCLocalize("DONE")
8556 style:UIBarButtonItemStyleDone
8558 action:@selector(doneButtonClicked)
8559 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8562 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8563 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8567 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8571 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8572 return nil; // This method is required by the protocol.
8575 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8577 return UCLocalize("ROLE_EX");
8579 return [NSString stringWithFormat:
8580 @"%@: %@\n%@: %@\n%@: %@",
8581 UCLocalize("USER"), UCLocalize("USER_EX"),
8582 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8583 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8588 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8589 return section == 3 ? 44.0f : 0;
8592 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8593 return section == 3 ? container_ : nil;
8596 - (void) reloadData {
8598 [table_ reloadData];
8603 /* Stash Controller {{{ */
8604 @interface StashController : CYViewController {
8605 UIActivityIndicatorView *spinner_;
8612 @implementation StashController
8615 [self releaseSubviews];
8621 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8622 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8624 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8625 CGRect spinrect = [spinner_ frame];
8626 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8627 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8628 [spinner_ setFrame:spinrect];
8629 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8630 [[self view] addSubview:spinner_];
8631 [spinner_ startAnimating];
8634 captrect.size.width = [[self view] frame].size.width;
8635 captrect.size.height = 40.0f;
8636 captrect.origin.x = 0;
8637 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8638 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8639 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8640 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8641 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8642 [caption_ setTextColor:[UIColor whiteColor]];
8643 [caption_ setBackgroundColor:[UIColor clearColor]];
8644 [caption_ setShadowColor:[UIColor blackColor]];
8645 [caption_ setTextAlignment:UITextAlignmentCenter];
8646 [[self view] addSubview:caption_];
8649 statusrect.size.width = [[self view] frame].size.width;
8650 statusrect.size.height = 30.0f;
8651 statusrect.origin.x = 0;
8652 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8653 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8654 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8655 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8656 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8657 [status_ setTextColor:[UIColor whiteColor]];
8658 [status_ setBackgroundColor:[UIColor clearColor]];
8659 [status_ setShadowColor:[UIColor blackColor]];
8660 [status_ setTextAlignment:UITextAlignmentCenter];
8661 [[self view] addSubview:status_];
8664 - (void) releaseSubviews {
8678 @interface Cydia : UIApplication <
8679 ConfirmationControllerDelegate,
8680 ProgressControllerDelegate,
8682 UINavigationControllerDelegate,
8683 UITabBarControllerDelegate
8685 // XXX: evaluate all fields for _transient
8688 CYTabBarController *tabbar_;
8690 NSMutableArray *essential_;
8691 NSMutableArray *broken_;
8693 Database *database_;
8700 StashController *stash_;
8709 @implementation Cydia
8711 - (void) beginUpdate {
8712 [tabbar_ beginUpdate];
8716 return [tabbar_ updating];
8720 if ([broken_ count] != 0) {
8721 int count = [broken_ count];
8723 UIAlertView *alert = [[[UIAlertView alloc]
8724 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8725 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8727 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8729 UCLocalize("TEMPORARY_IGNORE"),
8733 [alert setContext:@"fixhalf"];
8735 } else if (!Ignored_ && [essential_ count] != 0) {
8736 int count = [essential_ count];
8738 UIAlertView *alert = [[[UIAlertView alloc]
8739 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8740 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8742 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8744 UCLocalize("UPGRADE_ESSENTIAL"),
8745 UCLocalize("COMPLETE_UPGRADE"),
8749 [alert setContext:@"upgrade"];
8754 - (void) _saveConfig {
8760 NSString *error(nil);
8762 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8764 NSError *error(nil);
8765 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8766 NSLog(@"failure to save metadata data: %@", error);
8771 NSLog(@"failure to serialize metadata: %@", error);
8776 // Navigation controller for the queuing badge.
8777 - (CYNavigationController *) queueNavigationController {
8778 NSArray *controllers = [tabbar_ viewControllers];
8779 return [controllers objectAtIndex:3];
8782 - (void) _updateData {
8785 [tabbar_ reloadData];
8787 CYNavigationController *navigation = [self queueNavigationController];
8789 id queuedelegate = nil;
8790 if ([[navigation viewControllers] count] > 0)
8791 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8793 [queuedelegate queueStatusDidChange];
8794 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8797 - (void) _refreshIfPossible:(NSDate *)update {
8798 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8800 bool recently = false;
8801 if (update != nil) {
8802 NSTimeInterval interval([update timeIntervalSinceNow]);
8803 if (interval <= 0 && interval > -(15*60))
8807 // Don't automatic refresh if:
8808 // - We already refreshed recently.
8809 // - We already auto-refreshed this launch.
8810 // - Auto-refresh is disabled.
8811 if (recently || loaded_ || ManualRefresh) {
8812 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8814 // If we are cancelling, we need to make sure it knows it's already loaded.
8818 // We are going to load, so remember that.
8822 SCNetworkReachabilityFlags flags; {
8823 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8824 SCNetworkReachabilityGetFlags(reachability, &flags);
8825 CFRelease(reachability);
8828 // XXX: this elaborate mess is what Apple is using to determine this? :(
8829 // XXX: do we care if the user has to intervene? maybe that's ok?
8831 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8832 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8833 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8834 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8835 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8836 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8840 // If we can reach the server, auto-refresh!
8842 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8847 - (void) refreshIfPossible {
8848 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8851 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8852 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8853 [hud setText:UCLocalize("RELOADING_DATA")];
8855 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8858 [self removeProgressHUD:hud];
8862 [essential_ removeAllObjects];
8863 [broken_ removeAllObjects];
8865 NSArray *packages([database_ packages]);
8866 for (Package *package in packages) {
8868 [broken_ addObject:package];
8869 if ([package upgradableAndEssential:NO]) {
8870 if ([package essential])
8871 [essential_ addObject:package];
8876 NSLog(@"changes:#%u", changes);
8878 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8881 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8882 [changesItem setBadgeValue:badge];
8883 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8884 [self setApplicationIconBadgeNumber:changes];
8887 [changesItem setBadgeValue:nil];
8888 [changesItem setAnimatedBadge:NO];
8889 [self setApplicationIconBadgeNumber:0];
8894 [self refreshIfPossible];
8897 - (void) updateData {
8908 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8909 _assert(file != NULL);
8911 for (NSString *key in [Sources_ allKeys]) {
8912 NSDictionary *source([Sources_ objectForKey:key]);
8914 fprintf(file, "%s %s %s\n",
8915 [[source objectForKey:@"Type"] UTF8String],
8916 [[source objectForKey:@"URI"] UTF8String],
8917 [[source objectForKey:@"Distribution"] UTF8String]
8923 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8924 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8926 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8927 [tabbar_ presentModalViewController:navigation animated:YES];
8930 detachNewThreadSelector:@selector(update_)
8933 title:UCLocalize("UPDATING_SOURCES")
8937 - (void) addTrivialSource:(NSString *)href {
8938 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8941 @"./", @"Distribution",
8942 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8947 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8948 @synchronized (self) {
8949 [self _reloadDataWithInvocation:invocation];
8953 - (void) reloadData {
8954 [self reloadDataWithInvocation:nil];
8958 pkgProblemResolver *resolver = [database_ resolver];
8960 resolver->InstallProtect();
8961 if (!resolver->Resolve(true))
8966 // XXX: this is a really crappy way of doing this.
8967 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8968 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8969 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8970 if ([tabbar_ updating])
8971 [tabbar_ cancelUpdate];
8973 if (![database_ prepare])
8976 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8977 [page setDelegate:self];
8978 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8979 [confirm_ setDelegate:self];
8982 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8983 [tabbar_ presentModalViewController:confirm_ animated:YES];
8989 @synchronized (self) {
8994 - (void) clearPackage:(Package *)package {
8995 @synchronized (self) {
9002 - (void) installPackages:(NSArray *)packages {
9003 @synchronized (self) {
9004 for (Package *package in packages)
9011 - (void) installPackage:(Package *)package {
9012 @synchronized (self) {
9019 - (void) removePackage:(Package *)package {
9020 @synchronized (self) {
9027 - (void) distUpgrade {
9028 @synchronized (self) {
9029 if (![database_ upgrade])
9036 @synchronized (self) {
9037 [self _reloadDataWithInvocation:nil];
9041 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9044 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
9046 if (navigation != nil) {
9047 [navigation pushViewController:progress animated:YES];
9049 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
9051 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9052 [tabbar_ presentModalViewController:navigation animated:YES];
9056 detachNewThreadSelector:@selector(perform)
9059 title:UCLocalize("RUNNING")
9065 - (void) progressControllerIsComplete:(ProgressController *)progress {
9070 - (void) showSettings {
9071 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9072 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9074 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9075 [tabbar_ presentModalViewController:nav animated:YES];
9078 - (void) retainNetworkActivityIndicator {
9079 if (activity_++ == 0)
9080 [self setNetworkActivityIndicatorVisible:YES];
9083 - (void) releaseNetworkActivityIndicator {
9084 if (--activity_ == 0)
9085 [self setNetworkActivityIndicatorVisible:NO];
9088 - (void) cancelAndClear:(bool)clear {
9089 @synchronized (self) {
9101 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9102 NSString *context([alert context]);
9104 if ([context isEqualToString:@"fixhalf"]) {
9105 if (button == [alert cancelButtonIndex]) {
9106 @synchronized (self) {
9107 for (Package *broken in broken_) {
9110 NSString *id = [broken id];
9111 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9112 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9113 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9114 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9120 } else if (button == [alert firstOtherButtonIndex]) {
9121 [broken_ removeAllObjects];
9125 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9126 } else if ([context isEqualToString:@"upgrade"]) {
9127 if (button == [alert firstOtherButtonIndex]) {
9128 @synchronized (self) {
9129 for (Package *essential in essential_)
9130 [essential install];
9135 } else if (button == [alert firstOtherButtonIndex] + 1) {
9137 } else if (button == [alert cancelButtonIndex]) {
9141 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9145 - (void) system:(NSString *)command { _pooled
9147 system([command UTF8String]);
9151 - (void) applicationWillSuspend {
9153 [super applicationWillSuspend];
9156 - (BOOL) isSafeToSuspend {
9157 // Use external process status API internally.
9158 // This is probably a really bad idea.
9159 // XXX: what is the point of this? does this solve anything at all?
9160 uint64_t status = 0;
9162 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9163 notify_get_state(notify_token, &status);
9164 notify_cancel(notify_token);
9167 return locked_ == 0 && status == 0;
9170 - (void) applicationSuspend:(__GSEvent *)event {
9171 if ([self isSafeToSuspend])
9172 [super applicationSuspend:event];
9175 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9176 if ([self isSafeToSuspend])
9177 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9180 - (void) _setSuspended:(BOOL)value {
9181 if ([self isSafeToSuspend])
9182 [super _setSuspended:value];
9185 - (UIProgressHUD *) addProgressHUD {
9186 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9187 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9189 [window_ setUserInteractionEnabled:NO];
9192 UIViewController *target = tabbar_;
9193 while ([target modalViewController] != nil) target = [target modalViewController];
9194 [[target view] addSubview:hud];
9200 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9202 [hud removeFromSuperview];
9203 [window_ setUserInteractionEnabled:YES];
9207 - (CYViewController *) pageForPackage:(NSString *)name {
9208 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9211 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9212 NSString *scheme([[url scheme] lowercaseString]);
9213 if ([[url absoluteString] length] <= [scheme length] + 3)
9215 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9216 NSArray *components([path pathComponents]);
9218 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9219 return [self pageForPackage:[components objectAtIndex:1]];
9221 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9224 NSString *base([components objectAtIndex:0]);
9226 CYViewController *controller = nil;
9228 if ([base isEqualToString:@"url"]) {
9229 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9230 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9231 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9232 } else if (!external && [components count] == 1) {
9233 if ([base isEqualToString:@"manage"]) {
9234 controller = [[[ManageController alloc] init] autorelease];
9237 if ([base isEqualToString:@"sources"]) {
9238 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9241 if ([base isEqualToString:@"home"]) {
9242 controller = [[[HomeController alloc] init] autorelease];
9245 if ([base isEqualToString:@"sections"]) {
9246 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9249 if ([base isEqualToString:@"search"]) {
9250 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9253 if ([base isEqualToString:@"changes"]) {
9254 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9257 if ([base isEqualToString:@"installed"]) {
9258 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9260 } else if ([components count] == 2) {
9261 NSString *argument = [components objectAtIndex:1];
9263 if ([base isEqualToString:@"package"]) {
9264 controller = [self pageForPackage:argument];
9267 if (!external && [base isEqualToString:@"search"]) {
9268 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9269 [(SearchController *)controller setSearchTerm:argument];
9272 if (!external && [base isEqualToString:@"sections"]) {
9273 if ([argument isEqualToString:@"all"])
9275 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9278 if (!external && [base isEqualToString:@"sources"]) {
9279 if ([argument isEqualToString:@"add"]) {
9280 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9281 [(SourcesController *)controller showAddSourcePrompt];
9283 Source *source = [database_ sourceWithKey:argument];
9284 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9288 if (!external && [base isEqualToString:@"launch"]) {
9289 [self launchApplicationWithIdentifier:argument suspended:NO];
9292 } else if (!external && [components count] == 3) {
9293 NSString *arg1 = [components objectAtIndex:1];
9294 NSString *arg2 = [components objectAtIndex:2];
9296 if ([base isEqualToString:@"package"]) {
9297 if ([arg2 isEqualToString:@"settings"]) {
9298 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9299 } else if ([arg2 isEqualToString:@"files"]) {
9300 if (Package *package = [database_ packageWithName:arg1]) {
9301 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9302 [(FileTable *)controller setPackage:package];
9308 [controller setDelegate:self];
9312 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9313 CYViewController *page([self pageForURL:url forExternal:external]);
9316 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9317 [nav setViewControllers:[NSArray arrayWithObject:page]];
9318 [tabbar_ setUnselectedViewController:nav];
9324 - (void) applicationOpenURL:(NSURL *)url {
9325 [super applicationOpenURL:url];
9327 if (!loaded_) starturl_ = [url retain];
9328 else [self openCydiaURL:url forExternal:YES];
9331 - (void) applicationWillResignActive:(UIApplication *)application {
9332 // Stop refreshing if you get a phone call or lock the device.
9333 if ([tabbar_ updating])
9334 [tabbar_ cancelUpdate];
9336 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9337 [super applicationWillResignActive:application];
9340 - (void) applicationWillTerminate:(UIApplication *)application {
9342 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9343 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9344 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9349 - (void) addStashController {
9351 stash_ = [[StashController alloc] init];
9352 [window_ addSubview:[stash_ view]];
9355 - (void) removeStashController {
9356 [[stash_ view] removeFromSuperview];
9362 [self setIdleTimerDisabled:YES];
9364 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9365 [self setStatusBarShowsProgress:YES];
9366 UpdateExternalStatus(1);
9368 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9370 UpdateExternalStatus(0);
9371 [self setStatusBarShowsProgress:NO];
9373 [self removeStashController];
9375 if (ExecFork() == 0) {
9376 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9377 perror("launchctl stop");
9381 - (void) setupViewControllers {
9382 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9384 NSMutableArray *items([NSMutableArray arrayWithObjects:
9385 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9386 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9387 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9388 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9392 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9393 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9395 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9398 NSMutableArray *controllers([NSMutableArray array]);
9399 for (UITabBarItem *item in items) {
9400 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9401 [controller setTabBarItem:item];
9402 [controllers addObject:controller];
9404 [tabbar_ setViewControllers:controllers];
9406 [tabbar_ setUpdateDelegate:self];
9409 - (CYEmulatedLoadingController *) showEmulatedLoadingControllerInView:(UIView *)view {
9410 static CYEmulatedLoadingController *fake = nil;
9414 fake = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9415 [view addSubview:[fake view]];
9417 [[fake view] removeFromSuperview];
9425 - (void) applicationDidFinishLaunching:(id)unused {
9429 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9430 [self setApplicationSupportsShakeToEdit:NO];
9432 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9433 initWithMemoryCapacity:524288
9434 diskCapacity:10485760
9435 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9438 [CYBrowserController _initialize];
9440 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9442 Font12_ = [[UIFont systemFontOfSize:12] retain];
9443 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9444 Font14_ = [[UIFont systemFontOfSize:14] retain];
9445 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9446 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9448 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9449 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9451 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9452 [window_ orderFront:self];
9453 [window_ makeKey:self];
9454 [window_ setHidden:NO];
9457 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9458 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9459 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9460 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9461 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9462 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9463 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9464 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9465 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9468 [self addStashController];
9469 // XXX: this would be much cleaner as a yieldToSelector:
9470 // that way the removeStashController could happen right here inline
9471 // we also could no longer require the useless stash_ field anymore
9472 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9476 database_ = [Database sharedInstance];
9478 [window_ setUserInteractionEnabled:NO];
9479 [self setupViewControllers];
9480 [self showEmulatedLoadingControllerInView:window_];
9482 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9489 [window_ setUserInteractionEnabled:YES];
9491 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9492 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9494 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9495 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9499 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9500 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9501 [window_ setUserInteractionEnabled:NO];
9507 [window_ addSubview:[tabbar_ view]];
9508 [self showEmulatedLoadingControllerInView:nil];
9509 [window_ setUserInteractionEnabled:YES];
9511 int selectedIndex = 0;
9512 NSMutableArray *items = nil;
9514 bool recently = false;
9515 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9516 if (closed != nil) {
9517 NSTimeInterval interval([closed timeIntervalSinceNow]);
9518 // XXX: Is 15 minutes the optimal time here?
9519 if (interval <= 0 && interval > -(15*60))
9523 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9524 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9527 for (NSArray *entry in items)
9528 if ([entry count] <= 0)
9531 if (!recently || !items || !enough) {
9533 items = [NSMutableArray array];
9534 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9535 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9536 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9538 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9540 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9541 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9543 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9546 [tabbar_ setSelectedIndex:selectedIndex];
9547 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9548 NSArray *stack = [items objectAtIndex:tab];
9549 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9550 NSMutableArray *current = [NSMutableArray array];
9552 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9553 NSString *addr = [stack objectAtIndex:nav];
9554 NSURL *url = [NSURL URLWithString:addr];
9555 CYViewController *page = [self pageForURL:url forExternal:NO];
9557 [current addObject:page];
9560 [navigation setViewControllers:current];
9563 // (Try to) show the startup URL.
9564 if (starturl_ != nil) {
9565 [self openCydiaURL:starturl_ forExternal:NO];
9566 [starturl_ release];
9571 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9572 if (item != nil && IsWildcat_) {
9573 [sheet showFromBarButtonItem:item animated:YES];
9575 [sheet showInView:window_];
9582 id Alloc_(id self, SEL selector) {
9583 id object = alloc_(self, selector);
9584 lprintf("[%s]A-%p\n", self->isa->name, object);
9589 id Dealloc_(id self, SEL selector) {
9590 id object = dealloc_(self, selector);
9591 lprintf("[%s]D-%p\n", self->isa->name, object);
9595 Class $WebDefaultUIKitDelegate;
9597 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9598 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9599 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9600 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9603 static NSNumber *shouldPlayKeyboardSounds;
9607 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9609 case 1104: // Keyboard Button Clicked
9610 case 1105: // Keyboard Delete Repeated
9611 if (shouldPlayKeyboardSounds == nil) {
9612 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9613 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9616 if (![shouldPlayKeyboardSounds boolValue])
9620 _UIHardware$_playSystemSound$(self, _cmd, sound);
9624 Class $UIApplication;
9626 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9627 static BOOL initialized = NO;
9628 static BOOL started = NO;
9630 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9631 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9633 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9634 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9635 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9636 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9638 if (initialized && !enabled) {
9640 [bundle performSelector:@selector(_accessibilityStopServer)];
9641 } else if (enabled) {
9645 [bundle performSelector:@selector(_accessibilityStartServer)];
9651 int main(int argc, char *argv[]) { _pooled
9654 if (Class $UIDevice = objc_getClass("UIDevice")) {
9655 UIDevice *device([$UIDevice currentDevice]);
9656 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9660 UIScreen *screen([UIScreen mainScreen]);
9661 if ([screen respondsToSelector:@selector(scale)])
9662 ScreenScale_ = [screen scale];
9666 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9667 if (ScreenScale_ > 1)
9668 [parts addObject:@"@2x"];
9669 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9670 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9672 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9674 /* Library Hacks {{{ */
9675 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9677 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9678 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9679 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9680 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9681 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9684 $UIHardware = objc_getClass("UIHardware");
9685 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9686 if (UIHardware$_playSystemSound$ != NULL) {
9687 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9688 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9691 $UIApplication = objc_getClass("UIApplication");
9692 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9693 if (UIApplication$_updateApplicationAccessibility != NULL) {
9694 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9695 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9698 /* Set Locale {{{ */
9699 Locale_ = CFLocaleCopyCurrent();
9700 Languages_ = [NSLocale preferredLanguages];
9701 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9702 //NSLog(@"%@", [Languages_ description]);
9705 if (Languages_ == nil || [Languages_ count] == 0)
9706 // XXX: consider just setting to C and then falling through?
9709 lang = [[Languages_ objectAtIndex:0] UTF8String];
9710 setenv("LANG", lang, true);
9713 //std::setlocale(LC_ALL, lang);
9714 NSLog(@"Setting Language: %s", lang);
9717 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9719 /* Parse Arguments {{{ */
9720 bool substrate(false);
9726 for (int argi(1); argi != argc; ++argi)
9727 if (strcmp(argv[argi], "--") == 0) {
9729 argv[argi] = argv[0];
9735 for (int argi(1); argi != arge; ++argi)
9736 if (strcmp(args[argi], "--substrate") == 0)
9739 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9743 App_ = [[NSBundle mainBundle] bundlePath];
9744 Home_ = NSHomeDirectory();
9750 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9751 alloc_ = alloc->method_imp;
9752 alloc->method_imp = (IMP) &Alloc_;*/
9754 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9755 dealloc_ = dealloc->method_imp;
9756 dealloc->method_imp = (IMP) &Dealloc_;*/
9758 /* System Information {{{ */
9762 size = sizeof(maxproc);
9763 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9764 perror("sysctlbyname(\"kern.maxproc\", ?)");
9765 else if (maxproc < 64) {
9767 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9768 perror("sysctlbyname(\"kern.maxproc\", #)");
9771 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9772 char *osversion = new char[size];
9773 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9774 perror("sysctlbyname(\"kern.osversion\", ?)");
9776 System_ = [NSString stringWithUTF8String:osversion];
9778 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9779 char *machine = new char[size];
9780 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9781 perror("sysctlbyname(\"hw.machine\", ?)");
9785 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9786 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9787 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9788 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9792 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9793 NSData *data((NSData *) ecid);
9794 size_t length([data length]);
9795 uint8_t bytes[length];
9796 [data getBytes:bytes];
9797 char string[length * 2 + 1];
9798 for (size_t i(0); i != length; ++i)
9799 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9800 ChipID_ = [NSString stringWithUTF8String:string];
9804 IOObjectRelease(service);
9808 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9810 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9811 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9812 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9814 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9815 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9816 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9818 if (mcc != NULL && mnc != NULL)
9819 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9826 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9827 Build_ = [system objectForKey:@"ProductBuildVersion"];
9828 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9829 Product_ = [info objectForKey:@"SafariProductVersion"];
9830 Safari_ = [info objectForKey:@"CFBundleVersion"];
9833 /* Load Database {{{ */
9835 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9837 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9839 if (Metadata_ == NULL)
9840 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9842 Settings_ = [Metadata_ objectForKey:@"Settings"];
9844 Packages_ = [Metadata_ objectForKey:@"Packages"];
9845 Sections_ = [Metadata_ objectForKey:@"Sections"];
9846 Sources_ = [Metadata_ objectForKey:@"Sources"];
9848 Token_ = [Metadata_ objectForKey:@"Token"];
9851 if (Settings_ != nil)
9852 Role_ = [Settings_ objectForKey:@"Role"];
9854 if (Sections_ == nil) {
9855 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9856 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9859 if (Sources_ == nil) {
9860 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9861 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9866 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9869 if (Packages_ != nil) {
9871 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9875 [Metadata_ removeObjectForKey:@"Packages"];
9881 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9883 #define MobileSubstrate_(name) \
9884 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) \
9885 dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL);
9887 MobileSubstrate_(Activator)
9888 MobileSubstrate_(libstatusbar)
9889 MobileSubstrate_(SimulatedKeyEvents)
9890 MobileSubstrate_(WinterBoard)
9892 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9893 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9895 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9897 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9898 unlink("/tmp/.cydia.fw");
9900 } else if (access("/User", F_OK) != 0 || version < 2) {
9903 system("/usr/libexec/cydia/firmware.sh");
9907 _assert([[NSFileManager defaultManager]
9908 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9909 withIntermediateDirectories:YES
9914 if (access("/tmp/cydia.chk", F_OK) == 0) {
9915 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9916 _assert(errno == ENOENT);
9917 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9918 _assert(errno == ENOENT);
9921 /* APT Initialization {{{ */
9922 _assert(pkgInitConfig(*_config));
9923 _assert(pkgInitSystem(*_config, _system));
9926 _config->Set("APT::Acquire::Translation", lang);
9928 // XXX: this timeout might be important :(
9929 //_config->Set("Acquire::http::Timeout", 15);
9931 _config->Set("Acquire::http::MaxParallel", 3);
9933 /* Color Choices {{{ */
9934 space_ = CGColorSpaceCreateDeviceRGB();
9936 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9937 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9938 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9939 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9940 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9941 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9942 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9943 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9944 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9946 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9947 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9949 /* UIKit Configuration {{{ */
9950 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9951 if ($GSFontSetUseLegacyFontMetrics != NULL)
9952 $GSFontSetUseLegacyFontMetrics(YES);
9954 // XXX: I have a feeling this was important
9955 //UIKeyboardDisableAutomaticAppearance();
9958 Colon_ = UCLocalize("COLON_DELIMITED");
9959 Elision_ = UCLocalize("ELISION");
9960 Error_ = UCLocalize("ERROR");
9961 Warning_ = UCLocalize("WARNING");
9964 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9966 CGColorSpaceRelease(space_);