1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
122 #include <Cytore.hpp>
124 #include "UICaboodle/BrowserView.h"
125 #include "SDURLCache/SDURLCache.h"
127 #include "substrate.h"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
202 #define CYPoolStart() \
203 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
205 #define CYPoolEnd() \
209 // Hash Functions/Structures {{{
210 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
218 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
220 static _finline NSString *CydiaURL(NSString *path) {
222 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
223 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
224 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
225 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
226 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
227 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
230 static _finline void UpdateExternalStatus(uint64_t newStatus) {
232 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
233 notify_set_state(notify_token, newStatus);
234 notify_cancel(notify_token);
236 notify_post("com.saurik.Cydia.status");
239 /* [NSObject yieldToSelector:(withObject:)] {{{*/
240 @interface NSObject (Cydia)
241 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
242 - (id) yieldToSelector:(SEL)selector;
245 @implementation NSObject (Cydia)
250 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
251 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
252 id object([[context objectAtIndex:1] nonretainedObjectValue]);
253 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
255 /* XXX: deal with exceptions */
256 id value([self performSelector:selector withObject:object]);
258 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
259 [context removeAllObjects];
260 if ([signature methodReturnLength] != 0 && value != nil)
261 [context addObject:value];
266 performSelectorOnMainThread:@selector(doNothing)
272 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
273 volatile bool stopped(false);
275 NSMutableArray *context([NSMutableArray arrayWithObjects:
276 [NSValue valueWithPointer:selector],
277 [NSValue valueWithNonretainedObject:object],
278 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
281 NSThread *thread([[[NSThread alloc]
283 selector:@selector(_yieldToContext:)
289 NSRunLoop *loop([NSRunLoop currentRunLoop]);
290 NSDate *future([NSDate distantFuture]);
292 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
294 return [context count] == 0 ? nil : [context objectAtIndex:0];
297 - (id) yieldToSelector:(SEL)selector {
298 return [self yieldToSelector:selector withObject:nil];
304 /* Cydia Alert View {{{ */
305 @interface CYAlertView : UIAlertView {
309 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
313 @implementation CYAlertView
315 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
316 if ((self = [super init]) != nil) {
317 [self setTitle:title];
318 [self setDelegate:self];
319 for (NSString *button in buttons) [self addButtonWithTitle:button];
320 [self setCancelButtonIndex:index];
324 - (void) _updateFrameForDisplay {
325 [super _updateFrameForDisplay];
326 if ([self cancelButtonIndex] == -1) {
327 NSArray *buttons = [self buttons];
328 if ([buttons count]) {
329 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
330 for (UIThreePartButton *button in buttons)
331 [button setBackground:background forState:0];
336 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
337 button_ = buttonIndex + 1;
341 [self dismissWithClickedButtonIndex:-1 animated:YES];
344 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
345 [self setRunsModal:YES];
354 /* NSForcedOrderingSearch doesn't work on the iPhone */
355 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
356 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
357 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
359 #define lprintf(args...) fprintf(stderr, args)
362 #define TraceLogging (1 && !ForRelease)
363 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
364 #define ProfileTimes (0 && !ForRelease)
365 #define ForSaurik (0 && !ForRelease)
366 #define LogBrowser (0 && !ForRelease)
367 #define TrackResize (0 && !ForRelease)
368 #define ManualRefresh (1 && !ForRelease)
369 #define ShowInternals (0 && !ForRelease)
370 #define AlwaysReload (0 && !ForRelease)
371 #define TryIndexedCollation (0 && !ForRelease)
375 #define _trace(args...)
380 #define _profile(name) {
383 #define PrintTimes() do {} while (false)
387 typedef uint32_t (*SKRadixFunction)(id, void *);
389 @interface NSMutableArray (Radix)
390 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
398 @implementation NSMutableArray (Radix)
400 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
401 size_t count([self count]);
402 struct RadixItem_ *swap(new RadixItem_[count * 2]);
404 for (size_t i(0); i != count; ++i) {
405 RadixItem_ &item(swap[i]);
408 id object([self objectAtIndex:i]);
409 item.key = function(object, argument);
412 struct RadixItem_ *lhs(swap), *rhs(swap + count);
414 static const size_t width = 32;
415 static const size_t bits = 11;
416 static const size_t slots = 1 << bits;
417 static const size_t passes = (width + (bits - 1)) / bits;
419 size_t *hist(new size_t[slots]);
421 for (size_t pass(0); pass != passes; ++pass) {
422 memset(hist, 0, sizeof(size_t) * slots);
424 for (size_t i(0); i != count; ++i) {
425 uint32_t key(lhs[i].key);
427 key &= _not(uint32_t) >> width - bits;
432 for (size_t i(0); i != slots; ++i) {
433 size_t local(offset);
438 for (size_t i(0); i != count; ++i) {
439 uint32_t key(lhs[i].key);
441 key &= _not(uint32_t) >> width - bits;
442 rhs[hist[key]++] = lhs[i];
445 RadixItem_ *tmp(lhs);
452 const void **values(new const void *[count]);
453 for (size_t i(0); i != count; ++i)
454 values[i] = [self objectAtIndex:lhs[i].index];
455 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
463 /* Insertion Sort {{{ */
465 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
466 const char *ptr = (const char *)list;
468 CFIndex half = count / 2;
469 const char *probe = ptr + elementSize * half;
470 CFComparisonResult cr = comparator(element, probe, context);
471 if (0 == cr) return (probe - (const char *)list) / elementSize;
472 ptr = (cr < 0) ? ptr : probe + elementSize;
473 count = (cr < 0) ? half : (half + (count & 1) - 1);
475 return (ptr - (const char *)list) / elementSize;
478 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
479 const char *ptr = (const char *)list;
481 CFIndex half = count / 2;
482 const char *probe = ptr + elementSize * half;
483 CFComparisonResult cr = comparator(element, probe, context);
484 if (0 == cr) return (probe - (const char *)list) / elementSize;
485 ptr = (cr < 0) ? ptr : probe + elementSize;
486 count = (cr < 0) ? half : (half + (count & 1) - 1);
488 return (ptr - (const char *)list) / elementSize;
491 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
492 if (range.length == 0)
494 const void **values(new const void *[range.length]);
495 CFArrayGetValues(array, range, values);
497 #if HistogramInsertionSort > 0
498 uint32_t total(0), *offsets(new uint32_t[range.length]);
501 for (CFIndex index(1); index != range.length; ++index) {
502 const void *value(values[index]);
503 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
504 CFIndex correct(index);
505 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
506 #if HistogramInsertionSort > 1
507 NSLog(@"%@ < %@", value, values[correct - 1]);
512 if (correct != index) {
513 size_t offset(index - correct);
514 #if HistogramInsertionSort
518 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
520 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
521 values[correct] = value;
525 CFArrayReplaceValues(array, range, values, range.length);
528 #if HistogramInsertionSort > 0
529 for (CFIndex index(0); index != range.length; ++index)
530 if (offsets[index] != 0)
531 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
532 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
539 /* Apple Bug Fixes {{{ */
540 @implementation UIWebDocumentView (Cydia)
542 - (void) _setScrollerOffset:(CGPoint)offset {
543 UIScroller *scroller([self _scroller]);
545 CGSize size([scroller contentSize]);
546 CGSize bounds([scroller bounds].size);
549 max.x = size.width - bounds.width;
550 max.y = size.height - bounds.height;
558 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
559 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
561 [scroller setOffset:offset];
567 @implementation WebScriptObject (NSFastEnumeration)
569 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
570 size_t length([self count] - state->state);
573 else if (length > count)
575 for (size_t i(0); i != length; ++i)
576 objects[i] = [self objectAtIndex:state->state++];
577 state->itemsPtr = objects;
578 state->mutationsPtr = (unsigned long *) self;
584 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
585 size_t length([self length] - state->state);
588 else if (length > count)
590 for (size_t i(0); i != length; ++i)
591 objects[i] = [self item:state->state++];
592 state->itemsPtr = objects;
593 state->mutationsPtr = (unsigned long *) self;
597 /* Cydia NSString Additions {{{ */
598 @interface NSString (Cydia)
599 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
600 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
601 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
602 - (NSComparisonResult) compareByPath:(NSString *)other;
603 - (NSString *) stringByCachingURLWithCurrentCDN;
604 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
607 @implementation NSString (Cydia)
609 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
610 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
613 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
614 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
615 memcpy(data, bytes, length);
616 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
619 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
620 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
623 - (NSComparisonResult) compareByPath:(NSString *)other {
624 NSString *prefix = [self commonPrefixWithString:other options:0];
625 size_t length = [prefix length];
627 NSRange lrange = NSMakeRange(length, [self length] - length);
628 NSRange rrange = NSMakeRange(length, [other length] - length);
630 lrange = [self rangeOfString:@"/" options:0 range:lrange];
631 rrange = [other rangeOfString:@"/" options:0 range:rrange];
633 NSComparisonResult value;
635 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
636 value = NSOrderedSame;
637 else if (lrange.location == NSNotFound)
638 value = NSOrderedAscending;
639 else if (rrange.location == NSNotFound)
640 value = NSOrderedDescending;
642 value = NSOrderedSame;
644 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
645 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
646 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
647 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
649 NSComparisonResult result = [lpath compare:rpath];
650 return result == NSOrderedSame ? value : result;
653 - (NSString *) stringByCachingURLWithCurrentCDN {
655 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
656 withString:@"://cache.cydia.saurik.com/"
660 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
661 return [(id)CFURLCreateStringByAddingPercentEscapes(
666 kCFStringEncodingUTF8
673 /* C++ NSString Wrapper Cache {{{ */
674 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
675 return size == 0 ? NULL :
676 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
677 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
680 static _finline CFStringRef CYStringCreate(const char *data) {
681 return CYStringCreate(data, strlen(data));
690 _finline void clear_() {
691 if (cache_ != NULL) {
698 _finline bool empty() const {
702 _finline size_t size() const {
706 _finline char *data() const {
710 _finline void clear() {
715 _finline CYString() :
722 _finline ~CYString() {
726 void operator =(const CYString &rhs) {
730 if (rhs.cache_ == nil)
733 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
736 void copy(apr_pool_t *pool) {
737 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
738 memcpy(temp, data_, size_);
743 void set(apr_pool_t *pool, const char *data, size_t size) {
749 data_ = const_cast<char *>(data);
757 _finline void set(apr_pool_t *pool, const char *data) {
758 set(pool, data, data == NULL ? 0 : strlen(data));
761 _finline void set(apr_pool_t *pool, const std::string &rhs) {
762 set(pool, rhs.data(), rhs.size());
765 bool operator ==(const CYString &rhs) const {
766 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
769 _finline operator CFStringRef() {
771 cache_ = CYStringCreate(data_, size_);
775 _finline operator id() {
776 return (NSString *) static_cast<CFStringRef>(*this);
779 _finline operator const char *() {
780 return reinterpret_cast<const char *>(data_);
784 /* C++ NSString Algorithm Adapters {{{ */
786 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
789 struct NSStringMapHash :
790 std::unary_function<NSString *, size_t>
792 _finline size_t operator ()(NSString *value) const {
793 return CFStringHashNSString((CFStringRef) value);
797 struct NSStringMapLess :
798 std::binary_function<NSString *, NSString *, bool>
800 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
801 return [lhs compare:rhs] == NSOrderedAscending;
805 struct NSStringMapEqual :
806 std::binary_function<NSString *, NSString *, bool>
808 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
809 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
810 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
811 //[lhs isEqualToString:rhs];
816 /* Perl-Compatible RegEx {{{ */
826 Pcre(const char *regex) :
831 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
834 lprintf("%d:%s\n", offset, error);
838 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
839 matches_ = new int[(capture_ + 1) * 3];
847 NSString *operator [](size_t match) {
848 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
851 bool operator ()(NSString *data) {
852 // XXX: length is for characters, not for bytes
853 return operator ()([data UTF8String], [data length]);
856 bool operator ()(const char *data, size_t size) {
858 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
862 /* Mime Addresses {{{ */
863 @interface Address : NSObject {
869 - (NSString *) address;
871 - (void) setAddress:(NSString *)address;
873 + (Address *) addressWithString:(NSString *)string;
874 - (Address *) initWithString:(NSString *)string;
878 @implementation Address
887 - (NSString *) name {
891 - (NSString *) address {
895 - (void) setAddress:(NSString *)address {
897 [address_ autorelease];
901 address_ = [address retain];
904 + (Address *) addressWithString:(NSString *)string {
905 return [[[Address alloc] initWithString:string] autorelease];
908 + (NSArray *) _attributeKeys {
909 return [NSArray arrayWithObjects:
915 - (NSArray *) attributeKeys {
916 return [[self class] _attributeKeys];
919 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
920 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
923 - (Address *) initWithString:(NSString *)string {
924 if ((self = [super init]) != nil) {
925 const char *data = [string UTF8String];
926 size_t size = [string length];
928 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
930 if (address_r(data, size)) {
931 name_ = [address_r[1] retain];
932 address_ = [address_r[2] retain];
934 name_ = [string retain];
942 /* CoreGraphics Primitives {{{ */
947 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
948 CGFloat color[] = {red, green, blue, alpha};
949 return CGColorCreate(space, color);
958 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
959 color_(Create_(space, red, green, blue, alpha))
961 Set(space, red, green, blue, alpha);
966 CGColorRelease(color_);
973 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
975 color_ = Create_(space, red, green, blue, alpha);
978 operator CGColorRef() {
984 /* Random Global Variables {{{ */
985 static const int PulseInterval_ = 50000;
987 static const NSString *UI_;
990 static bool RestartSubstrate_;
991 static NSArray *Finishes_;
993 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
994 #define NotifyConfig_ "/etc/notify.conf"
996 static bool Queuing_;
998 static CYColor Blue_;
999 static CYColor Blueish_;
1000 static CYColor Black_;
1001 static CYColor Off_;
1002 static CYColor White_;
1003 static CYColor Gray_;
1004 static CYColor Green_;
1005 static CYColor Purple_;
1006 static CYColor Purplish_;
1008 static UIColor *InstallingColor_;
1009 static UIColor *RemovingColor_;
1011 static NSString *App_;
1012 static NSString *Home_;
1014 static BOOL Advanced_;
1015 static BOOL Ignored_;
1017 static UIFont *Font12_;
1018 static UIFont *Font12Bold_;
1019 static UIFont *Font14_;
1020 static UIFont *Font18Bold_;
1021 static UIFont *Font22Bold_;
1023 static const char *Machine_ = NULL;
1024 static NSString *System_ = nil;
1025 static NSString *SerialNumber_ = nil;
1026 static NSString *ChipID_ = nil;
1027 static NSString *Token_ = nil;
1028 static NSString *UniqueID_ = nil;
1029 static NSString *PLMN_ = nil;
1030 static NSString *Build_ = nil;
1031 static NSString *Product_ = nil;
1032 static NSString *Safari_ = nil;
1034 static CFLocaleRef Locale_;
1035 static NSArray *Languages_;
1036 static CGColorSpaceRef space_;
1038 static NSDictionary *SectionMap_;
1039 static NSMutableDictionary *Metadata_;
1040 static _transient NSMutableDictionary *Settings_;
1041 static _transient NSString *Role_;
1042 static _transient NSMutableDictionary *Packages_;
1043 static _transient NSMutableDictionary *Sections_;
1044 static _transient NSMutableDictionary *Sources_;
1045 static bool Changed_;
1049 static CGFloat ScreenScale_;
1052 /* Display Helpers {{{ */
1053 inline float Interpolate(float begin, float end, float fraction) {
1054 return (end - begin) * fraction + begin;
1057 static _finline const char *StripVersion_(const char *version) {
1058 const char *colon(strchr(version, ':'));
1059 return colon == NULL ? version : colon + 1;
1062 NSString *LocalizeSection(NSString *section) {
1063 static Pcre title_r("^(.*?) \\((.*)\\)$");
1064 if (title_r(section)) {
1065 NSString *parent(title_r[1]);
1066 NSString *child(title_r[2]);
1068 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1069 LocalizeSection(parent),
1070 LocalizeSection(child)
1074 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1077 NSString *Simplify(NSString *title) {
1078 const char *data = [title UTF8String];
1079 size_t size = [title length];
1081 static Pcre square_r("^\\[(.*)\\]$");
1082 if (square_r(data, size))
1083 return Simplify(square_r[1]);
1085 static Pcre paren_r("^\\((.*)\\)$");
1086 if (paren_r(data, size))
1087 return Simplify(paren_r[1]);
1089 static Pcre title_r("^(.*?) \\((.*)\\)$");
1090 if (title_r(data, size))
1091 return Simplify(title_r[1]);
1097 NSString *GetLastUpdate() {
1098 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1101 return UCLocalize("NEVER_OR_UNKNOWN");
1103 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1104 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1106 CFRelease(formatter);
1108 return [(NSString *) formatted autorelease];
1111 bool isSectionVisible(NSString *section) {
1112 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1113 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1114 return hidden == nil || ![hidden boolValue];
1119 /* Delegate Prototypes {{{ */
1123 @interface NSObject (ProgressDelegate)
1126 @protocol ProgressDelegate
1127 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1128 - (void) setProgressTitle:(NSString *)title;
1129 - (void) setProgressPercent:(NSNumber *)percent;
1130 - (void) startProgress;
1131 - (void) addProgressOutput:(NSString *)output;
1132 - (bool) isProgressCancelled;
1135 @protocol ConfigurationDelegate
1136 - (void) repairWithSelector:(SEL)selector;
1137 - (void) setConfigurationData:(NSString *)data;
1140 @class CYPackageController;
1142 @protocol CydiaDelegate
1143 - (void) retainNetworkActivityIndicator;
1144 - (void) releaseNetworkActivityIndicator;
1145 - (void) clearPackage:(Package *)package;
1146 - (void) installPackage:(Package *)package;
1147 - (void) installPackages:(NSArray *)packages;
1148 - (void) removePackage:(Package *)package;
1149 - (void) beginUpdate;
1151 - (void) distUpgrade;
1153 - (void) updateData;
1155 - (void) addTrivialSource:(NSString *)href;
1156 - (void) showSettings;
1157 - (UIProgressHUD *) addProgressHUD;
1158 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1159 - (CYViewController *) pageForPackage:(NSString *)name;
1160 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1161 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1164 static NSObject<CydiaDelegate> *CydiaApp;
1167 /* Status Delegation {{{ */
1169 public pkgAcquireStatus
1172 _transient NSObject<ProgressDelegate> *delegate_;
1180 void setDelegate(id delegate) {
1181 delegate_ = delegate;
1184 NSObject<ProgressDelegate> *getDelegate() const {
1188 virtual bool MediaChange(std::string media, std::string drive) {
1192 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1195 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1196 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1198 performSelectorOnMainThread:@selector(setProgressTitle:)
1199 withObject:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]
1204 virtual void Done(pkgAcquire::ItemDesc &item) {
1207 virtual void Fail(pkgAcquire::ItemDesc &item) {
1209 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1210 item.Owner->Status == pkgAcquire::Item::StatDone
1214 std::string &error(item.Owner->ErrorText);
1218 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1219 NSArray *fields([description componentsSeparatedByString:@" "]);
1220 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1222 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1223 withObject:[NSArray arrayWithObjects:
1224 [NSString stringWithUTF8String:error.c_str()],
1231 virtual bool Pulse(pkgAcquire *Owner) {
1232 bool value = pkgAcquireStatus::Pulse(Owner);
1235 double(CurrentBytes + CurrentItems) /
1236 double(TotalBytes + TotalItems)
1239 [delegate_ setProgressPercent:[NSNumber numberWithFloat:percent]];
1240 return [delegate_ isProgressCancelled] ? false : value;
1243 virtual void Start() {
1244 pkgAcquireStatus::Start();
1245 [delegate_ startProgress];
1248 virtual void Stop() {
1249 pkgAcquireStatus::Stop();
1254 /* Database Interface {{{ */
1255 typedef std::map< unsigned long, _H<Source> > SourceMap;
1257 @interface Database : NSObject {
1263 pkgCacheFile cache_;
1264 pkgDepCache::Policy *policy_;
1265 pkgRecords *records_;
1266 pkgProblemResolver *resolver_;
1267 pkgAcquire *fetcher_;
1269 SPtr<pkgPackageManager> manager_;
1270 pkgSourceList *list_;
1272 SourceMap sourceMap_;
1273 NSMutableArray *sourceList_;
1275 CFMutableArrayRef packages_;
1277 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1284 std::map<const char *, _H<NSString> > sections_;
1287 + (Database *) sharedInstance;
1290 - (void) _readCydia:(NSNumber *)fd;
1291 - (void) _readStatus:(NSNumber *)fd;
1292 - (void) _readOutput:(NSNumber *)fd;
1296 - (Package *) packageWithName:(NSString *)name;
1298 - (pkgCacheFile &) cache;
1299 - (pkgDepCache::Policy *) policy;
1300 - (pkgRecords *) records;
1301 - (pkgProblemResolver *) resolver;
1302 - (pkgAcquire &) fetcher;
1303 - (pkgSourceList &) list;
1304 - (NSArray *) packages;
1305 - (NSArray *) sources;
1306 - (Source *) sourceWithKey:(NSString *)key;
1307 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1315 - (void) updateWithStatus:(Status &)status;
1317 - (void) setDelegate:(id)delegate;
1318 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1320 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1324 /* Delegate Helpers {{{ */
1325 @implementation NSObject (ProgressDelegate)
1327 - (void) _setProgressErrorPackage:(NSArray *)args {
1328 [self performSelector:@selector(setProgressError:forPackage:)
1329 withObject:[args objectAtIndex:0]
1330 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1334 - (void) _setProgressErrorTitle:(NSArray *)args {
1335 [self performSelector:@selector(setProgressError:withTitle:)
1336 withObject:[args objectAtIndex:0]
1337 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1341 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1342 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1343 withObject:[NSArray arrayWithObjects:error, title, nil]
1348 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1349 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1351 [self performSelector:@selector(setProgressError:withTitle:)
1353 withObject:(package == nil ? id : [package name])
1360 // Cytore Definitions {{{
1361 struct PackageValue :
1364 Cytore::Offset<PackageValue> next_;
1366 uint32_t index_ : 23;
1367 uint32_t subscribed_ : 1;
1384 Cytore::Offset<PackageValue> packages_[1 << 16];
1387 static Cytore::File<MetaValue> MetaFile_;
1389 // Cytore Helper Functions {{{
1390 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1391 SplitHash nhash = { hashlittle(name, length) };
1393 PackageValue *metadata;
1395 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1396 offset: if (offset->IsNull()) {
1397 *offset = MetaFile_.New<PackageValue>(length + 1);
1398 metadata = &MetaFile_.Get(*offset);
1400 if (metadata == NULL) {
1404 metadata = new PackageValue();
1405 memset(metadata, 0, sizeof(*metadata));
1408 memcpy(metadata->name_, name, length + 1);
1409 metadata->nhash_ = nhash.u16[1];
1411 metadata = &MetaFile_.Get(*offset);
1413 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1414 offset = &metadata->next_;
1422 static void PackageImport(const void *key, const void *value, void *context) {
1423 bool &fail(*reinterpret_cast<bool *>(context));
1426 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1427 NSLog(@"failed to import package %@", key);
1431 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1432 NSDictionary *package((NSDictionary *) value);
1434 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1435 if ([subscribed boolValue] && !metadata->subscribed_)
1436 metadata->subscribed_ = true;
1438 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1439 time_t time([date timeIntervalSince1970]);
1440 if (metadata->first_ > time || metadata->first_ == 0)
1441 metadata->first_ = time;
1444 NSDate *date([package objectForKey:@"LastSeen"]);
1445 NSString *version([package objectForKey:@"LastVersion"]);
1447 if (date != nil && version != nil) {
1448 time_t time([date timeIntervalSince1970]);
1449 if (metadata->last_ < time || metadata->last_ == 0)
1450 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1451 size_t length(strlen(buffer));
1452 uint16_t vhash(hashlittle(buffer, length));
1454 size_t capped(std::min<size_t>(8, length));
1455 char *latest(buffer + length - capped);
1457 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1458 metadata->vhash_ = vhash;
1460 metadata->last_ = time;
1466 /* Source Class {{{ */
1467 @interface Source : NSObject {
1468 CYString depiction_;
1469 CYString description_;
1475 CYString distribution_;
1480 NSString *authority_;
1482 CYString defaultIcon_;
1484 NSDictionary *record_;
1488 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1490 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1492 - (NSString *) depictionForPackage:(NSString *)package;
1493 - (NSString *) supportForPackage:(NSString *)package;
1495 - (NSDictionary *) record;
1499 - (NSString *) distribution;
1500 - (NSString *) type;
1502 - (NSString *) host;
1504 - (NSString *) name;
1505 - (NSString *) description;
1506 - (NSString *) label;
1507 - (NSString *) origin;
1508 - (NSString *) version;
1510 - (NSString *) defaultIcon;
1514 @implementation Source
1518 distribution_.clear();
1521 description_.clear();
1527 defaultIcon_.clear();
1529 if (record_ != nil) {
1539 if (authority_ != nil) {
1540 [authority_ release];
1546 // XXX: this is a very inefficient way to call these deconstructors
1551 + (NSArray *) _attributeKeys {
1552 return [NSArray arrayWithObjects:
1567 - (NSArray *) attributeKeys {
1568 return [[self class] _attributeKeys];
1571 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1572 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1575 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1578 trusted_ = index->IsTrusted();
1580 uri_.set(pool, index->GetURI());
1581 distribution_.set(pool, index->GetDist());
1582 type_.set(pool, index->GetType());
1584 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1585 if (dindex != NULL) {
1587 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1590 pkgTagFile tags(&fd);
1592 pkgTagSection section;
1599 {"default-icon", &defaultIcon_},
1600 {"depiction", &depiction_},
1601 {"description", &description_},
1603 {"origin", &origin_},
1604 {"support", &support_},
1605 {"version", &version_},
1608 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1609 const char *start, *end;
1611 if (section.Find(names[i].name_, start, end)) {
1612 CYString &value(*names[i].value_);
1613 value.set(pool, start, end - start);
1619 record_ = [Sources_ objectForKey:[self key]];
1621 record_ = [record_ retain];
1623 NSURL *url([NSURL URLWithString:uri_]);
1627 host_ = [[host_ lowercaseString] retain];
1632 authority_ = [url path];
1634 if (authority_ != nil)
1635 authority_ = [authority_ retain];
1638 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1639 if ((self = [super init]) != nil) {
1640 [self setMetaIndex:index inPool:pool];
1644 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1645 NSDictionary *lhr = [self record];
1646 NSDictionary *rhr = [source record];
1649 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1651 NSString *lhs = [self name];
1652 NSString *rhs = [source name];
1654 if ([lhs length] != 0 && [rhs length] != 0) {
1655 unichar lhc = [lhs characterAtIndex:0];
1656 unichar rhc = [rhs characterAtIndex:0];
1658 if (isalpha(lhc) && !isalpha(rhc))
1659 return NSOrderedAscending;
1660 else if (!isalpha(lhc) && isalpha(rhc))
1661 return NSOrderedDescending;
1664 return [lhs compare:rhs options:LaxCompareOptions_];
1667 - (NSString *) depictionForPackage:(NSString *)package {
1668 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1671 - (NSString *) supportForPackage:(NSString *)package {
1672 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1675 - (NSDictionary *) record {
1683 - (NSString *) uri {
1687 - (NSString *) distribution {
1688 return distribution_;
1691 - (NSString *) type {
1695 - (NSString *) key {
1696 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1699 - (NSString *) host {
1703 - (NSString *) name {
1704 return origin_.empty() ? authority_ : origin_;
1707 - (NSString *) description {
1708 return description_;
1711 - (NSString *) label {
1712 return label_.empty() ? authority_ : label_;
1715 - (NSString *) origin {
1719 - (NSString *) version {
1723 - (NSString *) defaultIcon {
1724 return defaultIcon_;
1729 /* CydiaOperation Class {{{ */
1730 @interface CydiaOperation : NSObject {
1731 NSString *operator_;
1735 - (NSString *) operator;
1736 - (NSString *) value;
1740 @implementation CydiaOperation
1743 [operator_ release];
1748 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1749 if ((self = [super init]) != nil) {
1750 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1751 value_ = [[NSString alloc] initWithUTF8String:value];
1755 + (NSArray *) _attributeKeys {
1756 return [NSArray arrayWithObjects:
1762 - (NSArray *) attributeKeys {
1763 return [[self class] _attributeKeys];
1766 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1767 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1770 - (NSString *) operator {
1774 - (NSString *) value {
1780 /* CydiaClause Class {{{ */
1781 @interface CydiaClause : NSObject {
1783 CydiaOperation *version_;
1786 - (NSString *) package;
1787 - (CydiaOperation *) version;
1791 @implementation CydiaClause
1799 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1800 if ((self = [super init]) != nil) {
1801 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1803 if (const char *version = dep.TargetVer())
1804 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1806 version_ = [[NSNull null] retain];
1810 + (NSArray *) _attributeKeys {
1811 return [NSArray arrayWithObjects:
1817 - (NSArray *) attributeKeys {
1818 return [[self class] _attributeKeys];
1821 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1822 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1825 - (NSString *) package {
1829 - (CydiaOperation *) version {
1835 /* CydiaRelation Class {{{ */
1836 @interface CydiaRelation : NSObject {
1837 NSString *relationship_;
1838 NSMutableArray *clauses_;
1841 - (NSString *) relationship;
1842 - (NSArray *) clauses;
1846 @implementation CydiaRelation
1849 [relationship_ release];
1854 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1855 if ((self = [super init]) != nil) {
1856 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1857 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1859 pkgCache::DepIterator start;
1860 pkgCache::DepIterator end;
1861 dep.GlobOr(start, end); // ++dep
1864 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1866 // yes, seriously. (wtf?)
1874 + (NSArray *) _attributeKeys {
1875 return [NSArray arrayWithObjects:
1881 - (NSArray *) attributeKeys {
1882 return [[self class] _attributeKeys];
1885 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1886 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1889 - (NSString *) relationship {
1890 return relationship_;
1893 - (NSArray *) clauses {
1897 - (void) addClause:(CydiaClause *)clause {
1898 [clauses_ addObject:clause];
1903 /* Package Class {{{ */
1904 struct ParsedPackage {
1909 CYString depiction_;
1919 @interface Package : NSObject {
1922 uint32_t essential_ : 1;
1923 uint32_t obsolete_ : 1;
1924 uint32_t ignored_ : 1;
1928 _transient Database *database_;
1930 pkgCache::VerIterator version_;
1931 pkgCache::PkgIterator iterator_;
1932 pkgCache::VerFileIterator file_;
1938 CYString installed_;
1940 const char *section_;
1941 _transient NSString *section$_;
1945 PackageValue *metadata_;
1946 ParsedPackage *parsed_;
1948 NSMutableArray *tags_;
1951 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1952 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1954 - (pkgCache::PkgIterator) iterator;
1957 - (NSString *) section;
1958 - (NSString *) simpleSection;
1960 - (NSString *) longSection;
1961 - (NSString *) shortSection;
1965 - (Address *) maintainer;
1967 - (NSString *) longDescription;
1968 - (NSString *) shortDescription;
1971 - (PackageValue *) metadata;
1974 - (bool) subscribed;
1975 - (bool) setSubscribed:(bool)subscribed;
1979 - (NSString *) latest;
1980 - (NSString *) installed;
1981 - (BOOL) uninstalled;
1984 - (BOOL) upgradableAndEssential:(BOOL)essential;
1987 - (BOOL) unfiltered;
1991 - (BOOL) halfConfigured;
1992 - (BOOL) halfInstalled;
1994 - (NSString *) mode;
1997 - (NSString *) name;
1999 - (NSString *) homepage;
2000 - (NSString *) depiction;
2001 - (Address *) author;
2003 - (NSString *) support;
2005 - (NSArray *) files;
2006 - (NSArray *) warnings;
2007 - (NSArray *) applications;
2009 - (Source *) source;
2011 - (BOOL) matches:(NSString *)text;
2013 - (bool) hasSupportingRole;
2014 - (BOOL) hasTag:(NSString *)tag;
2015 - (NSString *) primaryPurpose;
2016 - (NSArray *) purposes;
2017 - (bool) isCommercial;
2019 - (void) setIndex:(size_t)index;
2021 - (CYString &) cyname;
2023 - (uint32_t) compareBySection:(NSArray *)sections;
2028 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2029 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2030 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2031 - (bool) isVisibleInSection:(NSString *)section;
2032 - (bool) isVisibleInSource:(Source *)source;
2036 uint32_t PackageChangesRadix(Package *self, void *) {
2041 uint32_t timestamp : 30;
2042 uint32_t ignored : 1;
2043 uint32_t upgradable : 1;
2047 bool upgradable([self upgradableAndEssential:YES]);
2048 value.bits.upgradable = upgradable ? 1 : 0;
2051 value.bits.timestamp = 0;
2052 value.bits.ignored = [self ignored] ? 0 : 1;
2053 value.bits.upgradable = 1;
2055 value.bits.timestamp = [self seen] >> 2;
2056 value.bits.ignored = 0;
2057 value.bits.upgradable = 0;
2060 return _not(uint32_t) - value.key;
2063 uint32_t PackagePrefixRadix(Package *self, void *context) {
2064 size_t offset(reinterpret_cast<size_t>(context));
2065 CYString &name([self cyname]);
2067 size_t size(name.size());
2070 char *text(name.data());
2073 if (!isdigit(text[0]))
2077 while (size != digits && isdigit(text[digits]))
2085 if (offset == 0 && zeros != 0) {
2086 memset(data, '0', zeros);
2087 memcpy(data + zeros, text, 4 - zeros);
2089 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2090 if (size <= offset - zeros)
2093 text += offset - zeros;
2094 size -= offset - zeros;
2097 memcpy(data, text, 4);
2099 memcpy(data, text, size);
2100 memset(data + size, 0, 4 - size);
2103 for (size_t i(0); i != 4; ++i)
2104 if (isalpha(data[i]))
2112 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2114 /* XXX: ntohl may be more honest */
2115 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2118 CYString &(*PackageName)(Package *self, SEL sel);
2120 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2121 _profile(PackageNameCompare)
2122 CYString &lhi(PackageName(lhs, @selector(cyname)));
2123 CYString &rhi(PackageName(rhs, @selector(cyname)));
2124 CFStringRef lhn(lhi), rhn(rhi);
2127 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2128 else if (rhn == NULL)
2129 return NSOrderedDescending;
2131 _profile(PackageNameCompare$NumbersLast)
2132 if (!lhi.empty() && !rhi.empty()) {
2133 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2134 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2135 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2136 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2137 return lha ? NSOrderedAscending : NSOrderedDescending;
2141 CFIndex length = CFStringGetLength(lhn);
2143 _profile(PackageNameCompare$Compare)
2144 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2149 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2150 return PackageNameCompare(*lhs, *rhs, context);
2153 struct PackageNameOrdering :
2154 std::binary_function<Package *, Package *, bool>
2156 _finline bool operator ()(Package *lhs, Package *rhs) const {
2157 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2161 @implementation Package
2163 - (NSString *) description {
2164 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2168 if (parsed_ != NULL)
2177 + (NSString *) webScriptNameForSelector:(SEL)selector {
2179 else if (selector == @selector(clear))
2181 else if (selector == @selector(getField:))
2183 else if (selector == @selector(hasTag:))
2185 else if (selector == @selector(install))
2187 else if (selector == @selector(remove))
2193 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2194 return [self webScriptNameForSelector:selector] == nil;
2197 + (NSArray *) _attributeKeys {
2198 return [NSArray arrayWithObjects:
2216 @"shortDescription",
2227 - (NSArray *) attributeKeys {
2228 return [[self class] _attributeKeys];
2231 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2232 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2235 - (NSArray *) relations {
2236 @synchronized (database_) {
2237 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2238 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2239 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2243 - (NSString *) getField:(NSString *)name {
2244 @synchronized (database_) {
2245 if ([database_ era] != era_ || file_.end())
2248 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2250 const char *start, *end;
2251 if (!parser.Find([name UTF8String], start, end))
2252 return (NSString *) [NSNull null];
2254 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2258 if (parsed_ != NULL)
2260 @synchronized (database_) {
2261 if ([database_ era] != era_ || file_.end())
2264 ParsedPackage *parsed(new ParsedPackage);
2267 _profile(Package$parse)
2268 pkgRecords::Parser *parser;
2270 _profile(Package$parse$Lookup)
2271 parser = &[database_ records]->Lookup(file_);
2276 _profile(Package$parse$Find)
2281 {"icon", &parsed->icon_},
2282 {"depiction", &parsed->depiction_},
2283 {"homepage", &parsed->homepage_},
2284 {"website", &website},
2285 {"bugs", &parsed->bugs_},
2286 {"support", &parsed->support_},
2287 {"sponsor", &parsed->sponsor_},
2288 {"author", &parsed->author_},
2291 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2292 const char *start, *end;
2294 if (parser->Find(names[i].name_, start, end)) {
2295 CYString &value(*names[i].value_);
2296 _profile(Package$parse$Value)
2297 value.set(pool_, start, end - start);
2303 _profile(Package$parse$Tagline)
2304 const char *start, *end;
2305 if (parser->ShortDesc(start, end)) {
2306 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2309 while (stop != start && stop[-1] == '\r')
2311 parsed->tagline_.set(pool_, start, stop - start);
2315 _profile(Package$parse$Retain)
2316 if (parsed->homepage_.empty())
2317 parsed->homepage_ = website;
2318 if (parsed->homepage_ == parsed->depiction_)
2319 parsed->homepage_.clear();
2324 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2325 if ((self = [super init]) != nil) {
2326 _profile(Package$initWithVersion)
2329 database_ = database;
2330 era_ = [database era];
2334 pkgCache::PkgIterator iterator(version.ParentPkg());
2335 iterator_ = iterator;
2337 _profile(Package$initWithVersion$Version)
2338 if (!version_.end())
2339 file_ = version_.FileList();
2341 pkgCache &cache([database_ cache]);
2342 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2346 _profile(Package$initWithVersion$Cache)
2347 name_.set(NULL, iterator.Display());
2349 latest_.set(NULL, StripVersion_(version_.VerStr()));
2351 pkgCache::VerIterator current(iterator.CurrentVer());
2353 installed_.set(NULL, StripVersion_(current.VerStr()));
2356 _profile(Package$initWithVersion$Tags)
2357 pkgCache::TagIterator tag(iterator.TagList());
2359 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2361 const char *name(tag.Name());
2362 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2364 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2365 if (strcmp(name + 6, "enduser") == 0)
2367 else if (strcmp(name + 6, "hacker") == 0)
2369 else if (strcmp(name + 6, "developer") == 0)
2371 else if (strcmp(name + 6, "cydia") == 0)
2377 if (strncmp(name, "cydia::", 7) == 0) {
2378 if (strcmp(name + 7, "essential") == 0)
2380 else if (strcmp(name + 7, "obsolete") == 0)
2385 } while (!tag.end());
2389 _profile(Package$initWithVersion$Metadata)
2390 const char *mixed(iterator.Name());
2391 size_t size(strlen(mixed));
2392 char lower[size + 1];
2394 for (size_t i(0); i != size; ++i)
2395 lower[i] = mixed[i] | 0x20;
2398 PackageValue *metadata(PackageFind(lower, size));
2399 metadata_ = metadata;
2401 id_.set(NULL, metadata->name_, size);
2403 const char *latest(version_.VerStr());
2404 size_t length(strlen(latest));
2406 uint16_t vhash(hashlittle(latest, length));
2408 size_t capped(std::min<size_t>(8, length));
2409 latest = latest + length - capped;
2411 if (metadata->first_ == 0)
2412 metadata->first_ = now_;
2414 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2415 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2416 metadata->vhash_ = vhash;
2417 metadata->last_ = now_;
2418 } else if (metadata->last_ == 0)
2419 metadata->last_ = metadata->first_;
2422 _profile(Package$initWithVersion$Section)
2423 section_ = iterator.Section();
2426 _profile(Package$initWithVersion$Flags)
2427 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2428 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2433 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2434 pkgCache::VerIterator version;
2436 _profile(Package$packageWithIterator$GetCandidateVer)
2437 version = [database policy]->GetCandidateVer(iterator);
2445 _profile(Package$packageWithIterator$Allocate)
2446 package = [Package allocWithZone:zone];
2449 _profile(Package$packageWithIterator$Initialize)
2451 initWithVersion:version
2458 _profile(Package$packageWithIterator$Autorelease)
2459 package = [package autorelease];
2465 - (pkgCache::PkgIterator) iterator {
2469 - (NSString *) section {
2470 if (section$_ == nil) {
2471 if (section_ == NULL)
2474 _profile(Package$section$mappedSectionForPointer)
2475 section$_ = [database_ mappedSectionForPointer:section_];
2480 - (NSString *) simpleSection {
2481 if (NSString *section = [self section])
2482 return Simplify(section);
2487 - (NSString *) longSection {
2488 return LocalizeSection([self section]);
2491 - (NSString *) shortSection {
2492 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2495 - (NSString *) uri {
2498 pkgIndexFile *index;
2499 pkgCache::PkgFileIterator file(file_.File());
2500 if (![database_ list].FindIndex(file, index))
2502 return [NSString stringWithUTF8String:iterator_->Path];
2503 //return [NSString stringWithUTF8String:file.Site()];
2504 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2508 - (Address *) maintainer {
2509 @synchronized (database_) {
2510 if ([database_ era] != era_ || file_.end())
2513 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2514 const std::string &maintainer(parser->Maintainer());
2515 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2519 @synchronized (database_) {
2520 if ([database_ era] != era_ || version_.end())
2523 return version_->InstalledSize;
2526 - (NSString *) longDescription {
2527 @synchronized (database_) {
2528 if ([database_ era] != era_ || file_.end())
2531 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2532 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2534 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2535 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2536 if ([lines count] < 2)
2539 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2540 for (size_t i(1), e([lines count]); i != e; ++i) {
2541 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2542 [trimmed addObject:trim];
2545 return [trimmed componentsJoinedByString:@"\n"];
2548 - (NSString *) shortDescription {
2549 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2553 _profile(Package$index)
2554 CFStringRef name((CFStringRef) [self name]);
2555 if (CFStringGetLength(name) == 0)
2557 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2558 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2560 return toupper(character);
2564 - (PackageValue *) metadata {
2569 PackageValue *metadata([self metadata]);
2570 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2573 - (bool) subscribed {
2574 return [self metadata]->subscribed_;
2577 - (bool) setSubscribed:(bool)subscribed {
2578 PackageValue *metadata([self metadata]);
2579 if (metadata->subscribed_ == subscribed)
2581 metadata->subscribed_ = subscribed;
2589 - (NSString *) latest {
2593 - (NSString *) installed {
2597 - (BOOL) uninstalled {
2598 return installed_.empty();
2602 return !version_.end();
2605 - (BOOL) upgradableAndEssential:(BOOL)essential {
2606 _profile(Package$upgradableAndEssential)
2607 pkgCache::VerIterator current(iterator_.CurrentVer());
2609 return essential && essential_;
2611 return !version_.end() && version_ != current;
2615 - (BOOL) essential {
2620 return [database_ cache][iterator_].InstBroken();
2623 - (BOOL) unfiltered {
2624 _profile(Package$unfiltered$obsolete)
2625 if (_unlikely(obsolete_))
2629 _profile(Package$unfiltered$hasSupportingRole)
2630 if (_unlikely(![self hasSupportingRole]))
2638 if (![self unfiltered])
2643 _profile(Package$visible$section)
2644 section = [self section];
2647 _profile(Package$visible$isSectionVisible)
2648 if (!isSectionVisible(section))
2656 unsigned char current(iterator_->CurrentState);
2657 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2660 - (BOOL) halfConfigured {
2661 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2664 - (BOOL) halfInstalled {
2665 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2669 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2670 return state.Mode != pkgDepCache::ModeKeep;
2673 - (NSString *) mode {
2674 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2676 switch (state.Mode) {
2677 case pkgDepCache::ModeDelete:
2678 if ((state.iFlags & pkgDepCache::Purge) != 0)
2682 case pkgDepCache::ModeKeep:
2683 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2684 return @"REINSTALL";
2685 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2689 case pkgDepCache::ModeInstall:
2690 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2691 return @"REINSTALL";
2692 else*/ switch (state.Status) {
2694 return @"DOWNGRADE";
2700 return @"NEW_INSTALL";
2711 - (NSString *) name {
2712 return name_.empty() ? id_ : name_;
2715 - (UIImage *) icon {
2716 NSString *section = [self simpleSection];
2719 if (parsed_ != NULL)
2720 if (NSString *href = parsed_->icon_)
2721 if ([href hasPrefix:@"file:///"])
2722 // XXX: correct escaping
2723 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2724 if (icon == nil) if (section != nil)
2725 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2726 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2727 if ([dicon hasPrefix:@"file:///"])
2728 // XXX: correct escaping
2729 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2731 icon = [UIImage applicationImageNamed:@"unknown.png"];
2735 - (NSString *) homepage {
2736 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2739 - (NSString *) depiction {
2740 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2743 - (Address *) sponsor {
2744 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2747 - (Address *) author {
2748 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2751 - (NSString *) support {
2752 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2755 - (NSArray *) files {
2756 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2757 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2760 fin.open([path UTF8String]);
2765 while (std::getline(fin, line))
2766 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2771 - (NSArray *) warnings {
2772 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2773 const char *name(iterator_.Name());
2775 size_t length(strlen(name));
2776 if (length < 2) invalid:
2777 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2778 else for (size_t i(0); i != length; ++i)
2780 /* XXX: technically this is not allowed */
2781 (name[i] < 'A' || name[i] > 'Z') &&
2782 (name[i] < 'a' || name[i] > 'z') &&
2783 (name[i] < '0' || name[i] > '9') &&
2784 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2787 if (strcmp(name, "cydia") != 0) {
2790 bool _private = false;
2793 bool repository = [[self section] isEqualToString:@"Repositories"];
2795 if (NSArray *files = [self files])
2796 for (NSString *file in files)
2797 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2799 else if (!user && [file isEqualToString:@"/User"])
2801 else if (!_private && [file isEqualToString:@"/private"])
2803 else if (!stash && [file isEqualToString:@"/var/stash"])
2806 /* XXX: this is not sensitive enough. only some folders are valid. */
2807 if (cydia && !repository)
2808 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2810 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2812 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2814 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2817 return [warnings count] == 0 ? nil : warnings;
2820 - (NSArray *) applications {
2821 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2823 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2825 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2826 if (NSArray *files = [self files])
2827 for (NSString *file in files)
2828 if (application_r(file)) {
2829 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2830 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2831 if ([id isEqualToString:me])
2834 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2836 display = application_r[1];
2838 NSString *bundle([file stringByDeletingLastPathComponent]);
2839 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2840 if (icon == nil || [icon length] == 0)
2842 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2844 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2845 [applications addObject:application];
2847 [application addObject:id];
2848 [application addObject:display];
2849 [application addObject:url];
2852 return [applications count] == 0 ? nil : applications;
2855 - (Source *) source {
2856 if (source_ == nil) {
2857 @synchronized (database_) {
2858 if ([database_ era] != era_ || file_.end())
2859 source_ = (Source *) [NSNull null];
2861 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2865 return source_ == (Source *) [NSNull null] ? nil : source_;
2868 - (BOOL) matches:(NSString *)text {
2874 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2875 if (range.location != NSNotFound)
2878 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2879 if (range.location != NSNotFound)
2884 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2885 if (range.location != NSNotFound)
2891 - (bool) hasSupportingRole {
2896 if ([Role_ isEqualToString:@"User"])
2900 if ([Role_ isEqualToString:@"Hacker"])
2904 if ([Role_ isEqualToString:@"Developer"])
2909 - (BOOL) hasTag:(NSString *)tag {
2910 return tags_ == nil ? NO : [tags_ containsObject:tag];
2913 - (NSString *) primaryPurpose {
2914 for (NSString *tag in tags_)
2915 if ([tag hasPrefix:@"purpose::"])
2916 return [tag substringFromIndex:9];
2920 - (NSArray *) purposes {
2921 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2922 for (NSString *tag in tags_)
2923 if ([tag hasPrefix:@"purpose::"])
2924 [purposes addObject:[tag substringFromIndex:9]];
2925 return [purposes count] == 0 ? nil : purposes;
2928 - (bool) isCommercial {
2929 return [self hasTag:@"cydia::commercial"];
2932 - (void) setIndex:(size_t)index {
2933 if (metadata_->index_ != index)
2934 metadata_->index_ = index;
2937 - (CYString &) cyname {
2938 return name_.empty() ? id_ : name_;
2941 - (uint32_t) compareBySection:(NSArray *)sections {
2942 NSString *section([self section]);
2943 for (size_t i(0), e([sections count]); i != e; ++i) {
2944 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2948 return _not(uint32_t);
2952 @synchronized (database_) {
2953 pkgProblemResolver *resolver = [database_ resolver];
2954 resolver->Clear(iterator_);
2956 pkgCacheFile &cache([database_ cache]);
2957 cache->SetReInstall(iterator_, false);
2958 cache->MarkKeep(iterator_, false);
2962 @synchronized (database_) {
2963 pkgProblemResolver *resolver = [database_ resolver];
2964 resolver->Clear(iterator_);
2965 resolver->Protect(iterator_);
2967 pkgCacheFile &cache([database_ cache]);
2968 cache->SetReInstall(iterator_, false);
2969 cache->MarkInstall(iterator_, false);
2971 pkgDepCache::StateCache &state((*cache)[iterator_]);
2972 if (!state.Install())
2973 cache->SetReInstall(iterator_, true);
2977 @synchronized (database_) {
2978 pkgProblemResolver *resolver = [database_ resolver];
2979 resolver->Clear(iterator_);
2980 resolver->Remove(iterator_);
2981 resolver->Protect(iterator_);
2983 pkgCacheFile &cache([database_ cache]);
2984 cache->SetReInstall(iterator_, false);
2985 cache->MarkDelete(iterator_, true);
2988 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2989 _profile(Package$isUnfilteredAndSearchedForBy)
2992 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2993 value &= [self unfiltered];
2996 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2997 value &= [self matches:search];
3004 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3005 if ([search length] == 0)
3008 _profile(Package$isUnfilteredAndSelectedForBy)
3011 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3012 value &= [self unfiltered];
3015 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3016 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3023 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3024 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3027 - (bool) isVisibleInSection:(NSString *)name {
3028 NSString *section([self section]);
3032 section == nil && [name length] == 0 ||
3033 [name isEqualToString:section]
3034 ) && [self visible];
3037 - (bool) isVisibleInSource:(Source *)source {
3038 return [self source] == source && [self visible];
3043 /* Section Class {{{ */
3044 @interface Section : NSObject {
3049 NSString *localized_;
3052 - (NSComparisonResult) compareByLocalized:(Section *)section;
3053 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3054 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3055 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3056 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3057 - (NSString *) name;
3064 - (void) addToCount;
3066 - (void) setCount:(size_t)count;
3067 - (NSString *) localized;
3071 @implementation Section
3075 if (localized_ != nil)
3076 [localized_ release];
3080 - (NSComparisonResult) compareByLocalized:(Section *)section {
3081 NSString *lhs(localized_);
3082 NSString *rhs([section localized]);
3084 /*if ([lhs length] != 0 && [rhs length] != 0) {
3085 unichar lhc = [lhs characterAtIndex:0];
3086 unichar rhc = [rhs characterAtIndex:0];
3088 if (isalpha(lhc) && !isalpha(rhc))
3089 return NSOrderedAscending;
3090 else if (!isalpha(lhc) && isalpha(rhc))
3091 return NSOrderedDescending;
3094 return [lhs compare:rhs options:LaxCompareOptions_];
3097 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3098 if ((self = [self initWithName:name localize:NO]) != nil) {
3099 if (localized != nil)
3100 localized_ = [localized retain];
3104 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3105 return [self initWithName:name row:0 localize:localize];
3108 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3109 if ((self = [super init]) != nil) {
3110 name_ = [name retain];
3114 localized_ = [LocalizeSection(name_) retain];
3118 /* XXX: localize the index thingees */
3119 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3120 if ((self = [super init]) != nil) {
3121 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3127 - (NSString *) name {
3147 - (void) addToCount {
3151 - (void) setCount:(size_t)count {
3155 - (NSString *) localized {
3162 static NSString *Colon_;
3163 static NSString *Elision_;
3164 static NSString *Error_;
3165 static NSString *Warning_;
3167 /* Database Implementation {{{ */
3168 @implementation Database
3170 + (Database *) sharedInstance {
3171 static Database *instance;
3172 if (instance == nil)
3173 instance = [[Database alloc] init];
3181 - (void) releasePackages {
3182 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3183 CFArrayRemoveAllValues(packages_);
3187 // XXX: actually implement this thing
3189 [sourceList_ release];
3190 [self releasePackages];
3191 apr_pool_destroy(pool_);
3192 NSRecycleZone(zone_);
3196 - (void) _readCydia:(NSNumber *)fd { _pooled
3197 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3198 std::istream is(&ib);
3201 static Pcre finish_r("^finish:([^:]*)$");
3203 while (std::getline(is, line)) {
3204 const char *data(line.c_str());
3205 size_t size = line.size();
3206 lprintf("C:%s\n", data);
3208 if (finish_r(data, size)) {
3209 NSString *finish = finish_r[1];
3210 int index = [Finishes_ indexOfObject:finish];
3211 if (index != INT_MAX && index > Finish_)
3219 - (void) _readStatus:(NSNumber *)fd { _pooled
3220 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3221 std::istream is(&ib);
3224 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3225 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3227 while (std::getline(is, line)) {
3228 const char *data(line.c_str());
3229 size_t size(line.size());
3230 lprintf("S:%s\n", data);
3232 if (conffile_r(data, size))
3233 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3234 else if (strncmp(data, "status: ", 8) == 0)
3235 [delegate_ performSelectorOnMainThread:@selector(setProgressTitle:) withObject:[NSString stringWithUTF8String:(data + 8)] waitUntilDone:YES];
3236 else if (pmstatus_r(data, size)) {
3237 std::string type([pmstatus_r[1] UTF8String]);
3238 NSString *id = pmstatus_r[2];
3240 float percent([pmstatus_r[3] floatValue]);
3241 [delegate_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3243 NSString *string = pmstatus_r[4];
3245 if (type == "pmerror")
3246 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3247 withObject:[NSArray arrayWithObjects:string, id, nil]
3250 else if (type == "pmstatus")
3251 [delegate_ performSelectorOnMainThread:@selector(setProgressTitle:) withObject:string waitUntilDone:YES];
3252 else if (type == "pmconffile")
3253 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3255 lprintf("E:unknown pmstatus\n");
3257 lprintf("E:unknown status\n");
3263 - (void) _readOutput:(NSNumber *)fd { _pooled
3264 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3265 std::istream is(&ib);
3268 while (std::getline(is, line)) {
3269 lprintf("O:%s\n", line.c_str());
3271 [delegate_ performSelectorOnMainThread:@selector(addProgressOutput:) withObject:[NSString stringWithUTF8String:line.c_str()] waitUntilDone:YES];
3281 - (Package *) packageWithName:(NSString *)name {
3282 @synchronized (self) {
3283 if (static_cast<pkgDepCache *>(cache_) == NULL)
3285 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3286 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3290 if ((self = [super init]) != nil) {
3297 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3298 apr_pool_create(&pool_, NULL);
3300 size_t capacity(MetaFile_->active_);
3306 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3307 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3311 _assert(pipe(fds) != -1);
3314 _config->Set("APT::Keep-Fds::", cydiafd_);
3315 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3318 detachNewThreadSelector:@selector(_readCydia:)
3320 withObject:[NSNumber numberWithInt:fds[0]]
3323 _assert(pipe(fds) != -1);
3327 detachNewThreadSelector:@selector(_readStatus:)
3329 withObject:[NSNumber numberWithInt:fds[0]]
3332 _assert(pipe(fds) != -1);
3333 _assert(dup2(fds[0], 0) != -1);
3334 _assert(close(fds[0]) != -1);
3336 input_ = fdopen(fds[1], "a");
3338 _assert(pipe(fds) != -1);
3339 _assert(dup2(fds[1], 1) != -1);
3340 _assert(close(fds[1]) != -1);
3343 detachNewThreadSelector:@selector(_readOutput:)
3345 withObject:[NSNumber numberWithInt:fds[0]]
3350 - (pkgCacheFile &) cache {
3354 - (pkgDepCache::Policy *) policy {
3358 - (pkgRecords *) records {
3362 - (pkgProblemResolver *) resolver {
3366 - (pkgAcquire &) fetcher {
3370 - (pkgSourceList &) list {
3374 - (NSArray *) packages {
3375 return (NSArray *) packages_;
3378 - (NSArray *) sources {
3382 - (Source *) sourceWithKey:(NSString *)key {
3383 for (Source *source in [self sources]) {
3384 if ([[source key] isEqualToString:key])
3389 - (bool) popErrorWithTitle:(NSString *)title {
3392 while (!_error->empty()) {
3394 bool warning(!_error->PopMessage(error));
3399 size_t size(error.size());
3400 if (size == 0 || error[size - 1] != '\n')
3402 error.resize(size - 1);
3405 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3407 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, (warning ? Warning_ : Error_), title]];
3413 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3414 return [self popErrorWithTitle:title] || !success;
3417 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3418 @synchronized (self) {
3421 [self releasePackages];
3424 [sourceList_ removeAllObjects];
3444 apr_pool_clear(pool_);
3446 NSRecycleZone(zone_);
3447 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3449 int chk(creat("/tmp/cydia.chk", 0644));
3453 if (invocation != nil)
3454 [invocation invoke];
3456 NSString *title(UCLocalize("DATABASE"));
3459 OpProgress progress;
3460 while (!cache_.Open(progress, true)) { pop:
3462 bool warning(!_error->PopMessage(error));
3463 lprintf("cache_.Open():[%s]\n", error.c_str());
3465 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3466 [delegate_ repairWithSelector:@selector(configure)];
3467 else if (error == "The package lists or status file could not be parsed or opened.")
3468 [delegate_ repairWithSelector:@selector(update)];
3469 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3470 else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3471 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, Error_, title]];
3472 // else if (error == "The list of sources could not be read.")
3474 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3484 unlink("/tmp/cydia.chk");
3486 now_ = [[NSDate date] timeIntervalSince1970];
3488 policy_ = new pkgDepCache::Policy();
3489 records_ = new pkgRecords(cache_);
3490 resolver_ = new pkgProblemResolver(cache_);
3491 fetcher_ = new pkgAcquire(&status_);
3494 list_ = new pkgSourceList();
3495 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3498 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3499 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3503 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3506 if (cache_->BrokenCount() != 0) {
3507 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3510 if (cache_->BrokenCount() != 0) {
3511 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3515 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3519 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3520 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3521 [sourceList_ addObject:object];
3523 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3524 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3525 // XXX: this could be more intelligent
3526 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3527 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3529 sourceMap_[cached->ID] = object;
3534 /*std::vector<Package *> packages;
3535 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3536 [packages_ release];
3541 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3542 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3543 //packages.push_back(package);
3544 CFArrayAppendValue(packages_, [package retain]);
3548 /*if (packages.empty())
3549 packages_ = [[NSArray alloc] init];
3551 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3554 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3555 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3556 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3564 /*if (!packages.empty())
3565 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3566 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3568 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3570 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3572 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3576 size_t count(CFArrayGetCount(packages_));
3577 MetaFile_->active_ = count;
3579 for (size_t index(0); index != count; ++index)
3580 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3584 } } CYPoolEnd() _trace(); }
3587 @synchronized (self) {
3589 resolver_ = new pkgProblemResolver(cache_);
3591 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3592 if (!cache_[iterator].Keep())
3593 cache_->MarkKeep(iterator, false);
3594 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3595 cache_->SetReInstall(iterator, false);
3598 - (void) configure {
3599 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3601 system([dpkg UTF8String]);
3606 // XXX: I don't remember this condition
3611 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3613 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3615 if ([self popErrorWithTitle:title])
3619 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3622 public pkgArchiveCleaner
3625 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3630 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3637 fetcher_->Shutdown();
3639 pkgRecords records(cache_);
3641 lock_ = new FileFd();
3642 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3644 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3646 if ([self popErrorWithTitle:title])
3650 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3653 manager_ = (_system->CreatePM(cache_));
3654 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3661 bool substrate(RestartSubstrate_);
3662 RestartSubstrate_ = false;
3664 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3666 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3668 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3670 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3671 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3674 [CydiaApp performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3676 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3678 [self popErrorWithTitle:title];
3682 bool failed = false;
3683 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3684 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3686 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3692 [CydiaApp performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3700 RestartSubstrate_ = true;
3703 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3705 if (_error->PendingError()) {
3710 if (result == pkgPackageManager::Failed) {
3715 if (result != pkgPackageManager::Completed) {
3720 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3722 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3724 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3725 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3728 if (![before isEqualToArray:after])
3733 NSString *title(UCLocalize("UPGRADE"));
3734 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3740 [self updateWithStatus:status_];
3743 - (void) updateWithStatus:(Status &)status {
3744 NSString *title(UCLocalize("REFRESHING_DATA"));
3747 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3751 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3752 if ([self popErrorWithTitle:title])
3755 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3756 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3757 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3759 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3763 - (void) setDelegate:(id)delegate {
3764 delegate_ = delegate;
3765 status_.setDelegate(delegate);
3768 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3769 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3770 return i == sourceMap_.end() ? nil : i->second;
3773 - (NSString *) mappedSectionForPointer:(const char *)section {
3774 _H<NSString> *mapped;
3776 _profile(Database$mappedSectionForPointer$Cache)
3777 mapped = §ions_[section];
3780 if (*mapped == NULL) {
3781 size_t length(strlen(section));
3782 char spaced[length + 1];
3784 _profile(Database$mappedSectionForPointer$Replace)
3785 for (size_t index(0); index != length; ++index)
3786 spaced[index] = section[index] == '_' ? ' ' : section[index];
3787 spaced[length] = '\0';
3792 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3793 string = [NSString stringWithUTF8String:spaced];
3796 _profile(Database$mappedSectionForPointer$Map)
3797 string = [SectionMap_ objectForKey:string] ?: string;
3807 /* Web Scripting {{{ */
3808 @interface CydiaObject : NSObject {
3810 _transient id delegate_;
3813 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3817 @implementation CydiaObject
3820 [indirect_ release];
3824 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3825 if ((self = [super init]) != nil) {
3826 indirect_ = [indirect retain];
3830 - (void) setDelegate:(id)delegate {
3831 delegate_ = delegate;
3834 + (NSArray *) _attributeKeys {
3835 return [NSArray arrayWithObjects:
3845 - (NSArray *) attributeKeys {
3846 return [[self class] _attributeKeys];
3849 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3850 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3853 - (NSString *) device {
3854 return [[UIDevice currentDevice] uniqueIdentifier];
3857 - (NSString *) plmn {
3861 - (NSString *) ecid {
3865 - (NSString *) serial {
3866 return SerialNumber_;
3869 - (NSString *) role {
3873 - (NSString *) model {
3874 return [NSString stringWithUTF8String:Machine_];
3877 + (NSString *) webScriptNameForSelector:(SEL)selector {
3879 else if (selector == @selector(addTrivialSource:))
3880 return @"addTrivialSource";
3881 else if (selector == @selector(close))
3883 else if (selector == @selector(du:))
3885 else if (selector == @selector(stringWithFormat:arguments:))
3887 else if (selector == @selector(getAllSources))
3888 return @"getAllSourcs";
3889 else if (selector == @selector(getKernelNumber:))
3890 return @"getKernelNumber";
3891 else if (selector == @selector(getKernelString:))
3892 return @"getKernelString";
3893 else if (selector == @selector(getInstalledPackages))
3894 return @"getInstalledPackages";
3895 else if (selector == @selector(getPackageById:))
3896 return @"getPackageById";
3897 else if (selector == @selector(installPackages:))
3898 return @"installPackages";
3899 else if (selector == @selector(localizedStringForKey:value:table:))
3901 else if (selector == @selector(refreshSources))
3902 return @"refreshSources";
3903 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3904 return @"setButtonImage";
3905 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3906 return @"setButtonTitle";
3907 else if (selector == @selector(setPopupHook:))
3908 return @"setPopupHook";
3909 else if (selector == @selector(setToken:))
3911 else if (selector == @selector(setViewportWidth:))
3912 return @"setViewportWidth";
3913 else if (selector == @selector(statfs:))
3915 else if (selector == @selector(supports:))
3921 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3922 return [self webScriptNameForSelector:selector] == nil;
3925 - (BOOL) supports:(NSString *)feature {
3926 return [feature isEqualToString:@"window.open"];
3929 - (NSNumber *) getKernelNumber:(NSString *)name {
3930 const char *string([name UTF8String]);
3933 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3934 return (id) [NSNull null];
3936 if (size != sizeof(int))
3937 return (id) [NSNull null];
3940 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3941 return (id) [NSNull null];
3943 return [NSNumber numberWithInt:value];
3946 - (NSString *) getKernelString:(NSString *)name {
3947 const char *string([name UTF8String]);
3950 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3951 return (id) [NSNull null];
3953 char value[size + 1];
3954 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3955 return (id) [NSNull null];
3957 // XXX: just in case you request something ludicrous
3960 return [NSString stringWithCString:value];
3963 - (void) addTrivialSource:(NSString *)href {
3964 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
3967 - (void) refreshSources {
3968 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
3971 - (NSArray *) getAllSources {
3972 return [[Database sharedInstance] sources];
3975 - (NSArray *) getInstalledPackages {
3976 Database *database([Database sharedInstance]);
3977 @synchronized (database) {
3978 NSArray *packages([database packages]);
3979 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3980 for (Package *package in packages)
3981 if (![package uninstalled])
3982 [installed addObject:package];
3986 - (Package *) getPackageById:(NSString *)id {
3987 Package *package([[Database sharedInstance] packageWithName:id]);
3992 - (NSArray *) statfs:(NSString *)path {
3995 if (path == nil || statfs([path UTF8String], &stat) == -1)
3998 return [NSArray arrayWithObjects:
3999 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4000 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4001 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4005 - (NSNumber *) du:(NSString *)path {
4006 NSNumber *value(nil);
4009 _assert(pipe(fds) != -1);
4011 pid_t pid(ExecFork());
4013 _assert(dup2(fds[1], 1) != -1);
4014 _assert(close(fds[0]) != -1);
4015 _assert(close(fds[1]) != -1);
4016 /* XXX: this should probably not use du */
4017 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4022 _assert(close(fds[1]) != -1);
4024 if (FILE *du = fdopen(fds[0], "r")) {
4026 while (fgets(line, sizeof(line), du) != NULL) {
4027 size_t length(strlen(line));
4028 while (length != 0 && line[length - 1] == '\n')
4029 line[--length] = '\0';
4030 if (char *tab = strchr(line, '\t')) {
4032 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4037 } else _assert(close(fds[0]));
4041 if (waitpid(pid, &status, 0) == -1)
4044 else _assert(false);
4050 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4053 - (void) installPackages:(NSArray *)packages {
4054 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4057 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4058 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4061 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4062 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4065 - (void) _setToken:(NSString *)token {
4068 Token_ = [token retain];
4070 [Metadata_ setObject:Token_ forKey:@"Token"];
4074 - (void) setToken:(NSString *)token {
4075 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4078 - (void) setPopupHook:(id)function {
4079 [indirect_ setPopupHook:function];
4082 - (void) setViewportWidth:(float)width {
4083 [indirect_ setViewportWidthOnMainThread:width];
4086 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4087 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4088 unsigned count([arguments count]);
4090 for (unsigned i(0); i != count; ++i)
4091 values[i] = [arguments objectAtIndex:i];
4092 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4095 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4096 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4098 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4100 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4106 /* @ Loading... Indicator {{{ */
4107 @interface CYLoadingIndicator : UIView {
4108 UIActivityIndicatorView *spinner_;
4113 @property (readonly, nonatomic) UILabel *label;
4114 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4118 @implementation CYLoadingIndicator
4120 - (id) initWithFrame:(CGRect)frame {
4121 if ((self = [super initWithFrame:frame]) != nil) {
4122 container_ = [[[UIView alloc] init] autorelease];
4123 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4125 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4126 [spinner_ startAnimating];
4127 [container_ addSubview:spinner_];
4129 label_ = [[[UILabel alloc] init] autorelease];
4130 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4131 [label_ setBackgroundColor:[UIColor clearColor]];
4132 [label_ setTextColor:[UIColor blackColor]];
4133 [label_ setShadowColor:[UIColor whiteColor]];
4134 [label_ setShadowOffset:CGSizeMake(0, 1)];
4135 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4136 [container_ addSubview:label_];
4138 CGSize viewsize = frame.size;
4139 CGSize spinnersize = [spinner_ bounds].size;
4140 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4141 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4143 CGRect containrect = {
4144 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4145 CGSizeMake(bothwidth, spinnersize.height)
4148 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4156 [container_ setFrame:containrect];
4157 [spinner_ setFrame:spinrect];
4158 [label_ setFrame:textrect];
4159 [self addSubview:container_];
4163 - (UILabel *) label {
4167 - (UIActivityIndicatorView *) activityIndicatorView {
4173 /* Emulated Loading Controller {{{ */
4174 @interface CYEmulatedLoadingController : CYViewController <
4176 ConfigurationDelegate
4178 _transient Database *database_;
4179 CYLoadingIndicator *indicator_;
4181 UINavigationBar *navbar_;
4186 @implementation CYEmulatedLoadingController
4189 [self releaseSubviews];
4190 [database_ setDelegate:nil];
4195 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4196 CYAlertView *sheet([[[CYAlertView alloc]
4198 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4199 defaultButtonIndex:0
4202 [sheet setMessage:error];
4203 [sheet yieldToPopupAlertAnimated:YES];
4207 - (void) setProgressTitle:(NSString *)title { }
4208 - (void) setProgressPercent:(NSNumber *)percent { }
4209 - (void) startProgress { }
4210 - (void) addProgressOutput:(NSString *)output { }
4211 - (bool) isProgressCancelled { return NO; }
4212 - (void) setConfigurationData:(NSString *)data { }
4214 - (void) repairWithSelector:(SEL)selector {
4215 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("REPAIRING"), nil] waitUntilDone:YES];
4216 [database_ performSelector:selector];
4218 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil] waitUntilDone:YES];
4221 - (id) initWithDatabase:(Database *)database {
4222 if ((self = [super init]) != nil) {
4223 database_ = database;
4224 [database_ setDelegate:self];
4229 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4230 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4232 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4233 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4234 [[self view] addSubview:indicator_];
4236 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4237 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4238 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4239 [[self view] addSubview:tabbar_];
4241 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4242 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4243 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4244 [[self view] addSubview:navbar_];
4247 - (void) releaseSubviews {
4248 [indicator_ release];
4261 /* Cydia Browser Controller {{{ */
4262 @interface CYBrowserController : BrowserController {
4263 CydiaObject *cydia_;
4268 @implementation CYBrowserController
4275 - (NSURL *) navigationURL {
4276 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4279 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4282 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4283 [super webView:view didClearWindowObject:window forFrame:frame];
4285 WebDataSource *source([frame dataSource]);
4286 NSURLResponse *response([source response]);
4288 NSURL *url([response URL]);
4289 NSString *scheme([url scheme]);
4290 NSString *host([url host]);
4292 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4293 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4294 NSDictionary *headers([http allHeaderFields]);
4295 [self setHeaders:headers forHost:host];
4299 [host isEqualToString:@"cydia.saurik.com"] ||
4300 [host hasSuffix:@".cydia.saurik.com"] ||
4301 [scheme isEqualToString:@"file"]
4303 [window setValue:cydia_ forKey:@"cydia"];
4306 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4307 if (System_ != NULL)
4308 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4309 if (Machine_ != NULL)
4310 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4312 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4314 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4317 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4318 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4319 [self _setMoreHeaders:copy];
4323 - (void) setDelegate:(id)delegate {
4324 [super setDelegate:delegate];
4325 [cydia_ setDelegate:delegate];
4329 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4330 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4332 WebView *webview([[webview_ _documentView] webView]);
4334 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4336 NSString *application = package == nil ? @"Cydia" : [NSString
4337 stringWithFormat:@"Cydia/%@",
4342 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4344 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4345 if (Product_ != nil)
4346 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4348 [webview setApplicationNameForUserAgent:application];
4356 @interface NSObject (CydiaScript)
4357 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4360 @implementation NSObject (CydiaScript)
4362 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4368 @implementation NSArray (CydiaScript)
4370 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4371 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4372 for (size_t i(0), e([self count]); i != e; ++i)
4373 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4379 @implementation NSDictionary (CydiaScript)
4381 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4382 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4384 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4391 /* Confirmation Controller {{{ */
4392 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4393 if (!iterator.end())
4394 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4395 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4397 pkgCache::PkgIterator package(dep.TargetPkg());
4400 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4407 @protocol ConfirmationControllerDelegate
4408 - (void) cancelAndClear:(bool)clear;
4409 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4413 @interface ConfirmationController : CYBrowserController {
4414 _transient Database *database_;
4416 UIAlertView *essential_;
4418 NSDictionary *changes_;
4419 NSMutableArray *issues_;
4420 NSDictionary *sizes_;
4425 - (id) initWithDatabase:(Database *)database;
4429 @implementation ConfirmationController
4436 if (essential_ != nil)
4437 [essential_ release];
4444 RestartSubstrate_ = true;
4445 [delegate_ confirmWithNavigationController:[self navigationController]];
4448 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4449 NSString *context([alert context]);
4451 if ([context isEqualToString:@"remove"]) {
4452 if (button == [alert cancelButtonIndex])
4453 [self dismissModalViewControllerAnimated:YES];
4454 else if (button == [alert firstOtherButtonIndex]) {
4458 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4459 } else if ([context isEqualToString:@"unable"]) {
4460 [self dismissModalViewControllerAnimated:YES];
4461 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4463 [super alertView:alert clickedButtonAtIndex:button];
4467 - (void) _doContinue {
4468 [self dismissModalViewControllerAnimated:YES];
4469 [delegate_ cancelAndClear:NO];
4472 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4473 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4477 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4478 [super webView:view didClearWindowObject:window forFrame:frame];
4480 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4481 changes_, @"changes",
4485 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4488 - (id) initWithDatabase:(Database *)database {
4489 if ((self = [super init]) != nil) {
4490 database_ = database;
4492 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4493 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4494 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4495 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4496 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4500 pkgCacheFile &cache([database_ cache]);
4501 NSArray *packages([database_ packages]);
4502 pkgDepCache::Policy *policy([database_ policy]);
4504 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4506 for (Package *package in packages) {
4507 pkgCache::PkgIterator iterator([package iterator]);
4508 NSString *name([package id]);
4510 if ([package broken]) {
4511 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4513 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4515 reasons, @"reasons",
4518 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4522 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4523 pkgCache::DepIterator start;
4524 pkgCache::DepIterator end;
4525 dep.GlobOr(start, end); // ++dep
4527 if (!cache->IsImportantDep(end))
4529 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4532 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4534 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4535 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4536 clauses, @"clauses",
4540 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4542 pkgCache::PkgIterator target(start.TargetPkg());
4543 if (target->ProvidesList != 0)
4544 reason = @"missing";
4546 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4548 reason = @"installed";
4549 installed = [NSString stringWithUTF8String:ver.VerStr()];
4550 } else if (!cache[target].CandidateVerIter(cache).end())
4551 reason = @"uninstalled";
4552 else if (target->ProvidesList == 0)
4553 reason = @"uninstallable";
4555 reason = @"virtual";
4558 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4559 [NSString stringWithUTF8String:start.CompType()], @"operator",
4560 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4563 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4564 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4565 version, @"version",
4567 installed, @"installed",
4570 // yes, seriously. (wtf?)
4578 pkgDepCache::StateCache &state(cache[iterator]);
4580 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4582 if (state.NewInstall())
4583 [installs addObject:name];
4584 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4585 [reinstalls addObject:name];
4586 else if (state.Upgrade())
4587 [upgrades addObject:name];
4588 else if (state.Downgrade())
4589 [downgrades addObject:name];
4590 else if (!state.Delete())
4592 else if (special_r(name))
4593 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4594 [NSNull null], @"package",
4595 [NSArray arrayWithObjects:
4596 [NSDictionary dictionaryWithObjectsAndKeys:
4597 @"Conflicts", @"relationship",
4598 [NSArray arrayWithObjects:
4599 [NSDictionary dictionaryWithObjectsAndKeys:
4601 [NSNull null], @"version",
4602 @"installed", @"reason",
4609 if ([package essential])
4611 [removes addObject:name];
4614 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4615 substrate_ |= DepSubstrate(iterator.CurrentVer());
4620 else if (Advanced_) {
4621 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4623 essential_ = [[UIAlertView alloc]
4624 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4625 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4627 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4629 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4633 [essential_ setContext:@"remove"];
4635 essential_ = [[UIAlertView alloc]
4636 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4637 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4639 cancelButtonTitle:UCLocalize("OKAY")
4640 otherButtonTitles:nil
4643 [essential_ setContext:@"unable"];
4646 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4647 installs, @"installs",
4648 reinstalls, @"reinstalls",
4649 upgrades, @"upgrades",
4650 downgrades, @"downgrades",
4651 removes, @"removes",
4654 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4655 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4656 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4659 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4661 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4662 initWithTitle:UCLocalize("CANCEL")
4663 style:UIBarButtonItemStylePlain
4665 action:@selector(cancelButtonClicked)
4671 - (void) applyRightButton {
4672 if ([issues_ count] == 0 && ![self isLoading])
4673 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4674 initWithTitle:UCLocalize("CONFIRM")
4675 style:UIBarButtonItemStyleDone
4677 action:@selector(confirmButtonClicked)
4680 [[self navigationItem] setRightBarButtonItem:nil];
4684 - (void) cancelButtonClicked {
4685 [self dismissModalViewControllerAnimated:YES];
4686 [delegate_ cancelAndClear:YES];
4690 - (void) confirmButtonClicked {
4691 if (essential_ != nil)
4701 /* Progress Data {{{ */
4702 @interface ProgressData : NSObject {
4704 // XXX: should these really both be _transient?
4705 _transient id target_;
4706 _transient id object_;
4709 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4717 @implementation ProgressData
4719 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4720 if ((self = [super init]) != nil) {
4721 selector_ = selector;
4741 /* Progress Controller {{{ */
4742 @interface ProgressController : CYViewController <
4743 ConfigurationDelegate,
4746 _transient Database *database_;
4747 UIProgressBar *progress_;
4748 UITextView *output_;
4749 UITextLabel *status_;
4750 UIPushButton *close_;
4752 SHA1SumValue springlist_;
4753 SHA1SumValue notifyconf_;
4757 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4759 - (void) _retachThread;
4760 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4766 @protocol ProgressControllerDelegate
4767 - (void) progressControllerIsComplete:(ProgressController *)sender;
4770 @implementation ProgressController
4773 [database_ setDelegate:nil];
4774 [progress_ release];
4783 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4784 if ((self = [super init]) != nil) {
4785 database_ = database;
4786 [database_ setDelegate:self];
4787 delegate_ = delegate;
4789 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4791 progress_ = [[UIProgressBar alloc] init];
4792 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4793 [progress_ setStyle:0];
4795 status_ = [[UITextLabel alloc] init];
4796 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4797 [status_ setColor:[UIColor whiteColor]];
4798 [status_ setBackgroundColor:[UIColor clearColor]];
4799 [status_ setCentersHorizontally:YES];
4800 //[status_ setFont:font];
4802 output_ = [[UITextView alloc] init];
4803 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4804 //[output_ setTextFont:@"Courier New"];
4805 [output_ setFont:[[output_ font] fontWithSize:12]];
4806 [output_ setTextColor:[UIColor whiteColor]];
4807 [output_ setBackgroundColor:[UIColor clearColor]];
4808 [output_ setMarginTop:0];
4809 [output_ setAllowsRubberBanding:YES];
4810 [output_ setEditable:NO];
4811 [[self view] addSubview:output_];
4813 close_ = [[UIPushButton alloc] init];
4814 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4815 [close_ setAutosizesToFit:NO];
4816 [close_ setDrawsShadow:YES];
4817 [close_ setStretchBackground:YES];
4818 [close_ setEnabled:YES];
4819 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4820 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4821 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4822 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4826 - (void) positionViews {
4827 CGRect bounds = [[self view] bounds];
4828 CGSize prgsize = [UIProgressBar defaultSize];
4831 (bounds.size.width - prgsize.width) / 2,
4832 bounds.size.height - prgsize.height - 20
4835 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4837 [progress_ setFrame:prgrect];
4838 [status_ setFrame:CGRectMake(
4840 bounds.size.height - prgsize.height - 50,
4841 bounds.size.width - 20,
4844 [output_ setFrame:CGRectMake(
4847 bounds.size.width - 20,
4848 bounds.size.height - 96
4850 [close_ setFrame:CGRectMake(
4851 (bounds.size.width - closewidth) / 2,
4852 bounds.size.height - prgsize.height - 50,
4858 - (void) viewWillAppear:(BOOL)animated {
4859 [super viewDidAppear:animated];
4860 [[self navigationItem] setHidesBackButton:YES];
4861 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4863 [self positionViews];
4866 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4867 [self positionViews];
4870 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4871 NSString *context([alert context]);
4873 if ([context isEqualToString:@"conffile"]) {
4874 FILE *input = [database_ input];
4875 if (button == [alert cancelButtonIndex])
4876 fprintf(input, "N\n");
4877 else if (button == [alert firstOtherButtonIndex])
4878 fprintf(input, "Y\n");
4881 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4885 - (void) closeButtonPushed {
4888 UpdateExternalStatus(0);
4892 [self dismissModalViewControllerAnimated:YES];
4896 [delegate_ terminateWithSuccess];
4897 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4898 [delegate_ suspendWithAnimation:YES];
4900 [delegate_ suspend];*/
4912 system("/usr/bin/sbreload");
4918 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4919 SBReboot(SBSSpringBoardServerPort());
4921 reboot2(RB_AUTOBOOT);
4926 - (void) _retachThread {
4927 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4929 [[self view] addSubview:close_];
4930 [progress_ removeFromSuperview];
4931 [status_ removeFromSuperview];
4933 [database_ popErrorWithTitle:title_];
4934 [delegate_ progressControllerIsComplete:self];
4938 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4941 MMap mmap(file, MMap::ReadOnly);
4943 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4944 if (!(notifyconf_ == sha1.Result()))
4951 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4954 MMap mmap(file, MMap::ReadOnly);
4956 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4957 if (!(springlist_ == sha1.Result()))
4963 if (RestartSubstrate_)
4967 RestartSubstrate_ = false;
4970 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4971 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4972 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4973 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4974 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4978 system("su -c /usr/bin/uicache mobile");
4981 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4983 [delegate_ setStatusBarShowsProgress:NO];
4986 - (void) _detachNewThreadInvocation:(NSInvocation *)invocation { _pooled
4987 [invocation invoke];
4988 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4991 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4992 UpdateExternalStatus(1);
4999 title_ = [title retain];
5001 [[self navigationItem] setTitle:title_];
5003 [status_ setText:nil];
5004 [output_ setText:@""];
5005 [progress_ setProgress:0];
5007 [close_ removeFromSuperview];
5008 [[self view] addSubview:progress_];
5009 [[self view] addSubview:status_];
5011 [delegate_ setStatusBarShowsProgress:YES];
5016 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5019 MMap mmap(file, MMap::ReadOnly);
5021 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5022 notifyconf_ = sha1.Result();
5028 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5031 MMap mmap(file, MMap::ReadOnly);
5033 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5034 springlist_ = sha1.Result();
5038 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
5039 [invocation setTarget:target];
5040 [invocation setSelector:selector];
5041 _assert(object == nil);
5043 [NSThread detachNewThreadSelector:@selector(_detachNewThreadInvocation:) toTarget:self withObject:invocation];
5046 - (void) repairWithSelector:(SEL)selector {
5048 detachNewThreadSelector:selector
5051 title:UCLocalize("REPAIRING")
5055 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
5056 CYAlertView *sheet([[[CYAlertView alloc]
5058 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
5059 defaultButtonIndex:0
5062 [sheet setMessage:error];
5063 [sheet yieldToPopupAlertAnimated:YES];
5067 - (void) startProgress {
5070 - (bool) isProgressCancelled {
5074 - (void) setConfigurationData:(NSString *)data {
5075 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
5077 if (!conffile_r(data)) {
5078 lprintf("E:invalid conffile\n");
5082 NSString *ofile = conffile_r[1];
5083 //NSString *nfile = conffile_r[2];
5085 UIAlertView *alert = [[[UIAlertView alloc]
5086 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
5087 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
5089 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
5091 UCLocalize("ACCEPT_NEW_COPY"),
5092 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
5096 [alert setContext:@"conffile"];
5100 - (void) setProgressTitle:(NSString *)title {
5101 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
5102 for (size_t i(0), e([words count]); i != e; ++i) {
5103 NSString *word([words objectAtIndex:i]);
5104 if (Package *package = [database_ packageWithName:word])
5105 [words replaceObjectAtIndex:i withObject:[package name]];
5108 [status_ setText:[words componentsJoinedByString:@" "]];
5111 - (void) setProgressPercent:(NSNumber *)percent {
5112 [progress_ setProgress:[percent floatValue]];
5115 - (void) addProgressOutput:(NSString *)output {
5116 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
5117 CGSize size = [output_ contentSize];
5118 CGPoint offset = [output_ contentOffset];
5119 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
5120 CGRect rect = {{0, size.height-1}, {size.width, 1}};
5121 [output_ scrollRectToVisible:rect animated:YES];
5125 - (BOOL) isRunning {
5132 /* Cell Content View {{{ */
5133 @protocol ContentDelegate
5134 - (void) drawContentRect:(CGRect)rect;
5137 @interface ContentView : UIView {
5138 _transient id<ContentDelegate> delegate_;
5143 @implementation ContentView
5145 - (id) initWithFrame:(CGRect)frame {
5146 if ((self = [super initWithFrame:frame]) != nil) {
5147 [self setNeedsDisplayOnBoundsChange:YES];
5151 - (void) setDelegate:(id<ContentDelegate>)delegate {
5152 delegate_ = delegate;
5155 - (void) drawRect:(CGRect)rect {
5156 [super drawRect:rect];
5157 [delegate_ drawContentRect:rect];
5162 /* Cydia TableView Cell {{{ */
5163 @interface CYTableViewCell : UITableViewCell {
5164 ContentView *content_;
5170 @implementation CYTableViewCell
5177 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5178 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5180 if (view == content_) {
5181 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5182 highlighted_ = highlighted;
5185 [super _updateHighlightColorsForView:view highlighted:highlighted];
5188 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5189 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5190 highlighted_ = selected;
5192 [super setSelected:selected animated:animated];
5193 [content_ setNeedsDisplay];
5199 /* Package Cell {{{ */
5200 @interface PackageCell : CYTableViewCell <
5205 NSString *description_;
5213 - (PackageCell *) init;
5214 - (void) setPackage:(Package *)package;
5216 - (void) drawContentRect:(CGRect)rect;
5220 @implementation PackageCell
5222 - (void) clearPackage {
5233 if (description_ != nil) {
5234 [description_ release];
5238 if (source_ != nil) {
5243 if (badge_ != nil) {
5248 if (placard_ != nil) {
5258 [self clearPackage];
5262 - (PackageCell *) init {
5263 CGRect frame(CGRectMake(0, 0, 320, 74));
5264 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5265 UIView *content([self contentView]);
5266 CGRect bounds([content bounds]);
5268 content_ = [[ContentView alloc] initWithFrame:bounds];
5269 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5270 [content addSubview:content_];
5272 [content_ setDelegate:self];
5273 [content_ setOpaque:YES];
5277 - (NSString *) accessibilityLabel {
5278 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5281 - (void) setPackage:(Package *)package {
5282 [self clearPackage];
5285 Source *source = [package source];
5287 icon_ = [[package icon] retain];
5288 name_ = [[package name] retain];
5291 description_ = [package longDescription];
5292 if (description_ == nil)
5293 description_ = [package shortDescription];
5294 if (description_ != nil)
5295 description_ = [description_ retain];
5297 commercial_ = [package isCommercial];
5299 package_ = [package retain];
5301 NSString *label = nil;
5302 bool trusted = false;
5304 if (source != nil) {
5305 label = [source label];
5306 trusted = [source trusted];
5307 } else if ([[package id] isEqualToString:@"firmware"])
5308 label = UCLocalize("APPLE");
5310 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5312 NSString *from(label);
5314 NSString *section = [package simpleSection];
5315 if (section != nil && ![section isEqualToString:label]) {
5316 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5317 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5320 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5321 source_ = [from retain];
5323 if (NSString *purpose = [package primaryPurpose])
5324 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5325 badge_ = [badge_ retain];
5330 if (NSString *mode = [package_ mode]) {
5331 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5332 color = RemovingColor_;
5333 //placard = @"removing";
5335 color = InstallingColor_;
5336 //placard = @"installing";
5339 // XXX: the removing/installing placards are not @2x
5342 color = [UIColor whiteColor];
5344 if ([package installed] != nil)
5345 placard = @"installed";
5350 [content_ setBackgroundColor:color];
5353 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5354 placard_ = [placard_ retain];
5356 [self setNeedsDisplay];
5357 [content_ setNeedsDisplay];
5360 - (void) drawContentRect:(CGRect)rect {
5361 bool highlighted(highlighted_);
5362 float width([self bounds].size.width);
5365 CGContextRef context(UIGraphicsGetCurrentContext());
5366 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5367 CGContextFillRect(context, rect);
5372 rect.size = [icon_ size];
5374 rect.size.width /= 2;
5375 rect.size.height /= 2;
5377 rect.origin.x = 25 - rect.size.width / 2;
5378 rect.origin.y = 25 - rect.size.height / 2;
5380 [icon_ drawInRect:rect];
5383 if (badge_ != nil) {
5385 rect.size = [badge_ size];
5387 rect.size.width /= 2;
5388 rect.size.height /= 2;
5390 rect.origin.x = 36 - rect.size.width / 2;
5391 rect.origin.y = 36 - rect.size.height / 2;
5393 [badge_ drawInRect:rect];
5400 UISetColor(commercial_ ? Purple_ : Black_);
5401 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5402 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5405 UISetColor(commercial_ ? Purplish_ : Gray_);
5406 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5408 if (placard_ != nil)
5409 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5414 /* Section Cell {{{ */
5415 @interface SectionCell : CYTableViewCell <
5427 - (void) setSection:(Section *)section editing:(BOOL)editing;
5431 @implementation SectionCell
5433 - (void) clearSection {
5434 if (basic_ != nil) {
5439 if (section_ != nil) {
5449 if (count_ != nil) {
5456 [self clearSection];
5462 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5463 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5464 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5465 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5466 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5468 UIView *content([self contentView]);
5469 CGRect bounds([content bounds]);
5471 content_ = [[ContentView alloc] initWithFrame:bounds];
5472 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5473 [content addSubview:content_];
5474 [content_ setBackgroundColor:[UIColor whiteColor]];
5476 [content_ setDelegate:self];
5480 - (void) onSwitch:(id)sender {
5481 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5482 if (metadata == nil) {
5483 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5484 [Sections_ setObject:metadata forKey:basic_];
5487 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5491 - (void) setSection:(Section *)section editing:(BOOL)editing {
5492 if (editing != editing_) {
5494 [switch_ removeFromSuperview];
5496 [self addSubview:switch_];
5500 [self clearSection];
5502 if (section == nil) {
5503 name_ = [UCLocalize("ALL_PACKAGES") retain];
5506 basic_ = [section name];
5508 basic_ = [basic_ retain];
5510 section_ = [section localized];
5511 if (section_ != nil)
5512 section_ = [section_ retain];
5514 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5515 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5518 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5521 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5522 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5524 [content_ setNeedsDisplay];
5527 - (void) setFrame:(CGRect)frame {
5528 [super setFrame:frame];
5530 CGRect rect([switch_ frame]);
5531 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5534 - (NSString *) accessibilityLabel {
5538 - (void) drawContentRect:(CGRect)rect {
5539 bool highlighted(highlighted_ && !editing_);
5541 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5546 float width(rect.size.width);
5552 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5554 CGSize size = [count_ sizeWithFont:Font14_];
5558 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5564 /* File Table {{{ */
5565 @interface FileTable : CYViewController <
5566 UITableViewDataSource,
5569 _transient Database *database_;
5572 NSMutableArray *files_;
5576 - (id) initWithDatabase:(Database *)database;
5577 - (void) setPackage:(Package *)package;
5581 @implementation FileTable
5584 [self releaseSubviews];
5593 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5594 return files_ == nil ? 0 : [files_ count];
5597 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5601 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5602 static NSString *reuseIdentifier = @"Cell";
5604 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5606 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5607 [cell setFont:[UIFont systemFontOfSize:16]];
5609 [cell setText:[files_ objectAtIndex:indexPath.row]];
5610 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5615 - (NSURL *) navigationURL {
5616 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5620 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5622 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5623 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5624 [list_ setRowHeight:24.0f];
5625 [list_ setDataSource:self];
5626 [list_ setDelegate:self];
5627 [[self view] addSubview:list_];
5630 - (void) viewDidLoad {
5631 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5634 - (void) releaseSubviews {
5639 - (id) initWithDatabase:(Database *)database {
5640 if ((self = [super init]) != nil) {
5641 database_ = database;
5643 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5647 - (void) setPackage:(Package *)package {
5648 if (package_ != nil) {
5649 [package_ autorelease];
5658 [files_ removeAllObjects];
5660 if (package != nil) {
5661 package_ = [package retain];
5662 name_ = [[package id] retain];
5664 if (NSArray *files = [package files])
5665 [files_ addObjectsFromArray:files];
5667 if ([files_ count] != 0) {
5668 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5669 [files_ removeObjectAtIndex:0];
5670 [files_ sortUsingSelector:@selector(compareByPath:)];
5672 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5673 [stack addObject:@"/"];
5675 for (int i(0), e([files_ count]); i != e; ++i) {
5676 NSString *file = [files_ objectAtIndex:i];
5677 while (![file hasPrefix:[stack lastObject]])
5678 [stack removeLastObject];
5679 NSString *directory = [stack lastObject];
5680 [stack addObject:[file stringByAppendingString:@"/"]];
5681 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5682 ([stack count] - 2) * 3, "",
5683 [file substringFromIndex:[directory length]]
5692 - (void) reloadData {
5695 [self setPackage:[database_ packageWithName:name_]];
5700 /* Package Controller {{{ */
5701 @interface CYPackageController : CYBrowserController <
5702 UIActionSheetDelegate
5704 _transient Database *database_;
5708 NSMutableArray *buttons_;
5709 UIBarButtonItem *button_;
5712 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5716 @implementation CYPackageController
5719 if (package_ != nil)
5732 - (NSURL *) navigationURL {
5733 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5736 /* XXX: this is not safe at all... localization of /fail/ */
5737 - (void) _clickButtonWithName:(NSString *)name {
5738 if ([name isEqualToString:UCLocalize("CLEAR")])
5739 [delegate_ clearPackage:package_];
5740 else if ([name isEqualToString:UCLocalize("INSTALL")])
5741 [delegate_ installPackage:package_];
5742 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5743 [delegate_ installPackage:package_];
5744 else if ([name isEqualToString:UCLocalize("REMOVE")])
5745 [delegate_ removePackage:package_];
5746 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5747 [delegate_ installPackage:package_];
5748 else _assert(false);
5751 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5752 NSString *context([sheet context]);
5754 if ([context isEqualToString:@"modify"]) {
5755 if (button != [sheet cancelButtonIndex]) {
5756 NSString *buttonName = [buttons_ objectAtIndex:button];
5757 [self _clickButtonWithName:buttonName];
5760 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5764 - (bool) _allowJavaScriptPanel {
5769 - (void) _customButtonClicked {
5770 int count([buttons_ count]);
5775 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5777 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5778 [buttons addObjectsFromArray:buttons_];
5780 UIActionSheet *sheet = [[[UIActionSheet alloc]
5783 cancelButtonTitle:nil
5784 destructiveButtonTitle:nil
5785 otherButtonTitles:nil
5788 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5790 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5791 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5793 [sheet setContext:@"modify"];
5795 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5799 // We don't want to allow non-commercial packages to do custom things to the install button,
5800 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5801 - (void) customButtonClicked {
5803 [super customButtonClicked];
5805 [self _customButtonClicked];
5808 - (void) reloadButtonClicked {
5809 // Don't reload a commerical package by tapping the loading button,
5810 // but if it's not an Install button, we should forward it on.
5811 if (![package_ uninstalled])
5812 [self _customButtonClicked];
5815 - (void) applyLoadingTitle {
5816 // Don't show "Loading" as the title. Ever.
5819 - (UIBarButtonItem *) rightButton {
5824 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5825 if ((self = [super init]) != nil) {
5826 database_ = database;
5827 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5828 name_ = [[NSString alloc] initWithString:name];
5829 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5833 - (void) reloadData {
5834 if (package_ != nil)
5835 [package_ autorelease];
5836 package_ = [database_ packageWithName:name_];
5838 [buttons_ removeAllObjects];
5840 if (package_ != nil) {
5843 package_ = [package_ retain];
5844 commercial_ = [package_ isCommercial];
5846 if ([package_ mode] != nil)
5847 [buttons_ addObject:UCLocalize("CLEAR")];
5848 if ([package_ source] == nil);
5849 else if ([package_ upgradableAndEssential:NO])
5850 [buttons_ addObject:UCLocalize("UPGRADE")];
5851 else if ([package_ uninstalled])
5852 [buttons_ addObject:UCLocalize("INSTALL")];
5854 [buttons_ addObject:UCLocalize("REINSTALL")];
5855 if (![package_ uninstalled])
5856 [buttons_ addObject:UCLocalize("REMOVE")];
5863 switch ([buttons_ count]) {
5864 case 0: title = nil; break;
5865 case 1: title = [buttons_ objectAtIndex:0]; break;
5866 default: title = UCLocalize("MODIFY"); break;
5869 button_ = [[UIBarButtonItem alloc]
5871 style:UIBarButtonItemStylePlain
5873 action:@selector(customButtonClicked)
5879 - (bool) isLoading {
5880 return commercial_ ? [super isLoading] : false;
5886 /* Package List Controller {{{ */
5887 @interface PackageListController : CYViewController <
5888 UITableViewDataSource,
5891 _transient Database *database_;
5893 NSMutableArray *packages_;
5894 NSMutableArray *sections_;
5896 NSMutableArray *index_;
5897 NSMutableDictionary *indices_;
5901 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5902 - (void) setDelegate:(id)delegate;
5903 - (void) resetCursor;
5907 @implementation PackageListController
5910 [packages_ release];
5911 [sections_ release];
5920 - (void) deselectWithAnimation:(BOOL)animated {
5921 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5924 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5925 CGRect base = [[self view] bounds];
5926 base.size.height -= bounds.size.height;
5927 base.origin = [list_ frame].origin;
5929 [UIView beginAnimations:nil context:NULL];
5930 [UIView setAnimationBeginsFromCurrentState:YES];
5931 [UIView setAnimationCurve:curve];
5932 [UIView setAnimationDuration:duration];
5933 [list_ setFrame:base];
5934 [UIView commitAnimations];
5937 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5938 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5941 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5942 [self resizeForKeyboardBounds:bounds duration:0];
5945 - (void) keyboardWillShow:(NSNotification *)notification {
5948 NSTimeInterval duration;
5949 UIViewAnimationCurve curve;
5950 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5951 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5952 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5953 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5955 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);
5956 UIViewController *base = self;
5957 while ([base parentViewController] != nil)
5958 base = [base parentViewController];
5959 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5960 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5962 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5965 - (void) keyboardWillHide:(NSNotification *)notification {
5966 NSTimeInterval duration;
5967 UIViewAnimationCurve curve;
5968 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5969 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5971 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5974 - (void) viewWillAppear:(BOOL)animated {
5975 [super viewWillAppear:animated];
5977 [self resizeForKeyboardBounds:CGRectZero];
5978 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5979 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5982 - (void) viewWillDisappear:(BOOL)animated {
5983 [super viewWillDisappear:animated];
5985 [self resizeForKeyboardBounds:CGRectZero];
5986 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5987 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5990 - (void) viewDidAppear:(BOOL)animated {
5991 [super viewDidAppear:animated];
5992 [self deselectWithAnimation:animated];
5995 - (void) didSelectPackage:(Package *)package {
5996 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5997 [view setDelegate:delegate_];
5998 [[self navigationController] pushViewController:view animated:YES];
6001 #if TryIndexedCollation
6002 + (BOOL) hasIndexedCollation {
6003 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6007 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6008 NSInteger count([sections_ count]);
6009 return count == 0 ? 1 : count;
6012 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6013 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6015 return [[sections_ objectAtIndex:section] name];
6018 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6019 if ([sections_ count] == 0)
6021 return [[sections_ objectAtIndex:section] count];
6024 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6025 @synchronized (database_) {
6026 if ([database_ era] != era_)
6029 Section *section([sections_ objectAtIndex:[path section]]);
6030 NSInteger row([path row]);
6031 Package *package([packages_ objectAtIndex:([section row] + row)]);
6032 return [[package retain] autorelease];
6035 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6036 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6038 cell = [[[PackageCell alloc] init] autorelease];
6039 [cell setPackage:[self packageAtIndexPath:path]];
6043 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6044 Package *package([self packageAtIndexPath:path]);
6045 package = [database_ packageWithName:[package id]];
6046 [self didSelectPackage:package];
6049 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6050 // XXX: is 20 the most optimal number here?
6051 return [packages_ count] > 20 ? index_ : nil;
6054 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6055 #if TryIndexedCollation
6056 if ([[self class] hasIndexedCollation]) {
6057 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6064 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6065 if ((self = [super init]) != nil) {
6066 database_ = database;
6067 title_ = [title copy];
6068 [[self navigationItem] setTitle:title_];
6070 #if TryIndexedCollation
6071 if ([[self class] hasIndexedCollation])
6072 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6075 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6077 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6079 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6080 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6082 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6083 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6084 [list_ setRowHeight:73];
6085 [[self view] addSubview:list_];
6087 [list_ setDataSource:self];
6088 [list_ setDelegate:self];
6092 - (void) setDelegate:(id)delegate {
6093 delegate_ = delegate;
6096 - (bool) hasPackage:(Package *)package {
6100 - (void) reloadData {
6103 era_ = [database_ era];
6104 NSArray *packages = [database_ packages];
6106 [packages_ removeAllObjects];
6107 [sections_ removeAllObjects];
6109 _profile(PackageTable$reloadData$Filter)
6110 for (Package *package in packages)
6111 if ([self hasPackage:package])
6112 [packages_ addObject:package];
6115 [indices_ removeAllObjects];
6117 Section *section = nil;
6119 #if TryIndexedCollation
6120 if ([[self class] hasIndexedCollation]) {
6121 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6122 NSArray *titles = [collation sectionIndexTitles];
6125 _profile(PackageTable$reloadData$Section)
6126 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6130 _profile(PackageTable$reloadData$Section$Package)
6131 package = [packages_ objectAtIndex:offset];
6132 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6135 while (secidx < index) {
6138 _profile(PackageTable$reloadData$Section$Allocate)
6139 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6142 _profile(PackageTable$reloadData$Section$Add)
6143 [sections_ addObject:section];
6147 [section addToCount];
6153 [index_ removeAllObjects];
6155 _profile(PackageTable$reloadData$Section)
6156 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6160 _profile(PackageTable$reloadData$Section$Package)
6161 package = [packages_ objectAtIndex:offset];
6162 index = [package index];
6165 if (section == nil || [section index] != index) {
6166 _profile(PackageTable$reloadData$Section$Allocate)
6167 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6170 [index_ addObject:[section name]];
6171 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6173 _profile(PackageTable$reloadData$Section$Add)
6174 [sections_ addObject:section];
6178 [section addToCount];
6183 _profile(PackageTable$reloadData$List)
6188 - (void) resetCursor {
6189 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6194 /* Filtered Package List Controller {{{ */
6195 @interface FilteredPackageListController : PackageListController {
6201 - (void) setObject:(id)object;
6202 - (void) setObject:(id)object forFilter:(SEL)filter;
6204 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6208 @implementation FilteredPackageListController
6216 - (void) setFilter:(SEL)filter {
6219 /* XXX: this is an unsafe optimization of doomy hell */
6220 Method method(class_getInstanceMethod([Package class], filter));
6221 _assert(method != NULL);
6222 imp_ = method_getImplementation(method);
6223 _assert(imp_ != NULL);
6226 - (void) setObject:(id)object {
6232 object_ = [object retain];
6235 - (void) setObject:(id)object forFilter:(SEL)filter {
6236 [self setFilter:filter];
6237 [self setObject:object];
6240 - (bool) hasPackage:(Package *)package {
6241 _profile(FilteredPackageTable$hasPackage)
6242 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6246 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6247 if ((self = [super initWithDatabase:database title:title]) != nil) {
6248 [self setFilter:filter];
6249 [self setObject:object];
6256 /* Home Controller {{{ */
6257 @interface HomeController : CYBrowserController {
6262 @implementation HomeController
6264 + (BOOL) shouldHideNavigationBar {
6268 - (NSURL *) navigationURL {
6269 return [NSURL URLWithString:@"cydia://home"];
6272 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6273 [super _setMoreHeaders:request];
6276 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6277 if (UniqueID_ != nil)
6278 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6280 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6283 - (void) aboutButtonClicked {
6284 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6286 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6287 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6288 [alert setCancelButtonIndex:0];
6291 @"Copyright (C) 2008-2011\n"
6292 "Jay Freeman (saurik)\n"
6293 "saurik@saurik.com\n"
6294 "http://www.saurik.com/"
6300 - (void) viewWillDisappear:(BOOL)animated {
6301 [super viewWillDisappear:animated];
6303 if ([[self class] shouldHideNavigationBar])
6304 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6307 - (void) viewWillAppear:(BOOL)animated {
6308 if (![self hasLoaded])
6309 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6311 [super viewWillAppear:animated];
6313 if ([[self class] shouldHideNavigationBar])
6314 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6317 - (void) viewDidLoad {
6318 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6319 initWithTitle:UCLocalize("ABOUT")
6320 style:UIBarButtonItemStylePlain
6322 action:@selector(aboutButtonClicked)
6328 /* Manage Controller {{{ */
6329 @interface ManageController : CYBrowserController {
6332 - (void) queueStatusDidChange;
6336 @implementation ManageController
6338 - (NSURL *) navigationURL {
6339 return [NSURL URLWithString:@"cydia://manage"];
6342 - (void) viewWillAppear:(BOOL)animated {
6343 if (![self hasLoaded])
6344 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6346 [super viewWillAppear:animated];
6349 - (void) viewDidLoad {
6350 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6351 initWithTitle:UCLocalize("SETTINGS")
6352 style:UIBarButtonItemStylePlain
6354 action:@selector(settingsButtonClicked)
6357 [self queueStatusDidChange];
6360 - (void) settingsButtonClicked {
6361 [delegate_ showSettings];
6365 - (void) queueButtonClicked {
6369 - (void) applyLoadingTitle {
6370 // Disable "Loading" title.
6373 - (void) applyRightButton {
6374 // Disable right button.
6378 - (void) queueStatusDidChange {
6380 if (!IsWildcat_ && Queuing_) {
6381 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6382 initWithTitle:UCLocalize("QUEUE")
6383 style:UIBarButtonItemStyleDone
6385 action:@selector(queueButtonClicked)
6388 [[self navigationItem] setRightBarButtonItem:nil];
6393 - (bool) isLoading {
6394 // Never show as loading.
6401 /* Refresh Bar {{{ */
6402 @interface RefreshBar : UINavigationBar {
6403 UIProgressIndicator *indicator_;
6404 UITextLabel *prompt_;
6405 UIProgressBar *progress_;
6406 UINavigationButton *cancel_;
6411 @implementation RefreshBar
6414 [indicator_ release];
6416 [progress_ release];
6421 - (void) positionViews {
6422 CGRect frame = [cancel_ frame];
6423 frame.size = [cancel_ sizeThatFits:frame.size];
6424 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6425 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6426 [cancel_ setFrame:frame];
6428 CGSize prgsize = {75, 100};
6430 [self frame].size.width - prgsize.width - 10,
6431 ([self frame].size.height - prgsize.height) / 2
6433 [progress_ setFrame:prgrect];
6435 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6436 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6437 CGRect indrect = {{indoffset, indoffset}, indsize};
6438 [indicator_ setFrame:indrect];
6440 CGSize prmsize = {215, indsize.height + 4};
6442 indoffset * 2 + indsize.width,
6443 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6445 [prompt_ setFrame:prmrect];
6448 - (void) setFrame:(CGRect)frame {
6449 [super setFrame:frame];
6450 [self positionViews];
6453 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6454 if ((self = [super initWithFrame:frame]) != nil) {
6455 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6457 [self setBarStyle:UIBarStyleBlack];
6459 UIBarStyle barstyle([self _barStyle:NO]);
6460 bool ugly(barstyle == UIBarStyleDefault);
6462 UIProgressIndicatorStyle style = ugly ?
6463 UIProgressIndicatorStyleMediumBrown :
6464 UIProgressIndicatorStyleMediumWhite;
6466 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6467 [indicator_ setStyle:style];
6468 [indicator_ startAnimation];
6469 [self addSubview:indicator_];
6471 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6472 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6473 [prompt_ setBackgroundColor:[UIColor clearColor]];
6474 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6475 [self addSubview:prompt_];
6477 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6478 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6479 [progress_ setStyle:0];
6480 [self addSubview:progress_];
6482 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6483 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6484 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6485 [cancel_ setBarStyle:barstyle];
6487 [self positionViews];
6492 [cancel_ removeFromSuperview];
6496 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6497 [progress_ setProgress:0];
6498 [self addSubview:cancel_];
6502 [cancel_ removeFromSuperview];
6505 - (void) setPrompt:(NSString *)prompt {
6506 [prompt_ setText:prompt];
6509 - (void) setProgress:(float)progress {
6510 [progress_ setProgress:progress];
6516 @class CYNavigationController;
6518 /* Cydia Tab Bar Controller {{{ */
6519 @interface CYTabBarController : UITabBarController <
6520 UITabBarControllerDelegate,
6523 _transient Database *database_;
6524 RefreshBar *refreshbar_;
6528 // XXX: ok, "updatedelegate_"?...
6529 _transient NSObject<CydiaDelegate> *updatedelegate_;
6532 UIViewController *remembered_;
6533 _transient UIViewController *transient_;
6536 - (NSArray *) navigationURLCollection;
6537 - (void) dropBar:(BOOL)animated;
6538 - (void) beginUpdate;
6539 - (void) raiseBar:(BOOL)animated;
6544 @implementation CYTabBarController
6546 - (void) setUnselectedViewController:(UIViewController *)transient {
6547 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6548 if (transient != nil) {
6549 if (transient_ == nil)
6550 remembered_ = [[controllers objectAtIndex:0] retain];
6551 transient_ = transient;
6552 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6553 [controllers replaceObjectAtIndex:0 withObject:transient_];
6554 [self setSelectedIndex:0];
6555 [self setViewControllers:controllers];
6556 [self concealTabBarSelection];
6557 } else if (remembered_ != nil) {
6558 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6559 transient_ = transient;
6560 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6561 [remembered_ release];
6563 [self setViewControllers:controllers];
6564 [self revealTabBarSelection];
6568 - (UIViewController *) unselectedViewController {
6572 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6573 if ([self unselectedViewController])
6574 [self setUnselectedViewController:nil];
6577 - (NSArray *) navigationURLCollection {
6578 NSMutableArray *items([NSMutableArray array]);
6580 // XXX: Should this deal with transient view controllers?
6581 for (id navigation in [self viewControllers]) {
6582 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6584 [items addObject:stack];
6590 - (void) reloadData {
6591 for (CYViewController *controller in [self viewControllers])
6592 [controller reloadData];
6594 [(CYNavigationController *)[self unselectedViewController] reloadData];
6598 [refreshbar_ release];
6599 [[NSNotificationCenter defaultCenter] removeObserver:self];
6604 - (id) initWithDatabase:(Database *)database {
6605 if ((self = [super init]) != nil) {
6606 database_ = database;
6607 [self setDelegate:self];
6609 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6610 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6612 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6616 - (void) setUpdate:(NSDate *)date {
6620 - (void) beginUpdate {
6621 [refreshbar_ start];
6624 [updatedelegate_ retainNetworkActivityIndicator];
6628 detachNewThreadSelector:@selector(performUpdate)
6634 - (void) performUpdate { _pooled
6636 status.setDelegate(self);
6637 [database_ updateWithStatus:status];
6640 performSelectorOnMainThread:@selector(completeUpdate)
6646 - (void) stopUpdateWithSelector:(SEL)selector {
6648 [updatedelegate_ releaseNetworkActivityIndicator];
6650 [self raiseBar:YES];
6653 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6656 - (void) completeUpdate {
6659 [self stopUpdateWithSelector:@selector(reloadData)];
6662 - (void) cancelUpdate {
6663 [self stopUpdateWithSelector:@selector(updateData)];
6666 - (void) cancelPressed {
6667 [self cancelUpdate];
6674 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6675 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6678 - (void) startProgress {
6681 - (bool) isProgressCancelled {
6685 - (void) setProgressTitle:(NSString *)title {
6686 [refreshbar_ setPrompt:title];
6689 - (void) setProgressPercent:(NSNumber *)percent {
6690 [refreshbar_ setProgress:[percent floatValue]];
6693 - (void) addProgressOutput:(NSString *)output {
6696 - (void) setUpdateDelegate:(id)delegate {
6697 updatedelegate_ = delegate;
6700 - (CGFloat) statusBarHeight {
6701 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6702 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6704 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6708 - (UIView *) transitionView {
6709 if ([self respondsToSelector:@selector(_transitionView)])
6710 return [self _transitionView];
6712 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6715 - (void) dropBar:(BOOL)animated {
6720 UIView *transition([self transitionView]);
6721 [[self view] addSubview:refreshbar_];
6723 CGRect barframe([refreshbar_ frame]);
6725 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6726 barframe.origin.y = [self statusBarHeight];
6728 barframe.origin.y = 0;
6730 [refreshbar_ setFrame:barframe];
6733 [UIView beginAnimations:nil context:NULL];
6735 CGRect viewframe = [transition frame];
6736 viewframe.origin.y += barframe.size.height;
6737 viewframe.size.height -= barframe.size.height;
6738 [transition setFrame:viewframe];
6741 [UIView commitAnimations];
6743 // Ensure bar has the proper width for our view, it might have changed
6744 barframe.size.width = viewframe.size.width;
6745 [refreshbar_ setFrame:barframe];
6747 // XXX: fix Apple's layout bug
6748 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6751 - (void) raiseBar:(BOOL)animated {
6756 UIView *transition([self transitionView]);
6757 [refreshbar_ removeFromSuperview];
6759 CGRect barframe([refreshbar_ frame]);
6762 [UIView beginAnimations:nil context:NULL];
6764 CGRect viewframe = [transition frame];
6765 viewframe.origin.y -= barframe.size.height;
6766 viewframe.size.height += barframe.size.height;
6767 [transition setFrame:viewframe];
6770 [UIView commitAnimations];
6772 // XXX: fix Apple's layout bug
6773 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6777 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6778 // XXX: fix Apple's layout bug
6779 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6783 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6784 bool dropped(dropped_);
6789 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6794 // XXX: fix Apple's layout bug
6795 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6798 - (void) statusBarFrameChanged:(NSNotification *)notification {
6807 /* Cydia Navigation Controller {{{ */
6808 @interface CYNavigationController : UINavigationController {
6809 _transient Database *database_;
6810 _transient id<UINavigationControllerDelegate> delegate_;
6813 - (NSArray *) navigationURLCollection;
6814 - (id) initWithDatabase:(Database *)database;
6815 - (void) reloadData;
6820 @implementation CYNavigationController
6822 - (NSArray *) navigationURLCollection {
6823 NSMutableArray *stack([NSMutableArray array]);
6825 for (CYViewController *controller in [self viewControllers]) {
6826 NSString *url = [[controller navigationURL] absoluteString];
6828 [stack addObject:url];
6834 - (void) reloadData {
6835 for (CYViewController *page in [self viewControllers]) {
6836 // Only reload controllers that have already loaded.
6837 // This prevents a page from accidentally loading too
6838 // early if it hasn't been shown on the screen yet.
6839 if ([page hasLoaded])
6844 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6845 delegate_ = delegate;
6848 - (id) initWithDatabase:(Database *)database {
6849 if ((self = [super init]) != nil) {
6850 database_ = database;
6857 /* Cydia:// Protocol {{{ */
6858 @interface CydiaURLProtocol : NSURLProtocol {
6863 @implementation CydiaURLProtocol
6865 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6866 NSURL *url([request URL]);
6869 NSString *scheme([[url scheme] lowercaseString]);
6870 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6875 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6879 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6880 id<NSURLProtocolClient> client([self client]);
6882 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6884 NSData *data(UIImagePNGRepresentation(icon));
6886 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6887 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6888 [client URLProtocol:self didLoadData:data];
6889 [client URLProtocolDidFinishLoading:self];
6893 - (void) startLoading {
6894 id<NSURLProtocolClient> client([self client]);
6895 NSURLRequest *request([self request]);
6897 NSURL *url([request URL]);
6898 NSString *href([url absoluteString]);
6900 NSString *path([href substringFromIndex:8]);
6901 NSRange slash([path rangeOfString:@"/"]);
6904 if (slash.location == NSNotFound) {
6908 command = [path substringToIndex:slash.location];
6909 path = [path substringFromIndex:(slash.location + 1)];
6912 Database *database([Database sharedInstance]);
6914 if ([command isEqualToString:@"package-icon"]) {
6917 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6918 Package *package([database packageWithName:path]);
6921 UIImage *icon([package icon]);
6922 [self _returnPNGWithImage:icon forRequest:request];
6923 } else if ([command isEqualToString:@"source-icon"]) {
6926 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6927 NSString *source(Simplify(path));
6928 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6930 icon = [UIImage applicationImageNamed:@"unknown.png"];
6931 [self _returnPNGWithImage:icon forRequest:request];
6932 } else if ([command isEqualToString:@"uikit-image"]) {
6935 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6936 UIImage *icon(_UIImageWithName(path));
6937 [self _returnPNGWithImage:icon forRequest:request];
6938 } else if ([command isEqualToString:@"section-icon"]) {
6941 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6942 NSString *section(Simplify(path));
6943 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6945 icon = [UIImage applicationImageNamed:@"unknown.png"];
6946 [self _returnPNGWithImage:icon forRequest:request];
6948 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6952 - (void) stopLoading {
6958 /* Section Controller {{{ */
6959 @interface SectionController : FilteredPackageListController {
6963 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6967 @implementation SectionController
6969 - (NSURL *) navigationURL {
6970 NSString *name = section_;
6974 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6977 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6980 title = UCLocalize("ALL_PACKAGES");
6981 else if (![name isEqual:@""])
6982 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6984 title = UCLocalize("NO_SECTION");
6986 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6993 /* Sections Controller {{{ */
6994 @interface SectionsController : CYViewController <
6995 UITableViewDataSource,
6998 _transient Database *database_;
6999 NSMutableArray *sections_;
7000 NSMutableArray *filtered_;
7005 - (id) initWithDatabase:(Database *)database;
7006 - (void) editButtonClicked;
7010 @implementation SectionsController
7013 [self releaseSubviews];
7014 [sections_ release];
7015 [filtered_ release];
7020 - (NSURL *) navigationURL {
7021 return [NSURL URLWithString:@"cydia://sections"];
7024 - (void) updateNavigationItem {
7025 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7026 if ([sections_ count] == 0) {
7027 [[self navigationItem] setRightBarButtonItem:nil];
7029 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7030 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7032 action:@selector(editButtonClicked)
7033 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7037 - (BOOL) isEditing {
7041 - (void) setEditing:(BOOL)editing {
7042 if ((editing_ = editing))
7045 [delegate_ updateData];
7047 [self updateNavigationItem];
7050 - (void) viewDidAppear:(BOOL)animated {
7051 [super viewDidAppear:animated];
7052 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7055 - (void) viewWillDisappear:(BOOL)animated {
7056 [super viewWillDisappear:animated];
7057 if (editing_) [self setEditing:NO];
7060 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7061 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7065 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7066 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7069 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7073 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7074 static NSString *reuseIdentifier = @"SectionCell";
7076 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7078 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7080 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7085 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7089 Section *section = [self sectionAtIndexPath:indexPath];
7091 SectionController *controller = [[[SectionController alloc]
7092 initWithDatabase:database_
7093 section:[section name]
7095 [controller setDelegate:delegate_];
7097 [[self navigationController] pushViewController:controller animated:YES];
7101 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7103 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7104 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7105 [list_ setRowHeight:45.0f];
7106 [list_ setDataSource:self];
7107 [list_ setDelegate:self];
7108 [[self view] addSubview:list_];
7111 - (void) viewDidLoad {
7112 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7115 - (void) releaseSubviews {
7120 - (id) initWithDatabase:(Database *)database {
7121 if ((self = [super init]) != nil) {
7122 database_ = database;
7124 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7125 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7129 - (void) reloadData {
7132 NSArray *packages = [database_ packages];
7134 [sections_ removeAllObjects];
7135 [filtered_ removeAllObjects];
7137 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7140 for (Package *package in packages) {
7141 NSString *name([package section]);
7142 NSString *key(name == nil ? @"" : name);
7146 _profile(SectionsView$reloadData$Section)
7147 section = [sections objectForKey:key];
7148 if (section == nil) {
7149 _profile(SectionsView$reloadData$Section$Allocate)
7150 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7151 [sections setObject:section forKey:key];
7156 [section addToCount];
7158 _profile(SectionsView$reloadData$Filter)
7159 if (![package valid] || ![package visible])
7167 [sections_ addObjectsFromArray:[sections allValues]];
7169 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7171 for (Section *section in sections_) {
7172 size_t count([section row]);
7176 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7177 [section setCount:count];
7178 [filtered_ addObject:section];
7181 [self updateNavigationItem];
7186 - (void) editButtonClicked {
7187 [self setEditing:(!editing_)];
7193 /* Changes Controller {{{ */
7194 @interface ChangesController : CYViewController <
7195 UITableViewDataSource,
7198 _transient Database *database_;
7200 CFMutableArrayRef packages_;
7201 NSMutableArray *sections_;
7204 BOOL hasSentFirstLoad_;
7207 - (id) initWithDatabase:(Database *)database;
7211 @implementation ChangesController
7214 [self releaseSubviews];
7215 CFRelease(packages_);
7216 [sections_ release];
7221 - (NSURL *) navigationURL {
7222 return [NSURL URLWithString:@"cydia://changes"];
7225 - (void) viewWillAppear:(BOOL)animated {
7226 // Loads after it appears, so don't load beforehand.
7228 [super viewWillAppear:animated];
7231 - (void) viewDidAppear:(BOOL)animated {
7232 [super viewDidAppear:animated];
7234 if (!hasSentFirstLoad_) {
7235 hasSentFirstLoad_ = YES;
7236 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7238 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7242 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7243 NSInteger count([sections_ count]);
7244 return count == 0 ? 1 : count;
7247 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7248 if ([sections_ count] == 0)
7250 return [[sections_ objectAtIndex:section] name];
7253 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7254 if ([sections_ count] == 0)
7256 return [[sections_ objectAtIndex:section] count];
7259 - (Package *) packageAtIndex:(NSUInteger)index {
7260 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7263 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7264 @synchronized (database_) {
7265 if ([database_ era] != era_)
7268 NSUInteger sectionIndex([path section]);
7269 if (sectionIndex >= [sections_ count])
7271 Section *section([sections_ objectAtIndex:sectionIndex]);
7272 NSInteger row([path row]);
7273 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7276 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7277 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7279 cell = [[[PackageCell alloc] init] autorelease];
7280 [cell setPackage:[self packageAtIndexPath:path]];
7284 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7285 Package *package([self packageAtIndexPath:path]);
7286 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7287 [view setDelegate:delegate_];
7288 [[self navigationController] pushViewController:view animated:YES];
7292 - (void) refreshButtonClicked {
7293 [delegate_ beginUpdate];
7294 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7297 - (void) upgradeButtonClicked {
7298 [delegate_ distUpgrade];
7302 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7304 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7305 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7306 [list_ setRowHeight:73];
7307 [list_ setDataSource:self];
7308 [list_ setDelegate:self];
7309 [[self view] addSubview:list_];
7312 - (void) viewDidLoad {
7313 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7316 - (void) releaseSubviews {
7321 - (id) initWithDatabase:(Database *)database {
7322 if ((self = [super init]) != nil) {
7323 database_ = database;
7325 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7326 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7330 // this mostly works because reloadData (below) is @synchronized (database_)
7331 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7332 - (void) _reloadPackages:(NSArray *)packages {
7333 CFRelease(packages_);
7334 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7337 _profile(ChangesController$_reloadPackages$Filter)
7338 for (Package *package in packages)
7339 if ([package upgradableAndEssential:YES] || [package visible])
7340 CFArrayAppendValue(packages_, package);
7343 _profile(ChangesController$_reloadPackages$radixSort)
7344 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7349 - (void) reloadData {
7350 @synchronized (database_) {
7351 era_ = [database_ era];
7352 NSArray *packages = [database_ packages];
7354 [sections_ removeAllObjects];
7357 UIProgressHUD *hud([delegate_ addProgressHUD]);
7358 [hud setText:UCLocalize("LOADING")];
7359 //NSLog(@"HUD:%@::%@", delegate_, hud);
7360 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7361 [delegate_ removeProgressHUD:hud];
7363 [self _reloadPackages:packages];
7366 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7367 Section *ignored = nil;
7368 Section *section = nil;
7372 bool unseens = false;
7374 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7376 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7377 Package *package = [self packageAtIndex:offset];
7379 BOOL uae = [package upgradableAndEssential:YES];
7383 time_t seen([package seen]);
7385 if (section == nil || last != seen) {
7389 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7392 _profile(ChangesController$reloadData$Allocate)
7393 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7394 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7395 [sections_ addObject:section];
7399 [section addToCount];
7400 } else if ([package ignored]) {
7401 if (ignored == nil) {
7402 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7404 [ignored addToCount];
7407 [upgradable addToCount];
7412 CFRelease(formatter);
7415 Section *last = [sections_ lastObject];
7416 size_t count = [last count];
7417 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7418 [sections_ removeLastObject];
7421 if ([ignored count] != 0)
7422 [sections_ insertObject:ignored atIndex:0];
7424 [sections_ insertObject:upgradable atIndex:0];
7429 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7430 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7431 style:UIBarButtonItemStylePlain
7433 action:@selector(upgradeButtonClicked)
7436 if (![delegate_ updating])
7437 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7438 initWithTitle:UCLocalize("REFRESH")
7439 style:UIBarButtonItemStylePlain
7441 action:@selector(refreshButtonClicked)
7449 /* Search Controller {{{ */
7450 @interface SearchController : FilteredPackageListController <
7453 UISearchBar *search_;
7457 - (id) initWithDatabase:(Database *)database;
7458 - (void) setSearchTerm:(NSString *)term;
7459 - (void) reloadData;
7463 @implementation SearchController
7470 - (NSURL *) navigationURL {
7471 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7472 return [NSURL URLWithString:@"cydia://search"];
7474 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7477 - (void) setSearchTerm:(NSString *)searchTerm {
7478 [search_ setText:searchTerm];
7482 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7483 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7484 [search_ resignFirstResponder];
7488 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7489 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7493 - (id) initWithDatabase:(Database *)database {
7494 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7495 search_ = [[UISearchBar alloc] init];
7499 - (void) viewDidAppear:(BOOL)animated {
7500 [super viewDidAppear:animated];
7502 if (!searchloaded_) {
7503 searchloaded_ = YES;
7504 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7505 [search_ layoutSubviews];
7506 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7508 UITextField *textField;
7509 if ([search_ respondsToSelector:@selector(searchField)])
7510 textField = [search_ searchField];
7512 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7514 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7515 [search_ setDelegate:self];
7516 [textField setEnablesReturnKeyAutomatically:NO];
7517 [[self navigationItem] setTitleView:textField];
7521 - (void) reloadData {
7522 [self setObject:[search_ text]];
7527 - (void) didSelectPackage:(Package *)package {
7528 [search_ resignFirstResponder];
7529 [super didSelectPackage:package];
7534 /* Package Settings Controller {{{ */
7535 @interface PackageSettingsController : CYViewController <
7536 UITableViewDataSource,
7539 _transient Database *database_;
7542 UITableView *table_;
7543 UISwitch *subscribedSwitch_;
7544 UISwitch *ignoredSwitch_;
7545 UITableViewCell *subscribedCell_;
7546 UITableViewCell *ignoredCell_;
7549 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7553 @implementation PackageSettingsController
7556 [self releaseSubviews];
7563 - (NSURL *) navigationURL {
7564 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7567 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7568 if (package_ == nil)
7571 if ([package_ installed] == nil)
7577 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7578 if (package_ == nil)
7581 // both sections contain just one item right now.
7585 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7589 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7591 return UCLocalize("SHOW_ALL_CHANGES_EX");
7593 return UCLocalize("IGNORE_UPGRADES_EX");
7596 - (void) onSubscribed:(id)control {
7597 bool value([control isOn]);
7598 if (package_ == nil)
7600 if ([package_ setSubscribed:value])
7601 [delegate_ updateData];
7604 - (void) _updateIgnored {
7605 const char *package([name_ UTF8String]);
7606 bool on([ignoredSwitch_ isOn]);
7608 pid_t pid(ExecFork());
7610 FILE *dpkg(popen("dpkg --set-selections", "w"));
7611 fwrite(package, strlen(package), 1, dpkg);
7614 fwrite(" hold\n", 6, 1, dpkg);
7616 fwrite(" install\n", 9, 1, dpkg);
7626 int result(waitpid(pid, &status, 0));
7629 _assert(result == pid);
7635 - (void) onIgnored:(id)control {
7636 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7637 [invocation setTarget:self];
7638 [invocation setSelector:@selector(_updateIgnored)];
7640 [delegate_ reloadDataWithInvocation:invocation];
7643 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7644 if (package_ == nil)
7647 switch ([indexPath section]) {
7648 case 0: return subscribedCell_;
7649 case 1: return ignoredCell_;
7658 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7660 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7661 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7662 [table_ setDataSource:self];
7663 [table_ setDelegate:self];
7664 [[self view] addSubview:table_];
7666 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7667 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7668 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7670 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7671 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7672 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7674 subscribedCell_ = [[UITableViewCell alloc] init];
7675 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7676 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7677 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7679 ignoredCell_ = [[UITableViewCell alloc] init];
7680 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7681 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7682 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7685 - (void) viewDidLoad {
7686 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7689 - (void) releaseSubviews {
7690 [ignoredCell_ release];
7693 [subscribedCell_ release];
7694 subscribedCell_ = nil;
7699 [ignoredSwitch_ release];
7700 ignoredSwitch_ = nil;
7702 [subscribedSwitch_ release];
7703 subscribedSwitch_ = nil;
7706 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7707 if ((self = [super init]) != nil) {
7708 database_ = database;
7709 name_ = [package retain];
7713 - (void) reloadData {
7716 if (package_ != nil)
7717 [package_ autorelease];
7718 package_ = [database_ packageWithName:name_];
7720 if (package_ != nil) {
7721 package_ = [package_ retain];
7722 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7723 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7724 } // XXX: what now, G?
7726 [table_ reloadData];
7732 /* Installed Controller {{{ */
7733 @interface InstalledController : FilteredPackageListController {
7737 - (id) initWithDatabase:(Database *)database;
7739 - (void) updateRoleButton;
7740 - (void) queueStatusDidChange;
7744 @implementation InstalledController
7750 - (NSURL *) navigationURL {
7751 return [NSURL URLWithString:@"cydia://installed"];
7754 - (id) initWithDatabase:(Database *)database {
7755 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7756 [self updateRoleButton];
7757 [self queueStatusDidChange];
7762 - (void) queueButtonClicked {
7767 - (void) queueStatusDidChange {
7771 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7772 initWithTitle:UCLocalize("QUEUE")
7773 style:UIBarButtonItemStyleDone
7775 action:@selector(queueButtonClicked)
7778 [[self navigationItem] setLeftBarButtonItem:nil];
7784 - (void) updateRoleButton {
7785 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7786 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7787 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7788 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7790 action:@selector(roleButtonClicked)
7794 - (void) roleButtonClicked {
7795 [self setObject:[NSNumber numberWithBool:expert_]];
7799 [self updateRoleButton];
7805 /* Source Cell {{{ */
7806 @interface SourceCell : CYTableViewCell <
7814 - (void) setSource:(Source *)source;
7818 @implementation SourceCell
7820 - (void) clearSource {
7830 - (void) setSource:(Source *)source {
7834 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7836 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7837 icon_ = [icon_ retain];
7839 origin_ = [[source name] retain];
7840 label_ = [[source uri] retain];
7842 [content_ setNeedsDisplay];
7850 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7851 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7852 UIView *content([self contentView]);
7853 CGRect bounds([content bounds]);
7855 content_ = [[ContentView alloc] initWithFrame:bounds];
7856 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7857 [content_ setBackgroundColor:[UIColor whiteColor]];
7858 [content addSubview:content_];
7860 [content_ setDelegate:self];
7861 [content_ setOpaque:YES];
7865 - (NSString *) accessibilityLabel {
7869 - (void) drawContentRect:(CGRect)rect {
7870 bool highlighted(highlighted_);
7871 float width(rect.size.width);
7874 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7881 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7885 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7890 /* Source Controller {{{ */
7891 @interface SourceController : FilteredPackageListController {
7892 _transient Source *source_;
7896 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7900 @implementation SourceController
7902 - (NSURL *) navigationURL {
7903 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7906 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7907 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7909 key_ = [[source key] retain];
7913 - (void) reloadData {
7914 source_ = [database_ sourceWithKey:key_];
7916 key_ = [[source_ key] retain];
7917 [self setObject:source_];
7918 [[self navigationItem] setTitle:[source_ label]];
7925 /* Sources Controller {{{ */
7926 @interface SourcesController : CYViewController <
7927 UITableViewDataSource,
7930 _transient Database *database_;
7932 NSMutableArray *sources_;
7936 UIProgressHUD *hud_;
7939 //NSURLConnection *installer_;
7940 NSURLConnection *trivial_;
7941 NSURLConnection *trivial_bz2_;
7942 NSURLConnection *trivial_gz_;
7943 //NSURLConnection *automatic_;
7948 - (id) initWithDatabase:(Database *)database;
7949 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7953 @implementation SourcesController
7955 - (void) _releaseConnection:(NSURLConnection *)connection {
7956 if (connection != nil) {
7957 [connection cancel];
7958 //[connection setDelegate:nil];
7959 [connection release];
7964 [self releaseSubviews];
7970 //[self _releaseConnection:installer_];
7971 [self _releaseConnection:trivial_];
7972 [self _releaseConnection:trivial_gz_];
7973 [self _releaseConnection:trivial_bz2_];
7974 //[self _releaseConnection:automatic_];
7980 - (NSURL *) navigationURL {
7981 return [NSURL URLWithString:@"cydia://sources"];
7984 - (void) viewDidAppear:(BOOL)animated {
7985 [super viewDidAppear:animated];
7986 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7989 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7990 return offset_ == 0 ? 1 : 2;
7993 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7994 switch (section + (offset_ == 0 ? 1 : 0)) {
7995 case 0: return UCLocalize("ENTERED_BY_USER");
7996 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8002 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8003 int count = [sources_ count];
8005 case 0: return (offset_ == 0 ? count : offset_);
8006 case 1: return count - offset_;
8012 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8014 switch (indexPath.section) {
8015 case 0: idx = indexPath.row; break;
8016 case 1: idx = indexPath.row + offset_; break;
8020 return [sources_ objectAtIndex:idx];
8023 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8024 static NSString *cellIdentifier = @"SourceCell";
8026 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8027 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8028 [cell setSource:[self sourceAtIndexPath:indexPath]];
8029 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8034 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8035 Source *source = [self sourceAtIndexPath:indexPath];
8037 SourceController *controller = [[[SourceController alloc]
8038 initWithDatabase:database_
8042 [controller setDelegate:delegate_];
8044 [[self navigationController] pushViewController:controller animated:YES];
8047 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8048 Source *source = [self sourceAtIndexPath:indexPath];
8049 return [source record] != nil;
8052 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8053 Source *source = [self sourceAtIndexPath:indexPath];
8054 [Sources_ removeObjectForKey:[source key]];
8055 [delegate_ syncData];
8059 [delegate_ addTrivialSource:href_];
8060 [delegate_ syncData];
8063 - (NSString *) getWarning {
8064 NSString *href(href_);
8065 NSRange colon([href rangeOfString:@"://"]);
8066 if (colon.location != NSNotFound)
8067 href = [href substringFromIndex:(colon.location + 3)];
8068 href = [href stringByAddingPercentEscapes];
8069 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8070 href = [href stringByCachingURLWithCurrentCDN];
8072 NSURL *url([NSURL URLWithString:href]);
8074 NSStringEncoding encoding;
8075 NSError *error(nil);
8077 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8078 return [warning length] == 0 ? nil : warning;
8082 - (void) _endConnection:(NSURLConnection *)connection {
8083 // XXX: the memory management in this method is horribly awkward
8085 NSURLConnection **field = NULL;
8086 if (connection == trivial_)
8088 else if (connection == trivial_bz2_)
8089 field = &trivial_bz2_;
8090 else if (connection == trivial_gz_)
8091 field = &trivial_gz_;
8092 _assert(field != NULL);
8093 [connection release];
8098 trivial_bz2_ == nil &&
8104 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8107 UIAlertView *alert = [[[UIAlertView alloc]
8108 initWithTitle:UCLocalize("SOURCE_WARNING")
8111 cancelButtonTitle:UCLocalize("CANCEL")
8113 UCLocalize("ADD_ANYWAY"),
8117 [alert setContext:@"warning"];
8118 [alert setNumberOfRows:1];
8122 } else if (error_ != nil) {
8123 UIAlertView *alert = [[[UIAlertView alloc]
8124 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8125 message:[error_ localizedDescription]
8127 cancelButtonTitle:UCLocalize("OK")
8128 otherButtonTitles:nil
8131 [alert setContext:@"urlerror"];
8134 UIAlertView *alert = [[[UIAlertView alloc]
8135 initWithTitle:UCLocalize("NOT_REPOSITORY")
8136 message:UCLocalize("NOT_REPOSITORY_EX")
8138 cancelButtonTitle:UCLocalize("OK")
8139 otherButtonTitles:nil
8142 [alert setContext:@"trivial"];
8146 [delegate_ setStatusBarShowsProgress:NO];
8147 [delegate_ removeProgressHUD:hud_];
8157 if (error_ != nil) {
8164 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8165 switch ([response statusCode]) {
8171 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8172 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8174 error_ = [error retain];
8175 [self _endConnection:connection];
8178 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8179 [self _endConnection:connection];
8182 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8183 NSMutableURLRequest *request = [NSMutableURLRequest
8184 requestWithURL:[NSURL URLWithString:href]
8185 cachePolicy:NSURLRequestUseProtocolCachePolicy
8186 timeoutInterval:120.0
8189 [request setHTTPMethod:method];
8191 if (Machine_ != NULL)
8192 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8193 if (UniqueID_ != nil)
8194 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8196 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8198 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8201 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8202 NSString *context([alert context]);
8204 if ([context isEqualToString:@"source"]) {
8207 NSString *href = [[alert textField] text];
8209 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8211 if (![href hasSuffix:@"/"])
8212 href_ = [href stringByAppendingString:@"/"];
8215 href_ = [href_ retain];
8217 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8218 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8219 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8220 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8224 // XXX: this is stupid
8225 hud_ = [[delegate_ addProgressHUD] retain];
8226 [hud_ setText:UCLocalize("VERIFYING_URL")];
8235 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8236 } else if ([context isEqualToString:@"trivial"])
8237 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8238 else if ([context isEqualToString:@"urlerror"])
8239 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8240 else if ([context isEqualToString:@"warning"]) {
8255 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8260 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8262 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8263 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8264 [list_ setRowHeight:56];
8265 [list_ setDataSource:self];
8266 [list_ setDelegate:self];
8267 [[self view] addSubview:list_];
8270 - (void) viewDidLoad {
8271 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8272 [self updateButtonsForEditingStatus:NO animated:NO];
8275 - (void) releaseSubviews {
8280 - (id) initWithDatabase:(Database *)database {
8281 if ((self = [super init]) != nil) {
8282 database_ = database;
8283 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8287 - (void) reloadData {
8291 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8294 [sources_ removeAllObjects];
8295 [sources_ addObjectsFromArray:[database_ sources]];
8297 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8300 int count([sources_ count]);
8302 for (int i = 0; i != count; i++) {
8303 if ([[sources_ objectAtIndex:i] record] == nil)
8308 [list_ setEditing:NO];
8309 [self updateButtonsForEditingStatus:NO animated:NO];
8313 - (void) showAddSourcePrompt {
8314 UIAlertView *alert = [[[UIAlertView alloc]
8315 initWithTitle:UCLocalize("ENTER_APT_URL")
8318 cancelButtonTitle:UCLocalize("CANCEL")
8320 UCLocalize("ADD_SOURCE"),
8324 [alert setContext:@"source"];
8325 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8327 [alert setNumberOfRows:1];
8328 [alert addTextFieldWithValue:@"http://" label:@""];
8330 UITextInputTraits *traits = [[alert textField] textInputTraits];
8331 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8332 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8333 [traits setKeyboardType:UIKeyboardTypeURL];
8334 // XXX: UIReturnKeyDone
8335 [traits setReturnKeyType:UIReturnKeyNext];
8340 - (void) addButtonClicked {
8341 [self showAddSourcePrompt];
8344 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8345 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8346 initWithTitle:UCLocalize("ADD")
8347 style:UIBarButtonItemStylePlain
8349 action:@selector(addButtonClicked)
8350 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8352 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8353 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8354 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8356 action:@selector(editButtonClicked)
8357 ] autorelease] animated:animated];
8359 if (IsWildcat_ && !editing)
8360 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8361 initWithTitle:UCLocalize("SETTINGS")
8362 style:UIBarButtonItemStylePlain
8364 action:@selector(settingsButtonClicked)
8368 - (void) settingsButtonClicked {
8369 [delegate_ showSettings];
8372 - (void) editButtonClicked {
8373 [list_ setEditing:![list_ isEditing] animated:YES];
8375 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8381 /* Settings Controller {{{ */
8382 @interface SettingsController : CYViewController <
8383 UITableViewDataSource,
8386 _transient Database *database_;
8387 // XXX: ok, "roledelegate_"?...
8388 _transient id roledelegate_;
8389 UITableView *table_;
8390 UISegmentedControl *segment_;
8394 - (void) showDoneButton;
8395 - (void) resizeSegmentedControl;
8399 @implementation SettingsController
8402 [self releaseSubviews];
8408 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8410 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8411 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8412 [table_ setDelegate:self];
8413 [table_ setDataSource:self];
8414 [[self view] addSubview:table_];
8416 NSArray *items = [NSArray arrayWithObjects:
8418 UCLocalize("HACKER"),
8419 UCLocalize("DEVELOPER"),
8421 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8422 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8423 [container_ addSubview:segment_];
8426 - (void) viewDidLoad {
8427 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8430 if ([Role_ isEqualToString:@"User"]) index = 0;
8431 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8432 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8434 [segment_ setSelectedSegmentIndex:index];
8435 [self showDoneButton];
8438 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8439 [self resizeSegmentedControl];
8442 - (void) releaseSubviews {
8449 [container_ release];
8453 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8454 if ((self = [super init]) != nil) {
8455 database_ = database;
8456 roledelegate_ = delegate;
8460 - (void) resizeSegmentedControl {
8461 CGFloat width = [[self view] frame].size.width;
8462 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8465 - (void) viewWillAppear:(BOOL)animated {
8466 [super viewWillAppear:animated];
8468 [self resizeSegmentedControl];
8471 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8472 [self resizeSegmentedControl];
8475 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8476 [self resizeSegmentedControl];
8480 NSString *role(nil);
8482 switch ([segment_ selectedSegmentIndex]) {
8483 case 0: role = @"User"; break;
8484 case 1: role = @"Hacker"; break;
8485 case 2: role = @"Developer"; break;
8490 if (![role isEqualToString:Role_]) {
8491 bool rolling(Role_ == nil);
8494 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8498 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8502 [roledelegate_ loadData];
8504 [roledelegate_ updateData];
8508 - (void) segmentChanged:(UISegmentedControl *)control {
8509 [self showDoneButton];
8512 - (void) saveAndClose {
8515 [[self navigationItem] setRightBarButtonItem:nil];
8516 [[self navigationController] dismissModalViewControllerAnimated:YES];
8519 - (void) doneButtonClicked {
8520 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8521 [spinner startAnimating];
8522 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8523 [[self navigationItem] setRightBarButtonItem:spinItem];
8525 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8528 - (void) showDoneButton {
8529 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8530 initWithTitle:UCLocalize("DONE")
8531 style:UIBarButtonItemStyleDone
8533 action:@selector(doneButtonClicked)
8534 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8537 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8538 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8542 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8546 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8547 return nil; // This method is required by the protocol.
8550 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8552 return UCLocalize("ROLE_EX");
8554 return [NSString stringWithFormat:
8555 @"%@: %@\n%@: %@\n%@: %@",
8556 UCLocalize("USER"), UCLocalize("USER_EX"),
8557 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8558 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8563 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8564 return section == 3 ? 44.0f : 0;
8567 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8568 return section == 3 ? container_ : nil;
8571 - (void) reloadData {
8573 [table_ reloadData];
8578 /* Stash Controller {{{ */
8579 @interface StashController : CYViewController {
8580 UIActivityIndicatorView *spinner_;
8587 @implementation StashController
8590 [self releaseSubviews];
8596 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8597 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8599 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8600 CGRect spinrect = [spinner_ frame];
8601 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8602 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8603 [spinner_ setFrame:spinrect];
8604 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8605 [[self view] addSubview:spinner_];
8606 [spinner_ startAnimating];
8609 captrect.size.width = [[self view] frame].size.width;
8610 captrect.size.height = 40.0f;
8611 captrect.origin.x = 0;
8612 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8613 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8614 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8615 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8616 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8617 [caption_ setTextColor:[UIColor whiteColor]];
8618 [caption_ setBackgroundColor:[UIColor clearColor]];
8619 [caption_ setShadowColor:[UIColor blackColor]];
8620 [caption_ setTextAlignment:UITextAlignmentCenter];
8621 [[self view] addSubview:caption_];
8624 statusrect.size.width = [[self view] frame].size.width;
8625 statusrect.size.height = 30.0f;
8626 statusrect.origin.x = 0;
8627 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8628 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8629 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8630 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8631 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8632 [status_ setTextColor:[UIColor whiteColor]];
8633 [status_ setBackgroundColor:[UIColor clearColor]];
8634 [status_ setShadowColor:[UIColor blackColor]];
8635 [status_ setTextAlignment:UITextAlignmentCenter];
8636 [[self view] addSubview:status_];
8639 - (void) releaseSubviews {
8653 @interface Cydia : UIApplication <
8654 ConfirmationControllerDelegate,
8655 ProgressControllerDelegate,
8657 UINavigationControllerDelegate,
8658 UITabBarControllerDelegate
8660 // XXX: evaluate all fields for _transient
8663 CYTabBarController *tabbar_;
8665 NSMutableArray *essential_;
8666 NSMutableArray *broken_;
8668 Database *database_;
8675 StashController *stash_;
8684 @implementation Cydia
8686 - (void) beginUpdate {
8687 [tabbar_ beginUpdate];
8691 return [tabbar_ updating];
8695 if ([broken_ count] != 0) {
8696 int count = [broken_ count];
8698 UIAlertView *alert = [[[UIAlertView alloc]
8699 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8700 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8702 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8704 UCLocalize("TEMPORARY_IGNORE"),
8708 [alert setContext:@"fixhalf"];
8710 } else if (!Ignored_ && [essential_ count] != 0) {
8711 int count = [essential_ count];
8713 UIAlertView *alert = [[[UIAlertView alloc]
8714 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8715 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8717 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8719 UCLocalize("UPGRADE_ESSENTIAL"),
8720 UCLocalize("COMPLETE_UPGRADE"),
8724 [alert setContext:@"upgrade"];
8729 - (void) _saveConfig {
8735 NSString *error(nil);
8737 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8739 NSError *error(nil);
8740 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8741 NSLog(@"failure to save metadata data: %@", error);
8746 NSLog(@"failure to serialize metadata: %@", error);
8751 // Navigation controller for the queuing badge.
8752 - (CYNavigationController *) queueNavigationController {
8753 NSArray *controllers = [tabbar_ viewControllers];
8754 return [controllers objectAtIndex:3];
8757 - (void) _updateData {
8760 [tabbar_ reloadData];
8762 CYNavigationController *navigation = [self queueNavigationController];
8764 id queuedelegate = nil;
8765 if ([[navigation viewControllers] count] > 0)
8766 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8768 [queuedelegate queueStatusDidChange];
8769 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8772 - (void) _refreshIfPossible:(NSDate *)update {
8773 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8775 bool recently = false;
8776 if (update != nil) {
8777 NSTimeInterval interval([update timeIntervalSinceNow]);
8778 if (interval <= 0 && interval > -(15*60))
8782 // Don't automatic refresh if:
8783 // - We already refreshed recently.
8784 // - We already auto-refreshed this launch.
8785 // - Auto-refresh is disabled.
8786 if (recently || loaded_ || ManualRefresh) {
8787 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8789 // If we are cancelling, we need to make sure it knows it's already loaded.
8793 // We are going to load, so remember that.
8797 SCNetworkReachabilityFlags flags; {
8798 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8799 SCNetworkReachabilityGetFlags(reachability, &flags);
8800 CFRelease(reachability);
8803 // XXX: this elaborate mess is what Apple is using to determine this? :(
8804 // XXX: do we care if the user has to intervene? maybe that's ok?
8806 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8807 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8808 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8809 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8810 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8811 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8815 // If we can reach the server, auto-refresh!
8817 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8822 - (void) refreshIfPossible {
8823 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8826 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8827 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8828 [hud setText:UCLocalize("RELOADING_DATA")];
8830 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8833 [self removeProgressHUD:hud];
8837 [essential_ removeAllObjects];
8838 [broken_ removeAllObjects];
8840 NSArray *packages([database_ packages]);
8841 for (Package *package in packages) {
8843 [broken_ addObject:package];
8844 if ([package upgradableAndEssential:NO]) {
8845 if ([package essential])
8846 [essential_ addObject:package];
8851 NSLog(@"changes:#%u", changes);
8853 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8856 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8857 [changesItem setBadgeValue:badge];
8858 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8859 [self setApplicationIconBadgeNumber:changes];
8862 [changesItem setBadgeValue:nil];
8863 [changesItem setAnimatedBadge:NO];
8864 [self setApplicationIconBadgeNumber:0];
8869 [self refreshIfPossible];
8872 - (void) updateData {
8883 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8884 _assert(file != NULL);
8886 for (NSString *key in [Sources_ allKeys]) {
8887 NSDictionary *source([Sources_ objectForKey:key]);
8889 fprintf(file, "%s %s %s\n",
8890 [[source objectForKey:@"Type"] UTF8String],
8891 [[source objectForKey:@"URI"] UTF8String],
8892 [[source objectForKey:@"Distribution"] UTF8String]
8898 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8899 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8901 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8902 [tabbar_ presentModalViewController:navigation animated:YES];
8905 detachNewThreadSelector:@selector(update_)
8908 title:UCLocalize("UPDATING_SOURCES")
8912 - (void) addTrivialSource:(NSString *)href {
8913 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8916 @"./", @"Distribution",
8917 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8922 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8923 @synchronized (self) {
8924 [self _reloadDataWithInvocation:invocation];
8928 - (void) reloadData {
8929 [self reloadDataWithInvocation:nil];
8933 pkgProblemResolver *resolver = [database_ resolver];
8935 resolver->InstallProtect();
8936 if (!resolver->Resolve(true))
8941 // XXX: this is a really crappy way of doing this.
8942 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8943 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8944 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8945 if ([tabbar_ updating])
8946 [tabbar_ cancelUpdate];
8948 if (![database_ prepare])
8951 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8952 [page setDelegate:self];
8953 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8954 [confirm_ setDelegate:self];
8957 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8958 [tabbar_ presentModalViewController:confirm_ animated:YES];
8964 @synchronized (self) {
8969 - (void) clearPackage:(Package *)package {
8970 @synchronized (self) {
8977 - (void) installPackages:(NSArray *)packages {
8978 @synchronized (self) {
8979 for (Package *package in packages)
8986 - (void) installPackage:(Package *)package {
8987 @synchronized (self) {
8994 - (void) removePackage:(Package *)package {
8995 @synchronized (self) {
9002 - (void) distUpgrade {
9003 @synchronized (self) {
9004 if (![database_ upgrade])
9011 @synchronized (self) {
9012 [self _reloadDataWithInvocation:nil];
9016 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9019 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
9021 if (navigation != nil) {
9022 [navigation pushViewController:progress animated:YES];
9024 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
9026 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9027 [tabbar_ presentModalViewController:navigation animated:YES];
9031 detachNewThreadSelector:@selector(perform)
9034 title:UCLocalize("RUNNING")
9040 - (void) progressControllerIsComplete:(ProgressController *)progress {
9045 - (void) showSettings {
9046 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9047 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9049 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9050 [tabbar_ presentModalViewController:nav animated:YES];
9053 - (void) retainNetworkActivityIndicator {
9054 if (activity_++ == 0)
9055 [self setNetworkActivityIndicatorVisible:YES];
9058 - (void) releaseNetworkActivityIndicator {
9059 if (--activity_ == 0)
9060 [self setNetworkActivityIndicatorVisible:NO];
9063 - (void) cancelAndClear:(bool)clear {
9064 @synchronized (self) {
9076 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9077 NSString *context([alert context]);
9079 if ([context isEqualToString:@"fixhalf"]) {
9080 if (button == [alert cancelButtonIndex]) {
9081 @synchronized (self) {
9082 for (Package *broken in broken_) {
9085 NSString *id = [broken id];
9086 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9087 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9088 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9089 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9095 } else if (button == [alert firstOtherButtonIndex]) {
9096 [broken_ removeAllObjects];
9100 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9101 } else if ([context isEqualToString:@"upgrade"]) {
9102 if (button == [alert firstOtherButtonIndex]) {
9103 @synchronized (self) {
9104 for (Package *essential in essential_)
9105 [essential install];
9110 } else if (button == [alert firstOtherButtonIndex] + 1) {
9112 } else if (button == [alert cancelButtonIndex]) {
9116 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9120 - (void) system:(NSString *)command { _pooled
9122 system([command UTF8String]);
9126 - (void) applicationWillSuspend {
9128 [super applicationWillSuspend];
9131 - (BOOL) isSafeToSuspend {
9132 // Use external process status API internally.
9133 // This is probably a really bad idea.
9134 // XXX: what is the point of this? does this solve anything at all?
9135 uint64_t status = 0;
9137 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9138 notify_get_state(notify_token, &status);
9139 notify_cancel(notify_token);
9142 return locked_ == 0 && status == 0;
9145 - (void) applicationSuspend:(__GSEvent *)event {
9146 if ([self isSafeToSuspend])
9147 [super applicationSuspend:event];
9150 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9151 if ([self isSafeToSuspend])
9152 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9155 - (void) _setSuspended:(BOOL)value {
9156 if ([self isSafeToSuspend])
9157 [super _setSuspended:value];
9160 - (UIProgressHUD *) addProgressHUD {
9161 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9162 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9164 [window_ setUserInteractionEnabled:NO];
9167 UIViewController *target = tabbar_;
9168 while ([target modalViewController] != nil) target = [target modalViewController];
9169 [[target view] addSubview:hud];
9175 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9177 [hud removeFromSuperview];
9178 [window_ setUserInteractionEnabled:YES];
9182 - (CYViewController *) pageForPackage:(NSString *)name {
9183 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9186 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9187 NSString *scheme([[url scheme] lowercaseString]);
9188 if ([[url absoluteString] length] <= [scheme length] + 3)
9190 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9191 NSArray *components([path pathComponents]);
9193 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9194 return [self pageForPackage:[components objectAtIndex:1]];
9196 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9199 NSString *base([components objectAtIndex:0]);
9201 CYViewController *controller = nil;
9203 if ([base isEqualToString:@"url"]) {
9204 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9205 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9206 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9207 } else if (!external && [components count] == 1) {
9208 if ([base isEqualToString:@"manage"]) {
9209 controller = [[[ManageController alloc] init] autorelease];
9212 if ([base isEqualToString:@"sources"]) {
9213 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9216 if ([base isEqualToString:@"home"]) {
9217 controller = [[[HomeController alloc] init] autorelease];
9220 if ([base isEqualToString:@"sections"]) {
9221 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9224 if ([base isEqualToString:@"search"]) {
9225 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9228 if ([base isEqualToString:@"changes"]) {
9229 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9232 if ([base isEqualToString:@"installed"]) {
9233 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9235 } else if ([components count] == 2) {
9236 NSString *argument = [components objectAtIndex:1];
9238 if ([base isEqualToString:@"package"]) {
9239 controller = [self pageForPackage:argument];
9242 if (!external && [base isEqualToString:@"search"]) {
9243 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9244 [(SearchController *)controller setSearchTerm:argument];
9247 if (!external && [base isEqualToString:@"sections"]) {
9248 if ([argument isEqualToString:@"all"])
9250 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9253 if (!external && [base isEqualToString:@"sources"]) {
9254 if ([argument isEqualToString:@"add"]) {
9255 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9256 [(SourcesController *)controller showAddSourcePrompt];
9258 Source *source = [database_ sourceWithKey:argument];
9259 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9263 if (!external && [base isEqualToString:@"launch"]) {
9264 [self launchApplicationWithIdentifier:argument suspended:NO];
9267 } else if (!external && [components count] == 3) {
9268 NSString *arg1 = [components objectAtIndex:1];
9269 NSString *arg2 = [components objectAtIndex:2];
9271 if ([base isEqualToString:@"package"]) {
9272 if ([arg2 isEqualToString:@"settings"]) {
9273 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9274 } else if ([arg2 isEqualToString:@"files"]) {
9275 if (Package *package = [database_ packageWithName:arg1]) {
9276 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9277 [(FileTable *)controller setPackage:package];
9283 [controller setDelegate:self];
9287 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9288 CYViewController *page([self pageForURL:url forExternal:external]);
9291 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9292 [nav setViewControllers:[NSArray arrayWithObject:page]];
9293 [tabbar_ setUnselectedViewController:nav];
9299 - (void) applicationOpenURL:(NSURL *)url {
9300 [super applicationOpenURL:url];
9302 if (!loaded_) starturl_ = [url retain];
9303 else [self openCydiaURL:url forExternal:YES];
9306 - (void) applicationWillResignActive:(UIApplication *)application {
9307 // Stop refreshing if you get a phone call or lock the device.
9308 if ([tabbar_ updating])
9309 [tabbar_ cancelUpdate];
9311 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9312 [super applicationWillResignActive:application];
9315 - (void) applicationWillTerminate:(UIApplication *)application {
9317 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9318 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9319 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9324 - (void) addStashController {
9326 stash_ = [[StashController alloc] init];
9327 [window_ addSubview:[stash_ view]];
9330 - (void) removeStashController {
9331 [[stash_ view] removeFromSuperview];
9337 [self setIdleTimerDisabled:YES];
9339 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9340 [self setStatusBarShowsProgress:YES];
9341 UpdateExternalStatus(1);
9343 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9345 UpdateExternalStatus(0);
9346 [self setStatusBarShowsProgress:NO];
9348 [self removeStashController];
9350 if (ExecFork() == 0) {
9351 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9352 perror("launchctl stop");
9356 - (void) setupViewControllers {
9357 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9359 NSMutableArray *items([NSMutableArray arrayWithObjects:
9360 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9361 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9362 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9363 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9367 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9368 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9370 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9373 NSMutableArray *controllers([NSMutableArray array]);
9374 for (UITabBarItem *item in items) {
9375 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9376 [controller setTabBarItem:item];
9377 [controllers addObject:controller];
9379 [tabbar_ setViewControllers:controllers];
9381 [tabbar_ setUpdateDelegate:self];
9384 - (CYEmulatedLoadingController *) showEmulatedLoadingControllerInView:(UIView *)view {
9385 static CYEmulatedLoadingController *fake = nil;
9389 fake = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9390 [view addSubview:[fake view]];
9392 [[fake view] removeFromSuperview];
9400 - (void) applicationDidFinishLaunching:(id)unused {
9404 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9405 [self setApplicationSupportsShakeToEdit:NO];
9407 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9408 initWithMemoryCapacity:524288
9409 diskCapacity:10485760
9410 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9413 [CYBrowserController _initialize];
9415 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9417 Font12_ = [[UIFont systemFontOfSize:12] retain];
9418 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9419 Font14_ = [[UIFont systemFontOfSize:14] retain];
9420 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9421 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9423 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9424 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9426 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9427 [window_ orderFront:self];
9428 [window_ makeKey:self];
9429 [window_ setHidden:NO];
9432 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9433 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9434 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9435 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9436 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9437 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9438 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9439 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9440 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9443 [self addStashController];
9444 // XXX: this would be much cleaner as a yieldToSelector:
9445 // that way the removeStashController could happen right here inline
9446 // we also could no longer require the useless stash_ field anymore
9447 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9451 database_ = [Database sharedInstance];
9453 [window_ setUserInteractionEnabled:NO];
9454 [self setupViewControllers];
9455 [self showEmulatedLoadingControllerInView:window_];
9457 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9464 [window_ setUserInteractionEnabled:YES];
9466 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9467 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9469 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9470 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9474 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9475 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9476 [window_ setUserInteractionEnabled:NO];
9482 [window_ addSubview:[tabbar_ view]];
9483 [self showEmulatedLoadingControllerInView:nil];
9484 [window_ setUserInteractionEnabled:YES];
9486 int selectedIndex = 0;
9487 NSMutableArray *items = nil;
9489 bool recently = false;
9490 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9491 if (closed != nil) {
9492 NSTimeInterval interval([closed timeIntervalSinceNow]);
9493 // XXX: Is 15 minutes the optimal time here?
9494 if (interval <= 0 && interval > -(15*60))
9498 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9499 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9502 for (NSArray *entry in items)
9503 if ([entry count] <= 0)
9506 if (!recently || !items || !enough) {
9508 items = [NSMutableArray array];
9509 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9510 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9511 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9513 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9515 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9516 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9518 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9521 [tabbar_ setSelectedIndex:selectedIndex];
9522 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9523 NSArray *stack = [items objectAtIndex:tab];
9524 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9525 NSMutableArray *current = [NSMutableArray array];
9527 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9528 NSString *addr = [stack objectAtIndex:nav];
9529 NSURL *url = [NSURL URLWithString:addr];
9530 CYViewController *page = [self pageForURL:url forExternal:NO];
9532 [current addObject:page];
9535 [navigation setViewControllers:current];
9538 // (Try to) show the startup URL.
9539 if (starturl_ != nil) {
9540 [self openCydiaURL:starturl_ forExternal:NO];
9541 [starturl_ release];
9546 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9547 if (item != nil && IsWildcat_) {
9548 [sheet showFromBarButtonItem:item animated:YES];
9550 [sheet showInView:window_];
9557 id Alloc_(id self, SEL selector) {
9558 id object = alloc_(self, selector);
9559 lprintf("[%s]A-%p\n", self->isa->name, object);
9564 id Dealloc_(id self, SEL selector) {
9565 id object = dealloc_(self, selector);
9566 lprintf("[%s]D-%p\n", self->isa->name, object);
9570 Class $WebDefaultUIKitDelegate;
9572 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9573 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9574 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9575 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9578 static NSNumber *shouldPlayKeyboardSounds;
9582 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9584 case 1104: // Keyboard Button Clicked
9585 case 1105: // Keyboard Delete Repeated
9586 if (shouldPlayKeyboardSounds == nil) {
9587 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9588 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9591 if (![shouldPlayKeyboardSounds boolValue])
9595 _UIHardware$_playSystemSound$(self, _cmd, sound);
9599 Class $UIApplication;
9601 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9602 static BOOL initialized = NO;
9603 static BOOL started = NO;
9605 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9606 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9608 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9609 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9610 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9611 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9613 if (initialized && !enabled) {
9615 [bundle performSelector:@selector(_accessibilityStopServer)];
9616 } else if (enabled) {
9620 [bundle performSelector:@selector(_accessibilityStartServer)];
9626 int main(int argc, char *argv[]) { _pooled
9629 UpdateExternalStatus(0);
9631 if (Class $UIDevice = objc_getClass("UIDevice")) {
9632 UIDevice *device([$UIDevice currentDevice]);
9633 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9637 UIScreen *screen([UIScreen mainScreen]);
9638 if ([screen respondsToSelector:@selector(scale)])
9639 ScreenScale_ = [screen scale];
9643 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9644 if (ScreenScale_ > 1)
9645 [parts addObject:@"@2x"];
9646 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9647 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9649 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9651 /* Library Hacks {{{ */
9652 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9654 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9655 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9656 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9657 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9658 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9661 $UIHardware = objc_getClass("UIHardware");
9662 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9663 if (UIHardware$_playSystemSound$ != NULL) {
9664 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9665 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9668 $UIApplication = objc_getClass("UIApplication");
9669 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9670 if (UIApplication$_updateApplicationAccessibility != NULL) {
9671 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9672 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9675 /* Set Locale {{{ */
9676 Locale_ = CFLocaleCopyCurrent();
9677 Languages_ = [NSLocale preferredLanguages];
9678 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9679 //NSLog(@"%@", [Languages_ description]);
9682 if (Languages_ == nil || [Languages_ count] == 0)
9683 // XXX: consider just setting to C and then falling through?
9686 lang = [[Languages_ objectAtIndex:0] UTF8String];
9687 setenv("LANG", lang, true);
9690 //std::setlocale(LC_ALL, lang);
9691 NSLog(@"Setting Language: %s", lang);
9694 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9696 /* Parse Arguments {{{ */
9697 bool substrate(false);
9703 for (int argi(1); argi != argc; ++argi)
9704 if (strcmp(argv[argi], "--") == 0) {
9706 argv[argi] = argv[0];
9712 for (int argi(1); argi != arge; ++argi)
9713 if (strcmp(args[argi], "--substrate") == 0)
9716 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9720 App_ = [[NSBundle mainBundle] bundlePath];
9721 Home_ = NSHomeDirectory();
9727 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9728 alloc_ = alloc->method_imp;
9729 alloc->method_imp = (IMP) &Alloc_;*/
9731 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9732 dealloc_ = dealloc->method_imp;
9733 dealloc->method_imp = (IMP) &Dealloc_;*/
9735 /* System Information {{{ */
9739 size = sizeof(maxproc);
9740 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9741 perror("sysctlbyname(\"kern.maxproc\", ?)");
9742 else if (maxproc < 64) {
9744 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9745 perror("sysctlbyname(\"kern.maxproc\", #)");
9748 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9749 char *osversion = new char[size];
9750 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9751 perror("sysctlbyname(\"kern.osversion\", ?)");
9753 System_ = [NSString stringWithUTF8String:osversion];
9755 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9756 char *machine = new char[size];
9757 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9758 perror("sysctlbyname(\"hw.machine\", ?)");
9762 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9763 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9764 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9765 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9769 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9770 NSData *data((NSData *) ecid);
9771 size_t length([data length]);
9772 uint8_t bytes[length];
9773 [data getBytes:bytes];
9774 char string[length * 2 + 1];
9775 for (size_t i(0); i != length; ++i)
9776 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9777 ChipID_ = [NSString stringWithUTF8String:string];
9781 IOObjectRelease(service);
9785 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9787 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9788 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9789 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9791 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9792 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9793 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9795 if (mcc != NULL && mnc != NULL)
9796 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9803 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9804 Build_ = [system objectForKey:@"ProductBuildVersion"];
9805 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9806 Product_ = [info objectForKey:@"SafariProductVersion"];
9807 Safari_ = [info objectForKey:@"CFBundleVersion"];
9810 /* Load Database {{{ */
9812 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9814 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9816 if (Metadata_ == NULL)
9817 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9819 Settings_ = [Metadata_ objectForKey:@"Settings"];
9821 Packages_ = [Metadata_ objectForKey:@"Packages"];
9822 Sections_ = [Metadata_ objectForKey:@"Sections"];
9823 Sources_ = [Metadata_ objectForKey:@"Sources"];
9825 Token_ = [Metadata_ objectForKey:@"Token"];
9828 if (Settings_ != nil)
9829 Role_ = [Settings_ objectForKey:@"Role"];
9831 if (Sections_ == nil) {
9832 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9833 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9836 if (Sources_ == nil) {
9837 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9838 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9843 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9846 if (Packages_ != nil) {
9848 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9852 [Metadata_ removeObjectForKey:@"Packages"];
9858 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9860 #define MobileSubstrate_(name) \
9861 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) \
9862 dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL);
9864 MobileSubstrate_(Activator)
9865 MobileSubstrate_(libstatusbar)
9866 MobileSubstrate_(SimulatedKeyEvents)
9867 MobileSubstrate_(WinterBoard)
9869 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9870 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9872 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9874 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9875 unlink("/tmp/.cydia.fw");
9877 } else if (access("/User", F_OK) != 0 || version < 2) {
9880 system("/usr/libexec/cydia/firmware.sh");
9884 _assert([[NSFileManager defaultManager]
9885 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9886 withIntermediateDirectories:YES
9891 if (access("/tmp/cydia.chk", F_OK) == 0) {
9892 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9893 _assert(errno == ENOENT);
9894 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9895 _assert(errno == ENOENT);
9898 /* APT Initialization {{{ */
9899 _assert(pkgInitConfig(*_config));
9900 _assert(pkgInitSystem(*_config, _system));
9903 _config->Set("APT::Acquire::Translation", lang);
9905 // XXX: this timeout might be important :(
9906 //_config->Set("Acquire::http::Timeout", 15);
9908 _config->Set("Acquire::http::MaxParallel", 3);
9910 /* Color Choices {{{ */
9911 space_ = CGColorSpaceCreateDeviceRGB();
9913 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9914 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9915 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9916 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9917 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9918 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9919 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9920 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9921 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9923 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9924 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9926 /* UIKit Configuration {{{ */
9927 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9928 if ($GSFontSetUseLegacyFontMetrics != NULL)
9929 $GSFontSetUseLegacyFontMetrics(YES);
9931 // XXX: I have a feeling this was important
9932 //UIKeyboardDisableAutomaticAppearance();
9935 Colon_ = UCLocalize("COLON_DELIMITED");
9936 Elision_ = UCLocalize("ELISION");
9937 Error_ = UCLocalize("ERROR");
9938 Warning_ = UCLocalize("WARNING");
9941 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9943 CGColorSpaceRelease(space_);