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;
312 @implementation CYAlertView
314 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
315 if ((self = [super init])) {
316 [self setTitle:title];
317 [self setDelegate:self];
318 for (NSString *button in buttons) [self addButtonWithTitle:button];
319 [self setCancelButtonIndex:index];
323 - (void) _updateFrameForDisplay {
324 [super _updateFrameForDisplay];
325 if ([self cancelButtonIndex] == -1) {
326 NSArray *buttons = [self buttons];
327 if ([buttons count]) {
328 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
329 for (UIThreePartButton *button in buttons)
330 [button setBackground:background forState:0];
335 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
336 button_ = buttonIndex + 1;
340 [self dismissWithClickedButtonIndex:-1 animated:YES];
343 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
344 [self setRunsModal:YES];
353 /* NSForcedOrderingSearch doesn't work on the iPhone */
354 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
355 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
356 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
358 #define lprintf(args...) fprintf(stderr, args)
361 #define TraceLogging (1 && !ForRelease)
362 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
363 #define ProfileTimes (0 && !ForRelease)
364 #define ForSaurik (0 && !ForRelease)
365 #define LogBrowser (0 && !ForRelease)
366 #define TrackResize (0 && !ForRelease)
367 #define ManualRefresh (1 && !ForRelease)
368 #define ShowInternals (0 && !ForRelease)
369 #define AlwaysReload (0 && !ForRelease)
370 #define TryIndexedCollation (0 && !ForRelease)
374 #define _trace(args...)
379 #define _profile(name) {
382 #define PrintTimes() do {} while (false)
386 typedef uint32_t (*SKRadixFunction)(id, void *);
388 @interface NSMutableArray (Radix)
389 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
397 @implementation NSMutableArray (Radix)
399 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
400 size_t count([self count]);
401 struct RadixItem_ *swap(new RadixItem_[count * 2]);
403 for (size_t i(0); i != count; ++i) {
404 RadixItem_ &item(swap[i]);
407 id object([self objectAtIndex:i]);
408 item.key = function(object, argument);
411 struct RadixItem_ *lhs(swap), *rhs(swap + count);
413 static const size_t width = 32;
414 static const size_t bits = 11;
415 static const size_t slots = 1 << bits;
416 static const size_t passes = (width + (bits - 1)) / bits;
418 size_t *hist(new size_t[slots]);
420 for (size_t pass(0); pass != passes; ++pass) {
421 memset(hist, 0, sizeof(size_t) * slots);
423 for (size_t i(0); i != count; ++i) {
424 uint32_t key(lhs[i].key);
426 key &= _not(uint32_t) >> width - bits;
431 for (size_t i(0); i != slots; ++i) {
432 size_t local(offset);
437 for (size_t i(0); i != count; ++i) {
438 uint32_t key(lhs[i].key);
440 key &= _not(uint32_t) >> width - bits;
441 rhs[hist[key]++] = lhs[i];
444 RadixItem_ *tmp(lhs);
451 const void **values(new const void *[count]);
452 for (size_t i(0); i != count; ++i)
453 values[i] = [self objectAtIndex:lhs[i].index];
454 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
462 /* Insertion Sort {{{ */
464 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
465 const char *ptr = (const char *)list;
467 CFIndex half = count / 2;
468 const char *probe = ptr + elementSize * half;
469 CFComparisonResult cr = comparator(element, probe, context);
470 if (0 == cr) return (probe - (const char *)list) / elementSize;
471 ptr = (cr < 0) ? ptr : probe + elementSize;
472 count = (cr < 0) ? half : (half + (count & 1) - 1);
474 return (ptr - (const char *)list) / elementSize;
477 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
478 const char *ptr = (const char *)list;
480 CFIndex half = count / 2;
481 const char *probe = ptr + elementSize * half;
482 CFComparisonResult cr = comparator(element, probe, context);
483 if (0 == cr) return (probe - (const char *)list) / elementSize;
484 ptr = (cr < 0) ? ptr : probe + elementSize;
485 count = (cr < 0) ? half : (half + (count & 1) - 1);
487 return (ptr - (const char *)list) / elementSize;
490 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
491 if (range.length == 0)
493 const void **values(new const void *[range.length]);
494 CFArrayGetValues(array, range, values);
496 #if HistogramInsertionSort > 0
497 uint32_t total(0), *offsets(new uint32_t[range.length]);
500 for (CFIndex index(1); index != range.length; ++index) {
501 const void *value(values[index]);
502 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
503 CFIndex correct(index);
504 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
505 #if HistogramInsertionSort > 1
506 NSLog(@"%@ < %@", value, values[correct - 1]);
511 if (correct != index) {
512 size_t offset(index - correct);
513 #if HistogramInsertionSort
517 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
519 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
520 values[correct] = value;
524 CFArrayReplaceValues(array, range, values, range.length);
527 #if HistogramInsertionSort > 0
528 for (CFIndex index(0); index != range.length; ++index)
529 if (offsets[index] != 0)
530 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
531 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
538 /* Apple Bug Fixes {{{ */
539 @implementation UIWebDocumentView (Cydia)
541 - (void) _setScrollerOffset:(CGPoint)offset {
542 UIScroller *scroller([self _scroller]);
544 CGSize size([scroller contentSize]);
545 CGSize bounds([scroller bounds].size);
548 max.x = size.width - bounds.width;
549 max.y = size.height - bounds.height;
557 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
558 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
560 [scroller setOffset:offset];
566 @implementation WebScriptObject (NSFastEnumeration)
568 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
569 size_t length([self count] - state->state);
572 else if (length > count)
574 for (size_t i(0); i != length; ++i)
575 objects[i] = [self objectAtIndex:state->state++];
576 state->itemsPtr = objects;
577 state->mutationsPtr = (unsigned long *) self;
583 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
584 size_t length([self length] - state->state);
587 else if (length > count)
589 for (size_t i(0); i != length; ++i)
590 objects[i] = [self item:state->state++];
591 state->itemsPtr = objects;
592 state->mutationsPtr = (unsigned long *) self;
596 /* Cydia NSString Additions {{{ */
597 @interface NSString (Cydia)
598 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
599 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
600 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
601 - (NSComparisonResult) compareByPath:(NSString *)other;
602 - (NSString *) stringByCachingURLWithCurrentCDN;
603 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
606 @implementation NSString (Cydia)
608 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
609 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
612 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
613 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
614 memcpy(data, bytes, length);
615 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
618 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
619 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
622 - (NSComparisonResult) compareByPath:(NSString *)other {
623 NSString *prefix = [self commonPrefixWithString:other options:0];
624 size_t length = [prefix length];
626 NSRange lrange = NSMakeRange(length, [self length] - length);
627 NSRange rrange = NSMakeRange(length, [other length] - length);
629 lrange = [self rangeOfString:@"/" options:0 range:lrange];
630 rrange = [other rangeOfString:@"/" options:0 range:rrange];
632 NSComparisonResult value;
634 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
635 value = NSOrderedSame;
636 else if (lrange.location == NSNotFound)
637 value = NSOrderedAscending;
638 else if (rrange.location == NSNotFound)
639 value = NSOrderedDescending;
641 value = NSOrderedSame;
643 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
644 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
645 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
646 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
648 NSComparisonResult result = [lpath compare:rpath];
649 return result == NSOrderedSame ? value : result;
652 - (NSString *) stringByCachingURLWithCurrentCDN {
654 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
655 withString:@"://cache.cydia.saurik.com/"
659 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
660 return [(id)CFURLCreateStringByAddingPercentEscapes(
665 kCFStringEncodingUTF8
672 /* C++ NSString Wrapper Cache {{{ */
673 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
674 return size == 0 ? NULL :
675 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
676 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
679 static _finline CFStringRef CYStringCreate(const char *data) {
680 return CYStringCreate(data, strlen(data));
689 _finline void clear_() {
690 if (cache_ != NULL) {
697 _finline bool empty() const {
701 _finline size_t size() const {
705 _finline char *data() const {
709 _finline void clear() {
714 _finline CYString() :
721 _finline ~CYString() {
725 void operator =(const CYString &rhs) {
729 if (rhs.cache_ == nil)
732 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
735 void copy(apr_pool_t *pool) {
736 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
737 memcpy(temp, data_, size_);
742 void set(apr_pool_t *pool, const char *data, size_t size) {
748 data_ = const_cast<char *>(data);
756 _finline void set(apr_pool_t *pool, const char *data) {
757 set(pool, data, data == NULL ? 0 : strlen(data));
760 _finline void set(apr_pool_t *pool, const std::string &rhs) {
761 set(pool, rhs.data(), rhs.size());
764 bool operator ==(const CYString &rhs) const {
765 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
768 _finline operator CFStringRef() {
770 cache_ = CYStringCreate(data_, size_);
774 _finline operator id() {
775 return (NSString *) static_cast<CFStringRef>(*this);
778 _finline operator const char *() {
779 return reinterpret_cast<const char *>(data_);
783 /* C++ NSString Algorithm Adapters {{{ */
785 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
788 struct NSStringMapHash :
789 std::unary_function<NSString *, size_t>
791 _finline size_t operator ()(NSString *value) const {
792 return CFStringHashNSString((CFStringRef) value);
796 struct NSStringMapLess :
797 std::binary_function<NSString *, NSString *, bool>
799 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
800 return [lhs compare:rhs] == NSOrderedAscending;
804 struct NSStringMapEqual :
805 std::binary_function<NSString *, NSString *, bool>
807 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
808 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
809 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
810 //[lhs isEqualToString:rhs];
815 /* Perl-Compatible RegEx {{{ */
825 Pcre(const char *regex) :
830 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
833 lprintf("%d:%s\n", offset, error);
837 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
838 matches_ = new int[(capture_ + 1) * 3];
846 NSString *operator [](size_t match) {
847 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
850 bool operator ()(NSString *data) {
851 // XXX: length is for characters, not for bytes
852 return operator ()([data UTF8String], [data length]);
855 bool operator ()(const char *data, size_t size) {
857 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
861 /* Mime Addresses {{{ */
862 @interface Address : NSObject {
868 - (NSString *) address;
870 - (void) setAddress:(NSString *)address;
872 + (Address *) addressWithString:(NSString *)string;
873 - (Address *) initWithString:(NSString *)string;
876 @implementation Address
885 - (NSString *) name {
889 - (NSString *) address {
893 - (void) setAddress:(NSString *)address {
895 [address_ autorelease];
899 address_ = [address retain];
902 + (Address *) addressWithString:(NSString *)string {
903 return [[[Address alloc] initWithString:string] autorelease];
906 + (NSArray *) _attributeKeys {
907 return [NSArray arrayWithObjects:@"address", @"name", nil];
910 - (NSArray *) attributeKeys {
911 return [[self class] _attributeKeys];
914 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
915 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
918 - (Address *) initWithString:(NSString *)string {
919 if ((self = [super init]) != nil) {
920 const char *data = [string UTF8String];
921 size_t size = [string length];
923 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
925 if (address_r(data, size)) {
926 name_ = [address_r[1] retain];
927 address_ = [address_r[2] retain];
929 name_ = [string retain];
937 /* CoreGraphics Primitives {{{ */
942 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
943 CGFloat color[] = {red, green, blue, alpha};
944 return CGColorCreate(space, color);
953 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
954 color_(Create_(space, red, green, blue, alpha))
956 Set(space, red, green, blue, alpha);
961 CGColorRelease(color_);
968 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
970 color_ = Create_(space, red, green, blue, alpha);
973 operator CGColorRef() {
979 /* Random Global Variables {{{ */
980 static const int PulseInterval_ = 50000;
982 static const NSString *UI_;
985 static NSArray *Finishes_;
987 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
988 #define NotifyConfig_ "/etc/notify.conf"
990 static bool Queuing_;
992 static CYColor Blue_;
993 static CYColor Blueish_;
994 static CYColor Black_;
996 static CYColor White_;
997 static CYColor Gray_;
998 static CYColor Green_;
999 static CYColor Purple_;
1000 static CYColor Purplish_;
1002 static UIColor *InstallingColor_;
1003 static UIColor *RemovingColor_;
1005 static NSString *App_;
1006 static NSString *Home_;
1008 static BOOL Advanced_;
1009 static BOOL Ignored_;
1011 static UIFont *Font12_;
1012 static UIFont *Font12Bold_;
1013 static UIFont *Font14_;
1014 static UIFont *Font18Bold_;
1015 static UIFont *Font22Bold_;
1017 static const char *Machine_ = NULL;
1018 static NSString *System_ = nil;
1019 static NSString *SerialNumber_ = nil;
1020 static NSString *ChipID_ = nil;
1021 static NSString *Token_ = nil;
1022 static NSString *UniqueID_ = nil;
1023 static NSString *PLMN_ = nil;
1024 static NSString *Build_ = nil;
1025 static NSString *Product_ = nil;
1026 static NSString *Safari_ = nil;
1028 static CFLocaleRef Locale_;
1029 static NSArray *Languages_;
1030 static CGColorSpaceRef space_;
1032 static NSDictionary *SectionMap_;
1033 static NSMutableDictionary *Metadata_;
1034 static _transient NSMutableDictionary *Settings_;
1035 static _transient NSString *Role_;
1036 static _transient NSMutableDictionary *Packages_;
1037 static _transient NSMutableDictionary *Sections_;
1038 static _transient NSMutableDictionary *Sources_;
1039 static bool Changed_;
1043 static CGFloat ScreenScale_;
1046 /* Display Helpers {{{ */
1047 inline float Interpolate(float begin, float end, float fraction) {
1048 return (end - begin) * fraction + begin;
1051 /* XXX: localize this! */
1052 NSString *SizeString(double size) {
1053 bool negative = size < 0;
1058 while (size > 1024) {
1063 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1065 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1068 static _finline const char *StripVersion_(const char *version) {
1069 const char *colon(strchr(version, ':'));
1070 return colon == NULL ? version : colon + 1;
1073 NSString *LocalizeSection(NSString *section) {
1074 static Pcre title_r("^(.*?) \\((.*)\\)$");
1075 if (title_r(section)) {
1076 NSString *parent(title_r[1]);
1077 NSString *child(title_r[2]);
1079 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1080 LocalizeSection(parent),
1081 LocalizeSection(child)
1085 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1088 NSString *Simplify(NSString *title) {
1089 const char *data = [title UTF8String];
1090 size_t size = [title length];
1092 static Pcre square_r("^\\[(.*)\\]$");
1093 if (square_r(data, size))
1094 return Simplify(square_r[1]);
1096 static Pcre paren_r("^\\((.*)\\)$");
1097 if (paren_r(data, size))
1098 return Simplify(paren_r[1]);
1100 static Pcre title_r("^(.*?) \\((.*)\\)$");
1101 if (title_r(data, size))
1102 return Simplify(title_r[1]);
1108 NSString *GetLastUpdate() {
1109 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1112 return UCLocalize("NEVER_OR_UNKNOWN");
1114 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1115 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1117 CFRelease(formatter);
1119 return [(NSString *) formatted autorelease];
1122 bool isSectionVisible(NSString *section) {
1123 NSDictionary *metadata([Sections_ objectForKey:section]);
1124 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1125 return hidden == nil || ![hidden boolValue];
1130 /* Delegate Prototypes {{{ */
1134 @interface NSObject (ProgressDelegate)
1137 @protocol ProgressDelegate
1138 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1139 - (void) setProgressTitle:(NSString *)title;
1140 - (void) setProgressPercent:(float)percent;
1141 - (void) startProgress;
1142 - (void) addProgressOutput:(NSString *)output;
1143 - (bool) isCancelling:(size_t)received;
1146 @protocol ConfigurationDelegate
1147 - (void) repairWithSelector:(SEL)selector;
1148 - (void) setConfigurationData:(NSString *)data;
1151 @class CYPackageController;
1153 @protocol CydiaDelegate
1154 - (void) retainNetworkActivityIndicator;
1155 - (void) releaseNetworkActivityIndicator;
1156 - (void) clearPackage:(Package *)package;
1157 - (void) installPackage:(Package *)package;
1158 - (void) installPackages:(NSArray *)packages;
1159 - (void) removePackage:(Package *)package;
1160 - (void) beginUpdate;
1162 - (void) distUpgrade;
1164 - (void) updateData;
1166 - (void) showSettings;
1167 - (UIProgressHUD *) addProgressHUD;
1168 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1169 - (CYViewController *) pageForPackage:(NSString *)name;
1170 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1173 static id<CydiaDelegate> CydiaApp;
1176 /* Status Delegation {{{ */
1178 public pkgAcquireStatus
1181 _transient NSObject<ProgressDelegate> *delegate_;
1189 void setDelegate(id delegate) {
1190 delegate_ = delegate;
1193 NSObject<ProgressDelegate> *getDelegate() const {
1197 virtual bool MediaChange(std::string media, std::string drive) {
1201 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1204 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1205 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1206 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1209 virtual void Done(pkgAcquire::ItemDesc &item) {
1212 virtual void Fail(pkgAcquire::ItemDesc &item) {
1214 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1215 item.Owner->Status == pkgAcquire::Item::StatDone
1219 std::string &error(item.Owner->ErrorText);
1223 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1224 NSArray *fields([description componentsSeparatedByString:@" "]);
1225 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1227 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1228 withObject:[NSArray arrayWithObjects:
1229 [NSString stringWithUTF8String:error.c_str()],
1236 virtual bool Pulse(pkgAcquire *Owner) {
1237 bool value = pkgAcquireStatus::Pulse(Owner);
1240 double(CurrentBytes + CurrentItems) /
1241 double(TotalBytes + TotalItems)
1244 [delegate_ setProgressPercent:percent];
1245 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1248 virtual void Start() {
1249 [delegate_ startProgress];
1252 virtual void Stop() {
1256 /* Progress Delegation {{{ */
1261 _transient id<ProgressDelegate> delegate_;
1265 virtual void Update() {
1266 /*if (abs(Percent - percent_) > 2)
1267 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1271 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1272 [delegate_ setProgressPercent:(Percent / 100)];*/
1282 void setDelegate(id delegate) {
1283 delegate_ = delegate;
1286 id getDelegate() const {
1290 virtual void Done() {
1292 //[delegate_ setProgressPercent:1];
1297 /* Database Interface {{{ */
1298 typedef std::map< unsigned long, _H<Source> > SourceMap;
1300 @interface Database : NSObject {
1306 pkgCacheFile cache_;
1307 pkgDepCache::Policy *policy_;
1308 pkgRecords *records_;
1309 pkgProblemResolver *resolver_;
1310 pkgAcquire *fetcher_;
1312 SPtr<pkgPackageManager> manager_;
1313 pkgSourceList *list_;
1316 CFMutableArrayRef deadSources_;
1317 CFMutableArrayRef packages_;
1319 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1327 std::map<const char *, _H<NSString> > sections_;
1330 + (Database *) sharedInstance;
1333 - (void) _readCydia:(NSNumber *)fd;
1334 - (void) _readStatus:(NSNumber *)fd;
1335 - (void) _readOutput:(NSNumber *)fd;
1339 - (Package *) packageWithName:(NSString *)name;
1341 - (pkgCacheFile &) cache;
1342 - (pkgDepCache::Policy *) policy;
1343 - (pkgRecords *) records;
1344 - (pkgProblemResolver *) resolver;
1345 - (pkgAcquire &) fetcher;
1346 - (pkgSourceList &) list;
1347 - (NSArray *) packages;
1348 - (NSArray *) sources;
1349 - (void) reloadData;
1357 - (void) updateWithStatus:(Status &)status;
1359 - (void) setDelegate:(id)delegate;
1360 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1362 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1366 /* Delegate Helpers {{{ */
1367 @implementation NSObject (ProgressDelegate)
1369 - (void) _setProgressErrorPackage:(NSArray *)args {
1370 [self performSelector:@selector(setProgressError:forPackage:)
1371 withObject:[args objectAtIndex:0]
1372 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1376 - (void) _setProgressErrorTitle:(NSArray *)args {
1377 [self performSelector:@selector(setProgressError:withTitle:)
1378 withObject:[args objectAtIndex:0]
1379 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1383 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1384 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1385 withObject:[NSArray arrayWithObjects:error, title, nil]
1390 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1391 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1393 [self performSelector:@selector(setProgressError:withTitle:)
1395 withObject:(package == nil ? id : [package name])
1402 // Cytore Definitions {{{
1403 struct PackageValue :
1406 Cytore::Offset<PackageValue> next_;
1408 uint32_t index_ : 23;
1409 uint32_t subscribed_ : 1;
1426 Cytore::Offset<PackageValue> packages_[1 << 16];
1429 static Cytore::File<MetaValue> MetaFile_;
1431 // Cytore Helper Functions {{{
1432 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1433 SplitHash nhash = { hashlittle(name, length) };
1435 PackageValue *metadata;
1437 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1438 offset: if (offset->IsNull()) {
1439 *offset = MetaFile_.New<PackageValue>(length + 1);
1440 metadata = &MetaFile_.Get(*offset);
1442 if (metadata == NULL) {
1446 metadata = new PackageValue();
1447 memset(metadata, 0, sizeof(*metadata));
1450 memcpy(metadata->name_, name, length + 1);
1451 metadata->nhash_ = nhash.u16[1];
1453 metadata = &MetaFile_.Get(*offset);
1455 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1456 offset = &metadata->next_;
1464 static void PackageImport(const void *key, const void *value, void *context) {
1465 bool &fail(*reinterpret_cast<bool *>(context));
1468 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1469 NSLog(@"failed to import package %@", key);
1473 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1474 NSDictionary *package((NSDictionary *) value);
1476 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1477 if ([subscribed boolValue] && !metadata->subscribed_)
1478 metadata->subscribed_ = true;
1480 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1481 time_t time([date timeIntervalSince1970]);
1482 if (metadata->first_ > time || metadata->first_ == 0)
1483 metadata->first_ = time;
1486 NSDate *date([package objectForKey:@"LastSeen"]);
1487 NSString *version([package objectForKey:@"LastVersion"]);
1489 if (date != nil && version != nil) {
1490 time_t time([date timeIntervalSince1970]);
1491 if (metadata->last_ < time || metadata->last_ == 0)
1492 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1493 size_t length(strlen(buffer));
1494 uint16_t vhash(hashlittle(buffer, length));
1496 size_t capped(std::min<size_t>(8, length));
1497 char *latest(buffer + length - capped);
1499 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1500 metadata->vhash_ = vhash;
1502 metadata->last_ = time;
1508 /* Source Class {{{ */
1509 @interface Source : NSObject {
1510 CYString depiction_;
1511 CYString description_;
1517 CYString distribution_;
1522 NSString *authority_;
1524 CYString defaultIcon_;
1526 NSDictionary *record_;
1530 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1532 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1534 - (NSString *) depictionForPackage:(NSString *)package;
1535 - (NSString *) supportForPackage:(NSString *)package;
1537 - (NSDictionary *) record;
1541 - (NSString *) distribution;
1542 - (NSString *) type;
1544 - (NSString *) host;
1546 - (NSString *) name;
1547 - (NSString *) description;
1548 - (NSString *) label;
1549 - (NSString *) origin;
1550 - (NSString *) version;
1552 - (NSString *) defaultIcon;
1556 @implementation Source
1560 distribution_.clear();
1563 description_.clear();
1569 defaultIcon_.clear();
1571 if (record_ != nil) {
1581 if (authority_ != nil) {
1582 [authority_ release];
1588 // XXX: this is a very inefficient way to call these deconstructors
1593 + (NSArray *) _attributeKeys {
1594 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1597 - (NSArray *) attributeKeys {
1598 return [[self class] _attributeKeys];
1601 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1602 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1605 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1608 trusted_ = index->IsTrusted();
1610 uri_.set(pool, index->GetURI());
1611 distribution_.set(pool, index->GetDist());
1612 type_.set(pool, index->GetType());
1614 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1615 if (dindex != NULL) {
1617 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1620 pkgTagFile tags(&fd);
1622 pkgTagSection section;
1629 {"default-icon", &defaultIcon_},
1630 {"depiction", &depiction_},
1631 {"description", &description_},
1633 {"origin", &origin_},
1634 {"support", &support_},
1635 {"version", &version_},
1638 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1639 const char *start, *end;
1641 if (section.Find(names[i].name_, start, end)) {
1642 CYString &value(*names[i].value_);
1643 value.set(pool, start, end - start);
1649 record_ = [Sources_ objectForKey:[self key]];
1651 record_ = [record_ retain];
1653 NSURL *url([NSURL URLWithString:uri_]);
1657 host_ = [[host_ lowercaseString] retain];
1662 authority_ = [url path];
1664 if (authority_ != nil)
1665 authority_ = [authority_ retain];
1668 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1669 if ((self = [super init]) != nil) {
1670 [self setMetaIndex:index inPool:pool];
1674 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1675 NSDictionary *lhr = [self record];
1676 NSDictionary *rhr = [source record];
1679 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1681 NSString *lhs = [self name];
1682 NSString *rhs = [source name];
1684 if ([lhs length] != 0 && [rhs length] != 0) {
1685 unichar lhc = [lhs characterAtIndex:0];
1686 unichar rhc = [rhs characterAtIndex:0];
1688 if (isalpha(lhc) && !isalpha(rhc))
1689 return NSOrderedAscending;
1690 else if (!isalpha(lhc) && isalpha(rhc))
1691 return NSOrderedDescending;
1694 return [lhs compare:rhs options:LaxCompareOptions_];
1697 - (NSString *) depictionForPackage:(NSString *)package {
1698 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1701 - (NSString *) supportForPackage:(NSString *)package {
1702 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1705 - (NSDictionary *) record {
1713 - (NSString *) uri {
1717 - (NSString *) distribution {
1718 return distribution_;
1721 - (NSString *) type {
1725 - (NSString *) key {
1726 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1729 - (NSString *) host {
1733 - (NSString *) name {
1734 return origin_.empty() ? authority_ : origin_;
1737 - (NSString *) description {
1738 return description_;
1741 - (NSString *) label {
1742 return label_.empty() ? authority_ : label_;
1745 - (NSString *) origin {
1749 - (NSString *) version {
1753 - (NSString *) defaultIcon {
1754 return defaultIcon_;
1759 /* Relationship Class {{{ */
1760 @interface Relationship : NSObject {
1765 - (NSString *) type;
1767 - (NSString *) name;
1771 @implementation Relationship
1779 - (NSString *) type {
1787 - (NSString *) name {
1794 /* Package Class {{{ */
1795 struct ParsedPackage {
1800 CYString depiction_;
1810 @interface Package : NSObject {
1813 uint32_t essential_ : 1;
1814 uint32_t obsolete_ : 1;
1815 uint32_t ignored_ : 1;
1819 _transient Database *database_;
1821 pkgCache::VerIterator version_;
1822 pkgCache::PkgIterator iterator_;
1823 pkgCache::VerFileIterator file_;
1829 CYString installed_;
1831 const char *section_;
1832 _transient NSString *section$_;
1836 PackageValue *metadata_;
1837 ParsedPackage *parsed_;
1839 NSMutableArray *tags_;
1842 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1843 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1845 - (pkgCache::PkgIterator) iterator;
1848 - (NSString *) section;
1849 - (NSString *) simpleSection;
1851 - (NSString *) longSection;
1852 - (NSString *) shortSection;
1856 - (Address *) maintainer;
1858 - (NSString *) longDescription;
1859 - (NSString *) shortDescription;
1862 - (PackageValue *) metadata;
1865 - (bool) subscribed;
1866 - (bool) setSubscribed:(bool)subscribed;
1870 - (NSString *) latest;
1871 - (NSString *) installed;
1872 - (BOOL) uninstalled;
1875 - (BOOL) upgradableAndEssential:(BOOL)essential;
1878 - (BOOL) unfiltered;
1882 - (BOOL) halfConfigured;
1883 - (BOOL) halfInstalled;
1885 - (NSString *) mode;
1888 - (NSString *) name;
1890 - (NSString *) homepage;
1891 - (NSString *) depiction;
1892 - (Address *) author;
1894 - (NSString *) support;
1896 - (NSArray *) files;
1897 - (NSArray *) warnings;
1898 - (NSArray *) applications;
1900 - (Source *) source;
1902 - (BOOL) matches:(NSString *)text;
1904 - (bool) hasSupportingRole;
1905 - (BOOL) hasTag:(NSString *)tag;
1906 - (NSString *) primaryPurpose;
1907 - (NSArray *) purposes;
1908 - (bool) isCommercial;
1910 - (void) setIndex:(size_t)index;
1912 - (CYString &) cyname;
1914 - (uint32_t) compareBySection:(NSArray *)sections;
1919 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1920 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1921 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1922 - (bool) isVisibleInSection:(NSString *)section;
1923 - (bool) isVisibleInSource:(Source *)source;
1927 uint32_t PackageChangesRadix(Package *self, void *) {
1932 uint32_t timestamp : 30;
1933 uint32_t ignored : 1;
1934 uint32_t upgradable : 1;
1938 bool upgradable([self upgradableAndEssential:YES]);
1939 value.bits.upgradable = upgradable ? 1 : 0;
1942 value.bits.timestamp = 0;
1943 value.bits.ignored = [self ignored] ? 0 : 1;
1944 value.bits.upgradable = 1;
1946 value.bits.timestamp = [self seen] >> 2;
1947 value.bits.ignored = 0;
1948 value.bits.upgradable = 0;
1951 return _not(uint32_t) - value.key;
1954 uint32_t PackagePrefixRadix(Package *self, void *context) {
1955 size_t offset(reinterpret_cast<size_t>(context));
1956 CYString &name([self cyname]);
1958 size_t size(name.size());
1961 char *text(name.data());
1964 if (!isdigit(text[0]))
1968 while (size != digits && isdigit(text[digits]))
1976 if (offset == 0 && zeros != 0) {
1977 memset(data, '0', zeros);
1978 memcpy(data + zeros, text, 4 - zeros);
1980 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1981 if (size <= offset - zeros)
1984 text += offset - zeros;
1985 size -= offset - zeros;
1988 memcpy(data, text, 4);
1990 memcpy(data, text, size);
1991 memset(data + size, 0, 4 - size);
1994 for (size_t i(0); i != 4; ++i)
1995 if (isalpha(data[i]))
2003 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2005 /* XXX: ntohl may be more honest */
2006 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2009 CYString &(*PackageName)(Package *self, SEL sel);
2011 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2012 _profile(PackageNameCompare)
2013 CYString &lhi(PackageName(lhs, @selector(cyname)));
2014 CYString &rhi(PackageName(rhs, @selector(cyname)));
2015 CFStringRef lhn(lhi), rhn(rhi);
2018 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2019 else if (rhn == NULL)
2020 return NSOrderedDescending;
2022 _profile(PackageNameCompare$NumbersLast)
2023 if (!lhi.empty() && !rhi.empty()) {
2024 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2025 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2026 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2027 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2028 return lha ? NSOrderedAscending : NSOrderedDescending;
2032 CFIndex length = CFStringGetLength(lhn);
2034 _profile(PackageNameCompare$Compare)
2035 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2040 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2041 return PackageNameCompare(*lhs, *rhs, context);
2044 struct PackageNameOrdering :
2045 std::binary_function<Package *, Package *, bool>
2047 _finline bool operator ()(Package *lhs, Package *rhs) const {
2048 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2052 @implementation Package
2054 - (NSString *) description {
2055 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2059 if (parsed_ != NULL)
2068 + (NSString *) webScriptNameForSelector:(SEL)selector {
2069 if (selector == @selector(hasTag:))
2075 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2076 return [self webScriptNameForSelector:selector] == nil;
2079 + (NSArray *) _attributeKeys {
2080 return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"longDescription", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"longSection", @"maintainer", @"mode", @"name", @"purposes", @"section", @"shortDescription", @"shortSection", @"simpleSection", @"size", @"source", @"sponsor", @"support", @"warnings", nil];
2083 - (NSArray *) attributeKeys {
2084 return [[self class] _attributeKeys];
2087 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2088 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2092 if (parsed_ != NULL)
2094 @synchronized (database_) {
2095 if ([database_ era] != era_ || file_.end())
2098 ParsedPackage *parsed(new ParsedPackage);
2101 _profile(Package$parse)
2102 pkgRecords::Parser *parser;
2104 _profile(Package$parse$Lookup)
2105 parser = &[database_ records]->Lookup(file_);
2110 _profile(Package$parse$Find)
2115 {"icon", &parsed->icon_},
2116 {"depiction", &parsed->depiction_},
2117 {"homepage", &parsed->homepage_},
2118 {"website", &website},
2119 {"bugs", &parsed->bugs_},
2120 {"support", &parsed->support_},
2121 {"sponsor", &parsed->sponsor_},
2122 {"author", &parsed->author_},
2125 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2126 const char *start, *end;
2128 if (parser->Find(names[i].name_, start, end)) {
2129 CYString &value(*names[i].value_);
2130 _profile(Package$parse$Value)
2131 value.set(pool_, start, end - start);
2137 _profile(Package$parse$Tagline)
2138 const char *start, *end;
2139 if (parser->ShortDesc(start, end)) {
2140 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2143 while (stop != start && stop[-1] == '\r')
2145 parsed->tagline_.set(pool_, start, stop - start);
2149 _profile(Package$parse$Retain)
2150 if (parsed->homepage_.empty())
2151 parsed->homepage_ = website;
2152 if (parsed->homepage_ == parsed->depiction_)
2153 parsed->homepage_.clear();
2158 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2159 if ((self = [super init]) != nil) {
2160 _profile(Package$initWithVersion)
2163 database_ = database;
2164 era_ = [database era];
2168 pkgCache::PkgIterator iterator(version.ParentPkg());
2169 iterator_ = iterator;
2171 _profile(Package$initWithVersion$Version)
2172 if (!version_.end())
2173 file_ = version_.FileList();
2175 pkgCache &cache([database_ cache]);
2176 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2180 _profile(Package$initWithVersion$Cache)
2181 name_.set(NULL, iterator.Display());
2183 latest_.set(NULL, StripVersion_(version_.VerStr()));
2185 pkgCache::VerIterator current(iterator.CurrentVer());
2187 installed_.set(NULL, StripVersion_(current.VerStr()));
2190 _profile(Package$initWithVersion$Tags)
2191 pkgCache::TagIterator tag(iterator.TagList());
2193 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2195 const char *name(tag.Name());
2196 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2198 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2199 if (strcmp(name + 6, "enduser") == 0)
2201 else if (strcmp(name + 6, "hacker") == 0)
2203 else if (strcmp(name + 6, "developer") == 0)
2205 else if (strcmp(name + 6, "cydia") == 0)
2211 if (strncmp(name, "cydia::", 7) == 0) {
2212 if (strcmp(name + 7, "essential") == 0)
2214 else if (strcmp(name + 7, "obsolete") == 0)
2219 } while (!tag.end());
2223 _profile(Package$initWithVersion$Metadata)
2224 const char *mixed(iterator.Name());
2225 size_t size(strlen(mixed));
2226 char lower[size + 1];
2228 for (size_t i(0); i != size; ++i)
2229 lower[i] = mixed[i] | 0x20;
2232 PackageValue *metadata(PackageFind(lower, size));
2233 metadata_ = metadata;
2235 id_.set(NULL, metadata->name_, size);
2237 const char *latest(version_.VerStr());
2238 size_t length(strlen(latest));
2240 uint16_t vhash(hashlittle(latest, length));
2242 size_t capped(std::min<size_t>(8, length));
2243 latest = latest + length - capped;
2245 if (metadata->first_ == 0)
2246 metadata->first_ = now_;
2248 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2249 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2250 metadata->vhash_ = vhash;
2251 metadata->last_ = now_;
2252 } else if (metadata->last_ == 0)
2253 metadata->last_ = metadata->first_;
2256 _profile(Package$initWithVersion$Section)
2257 section_ = iterator.Section();
2260 _profile(Package$initWithVersion$Flags)
2261 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2262 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2267 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2268 pkgCache::VerIterator version;
2270 _profile(Package$packageWithIterator$GetCandidateVer)
2271 version = [database policy]->GetCandidateVer(iterator);
2279 _profile(Package$packageWithIterator$Allocate)
2280 package = [Package allocWithZone:zone];
2283 _profile(Package$packageWithIterator$Initialize)
2285 initWithVersion:version
2292 _profile(Package$packageWithIterator$Autorelease)
2293 package = [package autorelease];
2299 - (pkgCache::PkgIterator) iterator {
2303 - (NSString *) section {
2304 if (section$_ == nil) {
2305 if (section_ == NULL)
2308 _profile(Package$section$mappedSectionForPointer)
2309 section$_ = [database_ mappedSectionForPointer:section_];
2314 - (NSString *) simpleSection {
2315 if (NSString *section = [self section])
2316 return Simplify(section);
2321 - (NSString *) longSection {
2322 return LocalizeSection([self section]);
2325 - (NSString *) shortSection {
2326 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2329 - (NSString *) uri {
2332 pkgIndexFile *index;
2333 pkgCache::PkgFileIterator file(file_.File());
2334 if (![database_ list].FindIndex(file, index))
2336 return [NSString stringWithUTF8String:iterator_->Path];
2337 //return [NSString stringWithUTF8String:file.Site()];
2338 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2342 - (Address *) maintainer {
2343 @synchronized (database_) {
2344 if ([database_ era] != era_ || file_.end())
2347 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2348 const std::string &maintainer(parser->Maintainer());
2349 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2353 @synchronized (database_) {
2354 if ([database_ era] != era_ || version_.end())
2357 return version_->InstalledSize;
2360 - (NSString *) longDescription {
2361 @synchronized (database_) {
2362 if ([database_ era] != era_ || file_.end())
2365 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2366 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2368 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2369 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2370 if ([lines count] < 2)
2373 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2374 for (size_t i(1), e([lines count]); i != e; ++i) {
2375 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2376 [trimmed addObject:trim];
2379 return [trimmed componentsJoinedByString:@"\n"];
2382 - (NSString *) shortDescription {
2383 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2387 _profile(Package$index)
2388 CFStringRef name((CFStringRef) [self name]);
2389 if (CFStringGetLength(name) == 0)
2391 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2392 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2394 return toupper(character);
2398 - (PackageValue *) metadata {
2403 PackageValue *metadata([self metadata]);
2404 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2407 - (bool) subscribed {
2408 return [self metadata]->subscribed_;
2411 - (bool) setSubscribed:(bool)subscribed {
2412 PackageValue *metadata([self metadata]);
2413 if (metadata->subscribed_ == subscribed)
2415 metadata->subscribed_ = subscribed;
2423 - (NSString *) latest {
2427 - (NSString *) installed {
2431 - (BOOL) uninstalled {
2432 return installed_.empty();
2436 return !version_.end();
2439 - (BOOL) upgradableAndEssential:(BOOL)essential {
2440 _profile(Package$upgradableAndEssential)
2441 pkgCache::VerIterator current(iterator_.CurrentVer());
2443 return essential && essential_;
2445 return !version_.end() && version_ != current;
2449 - (BOOL) essential {
2454 return [database_ cache][iterator_].InstBroken();
2457 - (BOOL) unfiltered {
2458 _profile(Package$unfiltered$obsolete)
2459 if (_unlikely(obsolete_))
2463 _profile(Package$unfiltered$hasSupportingRole)
2464 if (_unlikely(![self hasSupportingRole]))
2472 if (![self unfiltered])
2477 _profile(Package$visible$section)
2478 section = [self section];
2481 _profile(Package$visible$isSectionVisible)
2482 if (section != nil && !isSectionVisible(section))
2490 unsigned char current(iterator_->CurrentState);
2491 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2494 - (BOOL) halfConfigured {
2495 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2498 - (BOOL) halfInstalled {
2499 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2503 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2504 return state.Mode != pkgDepCache::ModeKeep;
2507 - (NSString *) mode {
2508 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2510 switch (state.Mode) {
2511 case pkgDepCache::ModeDelete:
2512 if ((state.iFlags & pkgDepCache::Purge) != 0)
2516 case pkgDepCache::ModeKeep:
2517 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2518 return @"REINSTALL";
2519 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2523 case pkgDepCache::ModeInstall:
2524 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2525 return @"REINSTALL";
2526 else*/ switch (state.Status) {
2528 return @"DOWNGRADE";
2534 return @"NEW_INSTALL";
2545 - (NSString *) name {
2546 return name_.empty() ? id_ : name_;
2549 - (UIImage *) icon {
2550 NSString *section = [self simpleSection];
2553 if (parsed_ != NULL)
2554 if (NSString *href = parsed_->icon_)
2555 if ([href hasPrefix:@"file:///"])
2556 // XXX: correct escaping
2557 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2558 if (icon == nil) if (section != nil)
2559 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2560 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2561 if ([dicon hasPrefix:@"file:///"])
2562 // XXX: correct escaping
2563 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2565 icon = [UIImage applicationImageNamed:@"unknown.png"];
2569 - (NSString *) homepage {
2570 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2573 - (NSString *) depiction {
2574 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2577 - (Address *) sponsor {
2578 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2581 - (Address *) author {
2582 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2585 - (NSString *) support {
2586 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2589 - (NSArray *) files {
2590 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2591 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2594 fin.open([path UTF8String]);
2599 while (std::getline(fin, line))
2600 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2605 - (NSArray *) warnings {
2606 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2607 const char *name(iterator_.Name());
2609 size_t length(strlen(name));
2610 if (length < 2) invalid:
2611 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2612 else for (size_t i(0); i != length; ++i)
2614 /* XXX: technically this is not allowed */
2615 (name[i] < 'A' || name[i] > 'Z') &&
2616 (name[i] < 'a' || name[i] > 'z') &&
2617 (name[i] < '0' || name[i] > '9') &&
2618 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2621 if (strcmp(name, "cydia") != 0) {
2624 bool _private = false;
2627 bool repository = [[self section] isEqualToString:@"Repositories"];
2629 if (NSArray *files = [self files])
2630 for (NSString *file in files)
2631 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2633 else if (!user && [file isEqualToString:@"/User"])
2635 else if (!_private && [file isEqualToString:@"/private"])
2637 else if (!stash && [file isEqualToString:@"/var/stash"])
2640 /* XXX: this is not sensitive enough. only some folders are valid. */
2641 if (cydia && !repository)
2642 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2644 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2646 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2648 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2651 return [warnings count] == 0 ? nil : warnings;
2654 - (NSArray *) applications {
2655 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2657 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2659 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2660 if (NSArray *files = [self files])
2661 for (NSString *file in files)
2662 if (application_r(file)) {
2663 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2664 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2665 if ([id isEqualToString:me])
2668 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2670 display = application_r[1];
2672 NSString *bundle([file stringByDeletingLastPathComponent]);
2673 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2674 if (icon == nil || [icon length] == 0)
2676 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2678 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2679 [applications addObject:application];
2681 [application addObject:id];
2682 [application addObject:display];
2683 [application addObject:url];
2686 return [applications count] == 0 ? nil : applications;
2689 - (Source *) source {
2690 if (source_ == nil) {
2691 @synchronized (database_) {
2692 if ([database_ era] != era_ || file_.end())
2693 source_ = (Source *) [NSNull null];
2695 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2699 return source_ == (Source *) [NSNull null] ? nil : source_;
2702 - (BOOL) matches:(NSString *)text {
2708 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2709 if (range.location != NSNotFound)
2712 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2713 if (range.location != NSNotFound)
2718 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2719 if (range.location != NSNotFound)
2725 - (bool) hasSupportingRole {
2730 if ([Role_ isEqualToString:@"User"])
2734 if ([Role_ isEqualToString:@"Hacker"])
2738 if ([Role_ isEqualToString:@"Developer"])
2743 - (BOOL) hasTag:(NSString *)tag {
2744 return tags_ == nil ? NO : [tags_ containsObject:tag];
2747 - (NSString *) primaryPurpose {
2748 for (NSString *tag in tags_)
2749 if ([tag hasPrefix:@"purpose::"])
2750 return [tag substringFromIndex:9];
2754 - (NSArray *) purposes {
2755 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2756 for (NSString *tag in tags_)
2757 if ([tag hasPrefix:@"purpose::"])
2758 [purposes addObject:[tag substringFromIndex:9]];
2759 return [purposes count] == 0 ? nil : purposes;
2762 - (bool) isCommercial {
2763 return [self hasTag:@"cydia::commercial"];
2766 - (void) setIndex:(size_t)index {
2767 if (metadata_->index_ != index)
2768 metadata_->index_ = index;
2771 - (CYString &) cyname {
2772 return name_.empty() ? id_ : name_;
2775 - (uint32_t) compareBySection:(NSArray *)sections {
2776 NSString *section([self section]);
2777 for (size_t i(0), e([sections count]); i != e; ++i) {
2778 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2782 return _not(uint32_t);
2786 @synchronized (database_) {
2787 pkgProblemResolver *resolver = [database_ resolver];
2788 resolver->Clear(iterator_);
2790 pkgCacheFile &cache([database_ cache]);
2791 cache->SetReInstall(iterator_, false);
2792 cache->MarkKeep(iterator_, false);
2796 @synchronized (database_) {
2797 pkgProblemResolver *resolver = [database_ resolver];
2798 resolver->Clear(iterator_);
2799 resolver->Protect(iterator_);
2801 pkgCacheFile &cache([database_ cache]);
2802 cache->SetReInstall(iterator_, false);
2803 cache->MarkInstall(iterator_, false);
2805 pkgDepCache::StateCache &state((*cache)[iterator_]);
2806 if (!state.Install())
2807 cache->SetReInstall(iterator_, true);
2811 @synchronized (database_) {
2812 pkgProblemResolver *resolver = [database_ resolver];
2813 resolver->Clear(iterator_);
2814 resolver->Remove(iterator_);
2815 resolver->Protect(iterator_);
2817 pkgCacheFile &cache([database_ cache]);
2818 cache->SetReInstall(iterator_, false);
2819 cache->MarkDelete(iterator_, true);
2822 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2823 _profile(Package$isUnfilteredAndSearchedForBy)
2826 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2827 value &= [self unfiltered];
2830 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2831 value &= [self matches:search];
2838 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2839 if ([search length] == 0)
2842 _profile(Package$isUnfilteredAndSelectedForBy)
2845 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2846 value &= [self unfiltered];
2849 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2850 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2857 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2858 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2861 - (bool) isVisibleInSection:(NSString *)name {
2862 NSString *section([self section]);
2866 section == nil && [name length] == 0 ||
2867 [name isEqualToString:section]
2868 ) && [self visible];
2871 - (bool) isVisibleInSource:(Source *)source {
2872 return [self source] == source && [self visible];
2877 /* Section Class {{{ */
2878 @interface Section : NSObject {
2883 NSString *localized_;
2886 - (NSComparisonResult) compareByLocalized:(Section *)section;
2887 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2888 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2889 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2890 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2891 - (NSString *) name;
2898 - (void) addToCount;
2900 - (void) setCount:(size_t)count;
2901 - (NSString *) localized;
2905 @implementation Section
2909 if (localized_ != nil)
2910 [localized_ release];
2914 - (NSComparisonResult) compareByLocalized:(Section *)section {
2915 NSString *lhs(localized_);
2916 NSString *rhs([section localized]);
2918 /*if ([lhs length] != 0 && [rhs length] != 0) {
2919 unichar lhc = [lhs characterAtIndex:0];
2920 unichar rhc = [rhs characterAtIndex:0];
2922 if (isalpha(lhc) && !isalpha(rhc))
2923 return NSOrderedAscending;
2924 else if (!isalpha(lhc) && isalpha(rhc))
2925 return NSOrderedDescending;
2928 return [lhs compare:rhs options:LaxCompareOptions_];
2931 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2932 if ((self = [self initWithName:name localize:NO]) != nil) {
2933 if (localized != nil)
2934 localized_ = [localized retain];
2938 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2939 return [self initWithName:name row:0 localize:localize];
2942 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2943 if ((self = [super init]) != nil) {
2944 name_ = [name retain];
2948 localized_ = [LocalizeSection(name_) retain];
2952 /* XXX: localize the index thingees */
2953 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2954 if ((self = [super init]) != nil) {
2955 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2961 - (NSString *) name {
2981 - (void) addToCount {
2985 - (void) setCount:(size_t)count {
2989 - (NSString *) localized {
2996 static NSString *Colon_;
2997 static NSString *Elision_;
2998 static NSString *Error_;
2999 static NSString *Warning_;
3001 /* Database Implementation {{{ */
3002 @implementation Database
3004 + (Database *) sharedInstance {
3005 static Database *instance;
3006 if (instance == nil)
3007 instance = [[Database alloc] init];
3015 - (void) releasePackages {
3016 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3017 CFArrayRemoveAllValues(packages_);
3021 // XXX: actually implement this thing
3024 CFRelease(deadSources_);
3025 [self releasePackages];
3026 apr_pool_destroy(pool_);
3027 NSRecycleZone(zone_);
3031 - (void) _readCydia:(NSNumber *)fd { _pooled
3032 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3033 std::istream is(&ib);
3036 static Pcre finish_r("^finish:([^:]*)$");
3038 while (std::getline(is, line)) {
3039 const char *data(line.c_str());
3040 size_t size = line.size();
3041 lprintf("C:%s\n", data);
3043 if (finish_r(data, size)) {
3044 NSString *finish = finish_r[1];
3045 int index = [Finishes_ indexOfObject:finish];
3046 if (index != INT_MAX && index > Finish_)
3054 - (void) _readStatus:(NSNumber *)fd { _pooled
3055 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3056 std::istream is(&ib);
3059 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3060 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3062 while (std::getline(is, line)) {
3063 const char *data(line.c_str());
3064 size_t size(line.size());
3065 lprintf("S:%s\n", data);
3067 if (conffile_r(data, size)) {
3068 [delegate_ setConfigurationData:conffile_r[1]];
3069 } else if (strncmp(data, "status: ", 8) == 0) {
3070 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3071 [delegate_ setProgressTitle:string];
3072 } else if (pmstatus_r(data, size)) {
3073 std::string type([pmstatus_r[1] UTF8String]);
3074 NSString *id = pmstatus_r[2];
3076 float percent([pmstatus_r[3] floatValue]);
3077 [delegate_ setProgressPercent:(percent / 100)];
3079 NSString *string = pmstatus_r[4];
3081 if (type == "pmerror")
3082 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3083 withObject:[NSArray arrayWithObjects:string, id, nil]
3086 else if (type == "pmstatus") {
3087 [delegate_ setProgressTitle:string];
3088 } else if (type == "pmconffile")
3089 [delegate_ setConfigurationData:string];
3091 lprintf("E:unknown pmstatus\n");
3093 lprintf("E:unknown status\n");
3099 - (void) _readOutput:(NSNumber *)fd { _pooled
3100 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3101 std::istream is(&ib);
3104 while (std::getline(is, line)) {
3105 lprintf("O:%s\n", line.c_str());
3106 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3116 - (Package *) packageWithName:(NSString *)name {
3117 @synchronized (self) {
3118 if (static_cast<pkgDepCache *>(cache_) == NULL)
3120 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3121 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3125 if ((self = [super init]) != nil) {
3132 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3133 apr_pool_create(&pool_, NULL);
3135 size_t capacity(MetaFile_->active_);
3141 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3142 deadSources_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
3146 _assert(pipe(fds) != -1);
3149 _config->Set("APT::Keep-Fds::", cydiafd_);
3150 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3153 detachNewThreadSelector:@selector(_readCydia:)
3155 withObject:[NSNumber numberWithInt:fds[0]]
3158 _assert(pipe(fds) != -1);
3162 detachNewThreadSelector:@selector(_readStatus:)
3164 withObject:[NSNumber numberWithInt:fds[0]]
3167 _assert(pipe(fds) != -1);
3168 _assert(dup2(fds[0], 0) != -1);
3169 _assert(close(fds[0]) != -1);
3171 input_ = fdopen(fds[1], "a");
3173 _assert(pipe(fds) != -1);
3174 _assert(dup2(fds[1], 1) != -1);
3175 _assert(close(fds[1]) != -1);
3178 detachNewThreadSelector:@selector(_readOutput:)
3180 withObject:[NSNumber numberWithInt:fds[0]]
3185 - (pkgCacheFile &) cache {
3189 - (pkgDepCache::Policy *) policy {
3193 - (pkgRecords *) records {
3197 - (pkgProblemResolver *) resolver {
3201 - (pkgAcquire &) fetcher {
3205 - (pkgSourceList &) list {
3209 - (NSArray *) packages {
3210 return (NSArray *) packages_;
3213 - (NSArray *) sources {
3214 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3215 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3216 [sources addObject:i->second];
3217 [sources addObjectsFromArray:(NSArray *)deadSources_];
3221 - (NSArray *) issues {
3222 if (cache_->BrokenCount() == 0)
3225 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3227 for (Package *package in [self packages]) {
3228 if (![package broken])
3230 pkgCache::PkgIterator pkg([package iterator]);
3232 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3233 [entry addObject:[package name]];
3234 [issues addObject:entry];
3236 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3240 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3241 pkgCache::DepIterator start;
3242 pkgCache::DepIterator end;
3243 dep.GlobOr(start, end); // ++dep
3245 if (!cache_->IsImportantDep(end))
3247 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3250 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3251 [entry addObject:failure];
3252 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3254 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3255 if (Package *package = [self packageWithName:name])
3256 name = [package name];
3257 [failure addObject:name];
3259 pkgCache::PkgIterator target(start.TargetPkg());
3260 if (target->ProvidesList != 0)
3261 [failure addObject:@"?"];
3263 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3265 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3266 else if (!cache_[target].CandidateVerIter(cache_).end())
3267 [failure addObject:@"-"];
3268 else if (target->ProvidesList == 0)
3269 [failure addObject:@"!"];
3271 [failure addObject:@"%"];
3275 if (start.TargetVer() != 0)
3276 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3287 - (bool) popErrorWithTitle:(NSString *)title {
3289 std::string message;
3291 while (!_error->empty()) {
3293 bool warning(!_error->PopMessage(error));
3297 size_t size(error.size());
3298 if (size == 0 || error[size - 1] != '\n')
3300 error.resize(size - 1);
3302 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3304 if (!message.empty())
3309 if (fatal && !message.empty())
3310 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3315 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3316 return [self popErrorWithTitle:title] || !success;
3319 - (void) reloadData { CYPoolStart() {
3320 @synchronized (self) {
3323 [self releasePackages];
3326 CFArrayRemoveAllValues(deadSources_);
3346 apr_pool_clear(pool_);
3348 NSRecycleZone(zone_);
3349 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3351 int chk(creat("/tmp/cydia.chk", 0644));
3355 NSString *title(UCLocalize("DATABASE"));
3358 while (!cache_.Open(progress_, true)) { pop:
3360 bool warning(!_error->PopMessage(error));
3361 lprintf("cache_.Open():[%s]\n", error.c_str());
3363 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3364 [delegate_ repairWithSelector:@selector(configure)];
3365 else if (error == "The package lists or status file could not be parsed or opened.")
3366 [delegate_ repairWithSelector:@selector(update)];
3367 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3368 else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3369 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, Error_, title]];
3370 // else if (error == "The list of sources could not be read.")
3372 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3382 unlink("/tmp/cydia.chk");
3384 now_ = [[NSDate date] timeIntervalSince1970];
3386 policy_ = new pkgDepCache::Policy();
3387 records_ = new pkgRecords(cache_);
3388 resolver_ = new pkgProblemResolver(cache_);
3389 fetcher_ = new pkgAcquire(&status_);
3392 list_ = new pkgSourceList();
3393 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3396 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3397 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3401 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3404 if (cache_->BrokenCount() != 0) {
3405 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3408 if (cache_->BrokenCount() != 0) {
3409 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3413 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3417 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3419 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3420 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3421 // XXX: this could be more intelligent
3422 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3423 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3424 if (!cached.end()) {
3425 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3430 CFArrayAppendValue(deadSources_, [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3434 /*std::vector<Package *> packages;
3435 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3436 [packages_ release];
3441 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3442 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3443 //packages.push_back(package);
3444 CFArrayAppendValue(packages_, [package retain]);
3448 /*if (packages.empty())
3449 packages_ = [[NSArray alloc] init];
3451 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3454 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3455 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3456 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3464 /*if (!packages.empty())
3465 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3466 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3468 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3470 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3472 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3476 size_t count(CFArrayGetCount(packages_));
3477 MetaFile_->active_ = count;
3479 for (size_t index(0); index != count; ++index)
3480 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3484 } } CYPoolEnd() _trace(); }
3487 @synchronized (self) {
3489 resolver_ = new pkgProblemResolver(cache_);
3491 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3492 if (!cache_[iterator].Keep()) {
3493 cache_->MarkKeep(iterator, false);
3494 cache_->SetReInstall(iterator, false);
3499 - (void) configure {
3500 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3502 system([dpkg UTF8String]);
3507 // XXX: I don't remember this condition
3512 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3514 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3516 if ([self popErrorWithTitle:title])
3520 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3523 public pkgArchiveCleaner
3526 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3531 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3538 fetcher_->Shutdown();
3540 pkgRecords records(cache_);
3542 lock_ = new FileFd();
3543 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3545 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3547 if ([self popErrorWithTitle:title])
3551 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3554 manager_ = (_system->CreatePM(cache_));
3555 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3562 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3564 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3566 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3568 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3569 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3572 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3577 [CydiaApp retainNetworkActivityIndicator];
3579 bool failed = false;
3580 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3581 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3583 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3586 std::string uri = (*item)->DescURI();
3587 std::string error = (*item)->ErrorText;
3589 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3592 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3593 withObject:[NSArray arrayWithObjects:
3594 [NSString stringWithUTF8String:error.c_str()],
3600 [CydiaApp releaseNetworkActivityIndicator];
3608 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3610 if (_error->PendingError()) {
3615 if (result == pkgPackageManager::Failed) {
3620 if (result != pkgPackageManager::Completed) {
3625 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3627 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3629 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3630 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3633 if (![before isEqualToArray:after])
3638 NSString *title(UCLocalize("UPGRADE"));
3639 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3645 [self updateWithStatus:status_];
3648 - (void) updateWithStatus:(Status &)status {
3649 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3650 NSString *title(UCLocalize("REFRESHING_DATA"));
3653 if (!list.ReadMainList())
3654 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3657 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3658 if ([self popErrorWithTitle:title])
3661 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3662 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3663 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3665 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3669 - (void) setDelegate:(id)delegate {
3670 delegate_ = delegate;
3671 status_.setDelegate(delegate);
3672 progress_.setDelegate(delegate);
3675 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3676 SourceMap::const_iterator i(sources_.find(file->ID));
3677 return i == sources_.end() ? nil : i->second;
3680 - (NSString *) mappedSectionForPointer:(const char *)section {
3681 _H<NSString> *mapped;
3683 _profile(Database$mappedSectionForPointer$Cache)
3684 mapped = §ions_[section];
3687 if (*mapped == NULL) {
3688 size_t length(strlen(section));
3689 char spaced[length + 1];
3691 _profile(Database$mappedSectionForPointer$Replace)
3692 for (size_t index(0); index != length; ++index)
3693 spaced[index] = section[index] == '_' ? ' ' : section[index];
3694 spaced[length] = '\0';
3699 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3700 string = [NSString stringWithUTF8String:spaced];
3703 _profile(Database$mappedSectionForPointer$Map)
3704 string = [SectionMap_ objectForKey:string] ?: string;
3714 /* Web Scripting {{{ */
3715 @interface CydiaObject : NSObject {
3717 _transient id delegate_;
3720 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3723 @implementation CydiaObject
3726 [indirect_ release];
3730 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3731 if ((self = [super init]) != nil) {
3732 indirect_ = [indirect retain];
3736 - (void) setDelegate:(id)delegate {
3737 delegate_ = delegate;
3740 + (NSArray *) _attributeKeys {
3741 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3744 - (NSArray *) attributeKeys {
3745 return [[self class] _attributeKeys];
3748 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3749 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3752 - (NSString *) device {
3753 return [[UIDevice currentDevice] uniqueIdentifier];
3756 #if 0 // XXX: implement!
3757 - (NSString *) mac {
3758 if (![indirect_ promptForSensitive:@"Mac Address"])
3762 - (NSString *) serial {
3763 if (![indirect_ promptForSensitive:@"Serial #"])
3767 - (NSString *) firewire {
3768 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3772 - (NSString *) imei {
3773 if (![indirect_ promptForSensitive:@"IMEI"])
3778 + (NSString *) webScriptNameForSelector:(SEL)selector {
3779 if (selector == @selector(close))
3781 else if (selector == @selector(getInstalledPackages))
3782 return @"getInstalledPackages";
3783 else if (selector == @selector(getPackageById:))
3784 return @"getPackageById";
3785 else if (selector == @selector(installPackages:))
3786 return @"installPackages";
3787 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3788 return @"setButtonImage";
3789 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3790 return @"setButtonTitle";
3791 else if (selector == @selector(setPopupHook:))
3792 return @"setPopupHook";
3793 else if (selector == @selector(setSpecial:))
3794 return @"setSpecial";
3795 else if (selector == @selector(setToken:))
3797 else if (selector == @selector(setViewportWidth:))
3798 return @"setViewportWidth";
3799 else if (selector == @selector(supports:))
3801 else if (selector == @selector(stringWithFormat:arguments:))
3803 else if (selector == @selector(localizedStringForKey:value:table:))
3805 else if (selector == @selector(du:))
3807 else if (selector == @selector(statfs:))
3813 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3814 return [self webScriptNameForSelector:selector] == nil;
3817 - (BOOL) supports:(NSString *)feature {
3818 return [feature isEqualToString:@"window.open"];
3821 - (NSArray *) getInstalledPackages {
3822 NSArray *packages([[Database sharedInstance] packages]);
3823 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3824 for (Package *package in packages)
3825 if ([package installed] != nil)
3826 [installed addObject:package];
3830 - (Package *) getPackageById:(NSString *)id {
3831 Package *package([[Database sharedInstance] packageWithName:id]);
3836 - (NSArray *) statfs:(NSString *)path {
3839 if (path == nil || statfs([path UTF8String], &stat) == -1)
3842 return [NSArray arrayWithObjects:
3843 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3844 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3845 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3849 - (NSNumber *) du:(NSString *)path {
3850 NSNumber *value(nil);
3853 _assert(pipe(fds) != -1);
3855 pid_t pid(ExecFork());
3857 _assert(dup2(fds[1], 1) != -1);
3858 _assert(close(fds[0]) != -1);
3859 _assert(close(fds[1]) != -1);
3860 /* XXX: this should probably not use du */
3861 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3866 _assert(close(fds[1]) != -1);
3868 if (FILE *du = fdopen(fds[0], "r")) {
3870 while (fgets(line, sizeof(line), du) != NULL) {
3871 size_t length(strlen(line));
3872 while (length != 0 && line[length - 1] == '\n')
3873 line[--length] = '\0';
3874 if (char *tab = strchr(line, '\t')) {
3876 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3881 } else _assert(close(fds[0]));
3885 if (waitpid(pid, &status, 0) == -1)
3888 else _assert(false);
3897 - (void) installPackages:(NSArray *)packages {
3898 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3901 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3902 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3905 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3906 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3909 - (void) setSpecial:(id)function {
3910 [indirect_ setSpecial:function];
3913 - (void) setToken:(NSString *)token {
3916 Token_ = [token retain];
3918 [Metadata_ setObject:Token_ forKey:@"Token"];
3922 - (void) setPopupHook:(id)function {
3923 [indirect_ setPopupHook:function];
3926 - (void) setViewportWidth:(float)width {
3927 [indirect_ setViewportWidth:width];
3930 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3931 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3932 unsigned count([arguments count]);
3934 for (unsigned i(0); i != count; ++i)
3935 values[i] = [arguments objectAtIndex:i];
3936 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3939 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3940 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3942 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3944 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3950 /* @ Loading... Indicator {{{ */
3951 @interface CYLoadingIndicator : UIView {
3952 UIActivityIndicatorView *spinner_;
3957 @property (readonly, nonatomic) UILabel *label;
3958 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
3962 @implementation CYLoadingIndicator
3964 - (id)initWithFrame:(CGRect)frame {
3965 if ((self = [super initWithFrame:frame])) {
3966 container_ = [[[UIView alloc] init] autorelease];
3967 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
3969 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
3970 [spinner_ startAnimating];
3971 [container_ addSubview:spinner_];
3973 label_ = [[[UILabel alloc] init] autorelease];
3974 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
3975 [label_ setBackgroundColor:[UIColor clearColor]];
3976 [label_ setTextColor:[UIColor blackColor]];
3977 [label_ setShadowColor:[UIColor whiteColor]];
3978 [label_ setShadowOffset:CGSizeMake(0, 1)];
3979 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
3980 [container_ addSubview:label_];
3982 CGSize viewsize = frame.size;
3983 CGSize spinnersize = [spinner_ bounds].size;
3984 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
3985 float bothwidth = spinnersize.width + textsize.width + 5.0f;
3987 CGRect containrect = {
3988 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
3989 CGSizeMake(bothwidth, spinnersize.height)
3992 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4000 [container_ setFrame:containrect];
4001 [spinner_ setFrame:spinrect];
4002 [label_ setFrame:textrect];
4003 [self addSubview:container_];
4009 - (UILabel *)label { return label_; }
4010 - (UIActivityIndicatorView *)activityIndicatorView { return spinner_; }
4014 /* Emulated Loading Controller {{{ */
4015 @interface CYEmulatedLoadingController : CYViewController <
4017 ConfigurationDelegate
4019 _transient Database *database_;
4020 CYLoadingIndicator *indicator_;
4022 UINavigationBar *navbar_;
4026 @implementation CYEmulatedLoadingController
4029 [self releaseSubviews];
4030 [database_ setDelegate:nil];
4035 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4036 CYAlertView *sheet([[[CYAlertView alloc]
4038 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4039 defaultButtonIndex:0
4042 [sheet setMessage:error];
4043 [sheet yieldToPopupAlertAnimated:YES];
4047 - (void) setProgressTitle:(NSString *)title { }
4048 - (void) setProgressPercent:(float)percent { }
4049 - (void) startProgress { }
4050 - (void) addProgressOutput:(NSString *)output { }
4051 - (bool) isCancelling:(size_t)received { return NO; }
4052 - (void) setConfigurationData:(NSString *)data { }
4054 - (void) repairWithSelector:(SEL)selector {
4055 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("REPAIRING"), nil] waitUntilDone:YES];
4056 [database_ performSelector:selector];
4058 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil] waitUntilDone:YES];
4061 - (id) initWithDatabase:(Database *)database {
4062 if ((self = [super init])) {
4063 database_ = database;
4064 [database_ setDelegate:self];
4069 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4070 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4072 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4073 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4074 [[self view] addSubview:indicator_];
4076 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4077 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4078 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4079 [[self view] addSubview:tabbar_];
4081 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4082 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4083 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4084 [[self view] addSubview:navbar_];
4087 - (void) releaseSubviews {
4088 [indicator_ release];
4101 /* Cydia Browser Controller {{{ */
4102 @interface CYBrowserController : BrowserController {
4103 CydiaObject *cydia_;
4108 @implementation CYBrowserController
4115 - (NSURL *) navigationURL {
4116 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4119 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4122 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4123 [super webView:view didClearWindowObject:window forFrame:frame];
4125 WebDataSource *source([frame dataSource]);
4126 NSURLResponse *response([source response]);
4128 NSURL *url([response URL]);
4129 NSString *scheme([url scheme]);
4130 NSString *host([url host]);
4132 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4133 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4134 NSDictionary *headers([http allHeaderFields]);
4135 [self setHeaders:headers forHost:host];
4139 [host isEqualToString:@"cydia.saurik.com"] ||
4140 [host hasSuffix:@".cydia.saurik.com"] ||
4141 [scheme isEqualToString:@"file"]
4143 [window setValue:cydia_ forKey:@"cydia"];
4146 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4147 if (System_ != NULL)
4148 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4149 if (Machine_ != NULL)
4150 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4152 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4154 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4157 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4158 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4159 [self _setMoreHeaders:copy];
4163 - (void) setDelegate:(id)delegate {
4164 [super setDelegate:delegate];
4165 [cydia_ setDelegate:delegate];
4169 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4170 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4172 WebView *webview([[webview_ _documentView] webView]);
4174 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4176 NSString *application = package == nil ? @"Cydia" : [NSString
4177 stringWithFormat:@"Cydia/%@",
4182 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4184 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4185 if (Product_ != nil)
4186 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4188 [webview setApplicationNameForUserAgent:application];
4195 /* Confirmation Controller {{{ */
4196 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4197 if (!iterator.end())
4198 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4199 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4201 pkgCache::PkgIterator package(dep.TargetPkg());
4204 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4211 @protocol ConfirmationControllerDelegate
4212 - (void) cancelAndClear:(bool)clear;
4213 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4217 @interface ConfirmationController : CYBrowserController {
4218 _transient Database *database_;
4219 UIAlertView *essential_;
4226 - (id) initWithDatabase:(Database *)database;
4230 @implementation ConfirmationController
4237 if (essential_ != nil)
4238 [essential_ release];
4242 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4243 NSString *context([alert context]);
4245 if ([context isEqualToString:@"remove"]) {
4246 if (button == [alert cancelButtonIndex]) {
4247 [self dismissModalViewControllerAnimated:YES];
4248 } else if (button == [alert firstOtherButtonIndex]) {
4251 [delegate_ confirmWithNavigationController:[self navigationController]];
4254 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4255 } else if ([context isEqualToString:@"unable"]) {
4256 [self dismissModalViewControllerAnimated:YES];
4257 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4259 [super alertView:alert clickedButtonAtIndex:button];
4263 - (void) _doContinue {
4264 [self dismissModalViewControllerAnimated:YES];
4265 [delegate_ cancelAndClear:NO];
4268 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4269 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4273 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4274 [super webView:view didClearWindowObject:window forFrame:frame];
4275 [window setValue:changes_ forKey:@"changes"];
4276 [window setValue:issues_ forKey:@"issues"];
4277 [window setValue:sizes_ forKey:@"sizes"];
4278 [window setValue:self forKey:@"queue"];
4281 - (id) initWithDatabase:(Database *)database {
4282 if ((self = [super init]) != nil) {
4283 database_ = database;
4285 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4287 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4288 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4289 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4290 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4291 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4295 pkgDepCache::Policy *policy([database_ policy]);
4297 pkgCacheFile &cache([database_ cache]);
4298 NSArray *packages = [database_ packages];
4299 for (Package *package in packages) {
4300 pkgCache::PkgIterator iterator = [package iterator];
4301 pkgDepCache::StateCache &state(cache[iterator]);
4303 NSString *name([package name]);
4305 if (state.NewInstall())
4306 [installing addObject:name];
4307 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4308 [reinstalling addObject:name];
4309 else if (state.Upgrade())
4310 [upgrading addObject:name];
4311 else if (state.Downgrade())
4312 [downgrading addObject:name];
4313 else if (state.Delete()) {
4314 if ([package essential])
4316 [removing addObject:name];
4319 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4320 substrate_ |= DepSubstrate(iterator.CurrentVer());
4325 else if (Advanced_) {
4326 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4328 essential_ = [[UIAlertView alloc]
4329 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4330 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4332 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4333 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4336 [essential_ setContext:@"remove"];
4338 essential_ = [[UIAlertView alloc]
4339 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4340 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4342 cancelButtonTitle:UCLocalize("OKAY")
4343 otherButtonTitles:nil
4346 [essential_ setContext:@"unable"];
4349 changes_ = [[NSArray alloc] initWithObjects:
4357 issues_ = [database_ issues];
4359 issues_ = [issues_ retain];
4361 sizes_ = [[NSArray alloc] initWithObjects:
4362 SizeString([database_ fetcher].FetchNeeded()),
4363 SizeString([database_ fetcher].PartialPresent()),
4366 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4368 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4369 initWithTitle:UCLocalize("CANCEL")
4370 style:UIBarButtonItemStylePlain
4372 action:@selector(cancelButtonClicked)
4377 - (void) applyRightButton {
4379 if (issues_ == nil && ![self isLoading])
4380 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4381 initWithTitle:UCLocalize("CONFIRM")
4382 style:UIBarButtonItemStyleDone
4384 action:@selector(confirmButtonClicked)
4387 [super applyRightButton];
4389 [[self navigationItem] setRightBarButtonItem:nil];
4393 - (void) cancelButtonClicked {
4394 [self dismissModalViewControllerAnimated:YES];
4395 [delegate_ cancelAndClear:YES];
4399 - (void) confirmButtonClicked {
4400 if (essential_ != nil)
4405 [delegate_ confirmWithNavigationController:[self navigationController]];
4413 /* Progress Data {{{ */
4414 @interface ProgressData : NSObject {
4416 // XXX: should these really both be _transient?
4417 _transient id target_;
4418 _transient id object_;
4421 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4428 @implementation ProgressData
4430 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4431 if ((self = [super init]) != nil) {
4432 selector_ = selector;
4452 /* Progress Controller {{{ */
4453 @interface ProgressController : CYViewController <
4454 ConfigurationDelegate,
4457 _transient Database *database_;
4458 UIProgressBar *progress_;
4459 UITextView *output_;
4460 UITextLabel *status_;
4461 UIPushButton *close_;
4463 SHA1SumValue springlist_;
4464 SHA1SumValue notifyconf_;
4468 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4470 - (void) _retachThread;
4471 - (void) _detachNewThreadData:(ProgressData *)data;
4472 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4478 @protocol ProgressControllerDelegate
4479 - (void) progressControllerIsComplete:(ProgressController *)sender;
4482 @implementation ProgressController
4485 [database_ setDelegate:nil];
4486 [progress_ release];
4495 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4496 if ((self = [super init]) != nil) {
4497 database_ = database;
4498 [database_ setDelegate:self];
4499 delegate_ = delegate;
4501 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4503 progress_ = [[UIProgressBar alloc] init];
4504 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4505 [progress_ setStyle:0];
4507 status_ = [[UITextLabel alloc] init];
4508 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4509 [status_ setColor:[UIColor whiteColor]];
4510 [status_ setBackgroundColor:[UIColor clearColor]];
4511 [status_ setCentersHorizontally:YES];
4512 //[status_ setFont:font];
4514 output_ = [[UITextView alloc] init];
4515 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4516 //[output_ setTextFont:@"Courier New"];
4517 [output_ setFont:[[output_ font] fontWithSize:12]];
4518 [output_ setTextColor:[UIColor whiteColor]];
4519 [output_ setBackgroundColor:[UIColor clearColor]];
4520 [output_ setMarginTop:0];
4521 [output_ setAllowsRubberBanding:YES];
4522 [output_ setEditable:NO];
4523 [[self view] addSubview:output_];
4525 close_ = [[UIPushButton alloc] init];
4526 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4527 [close_ setAutosizesToFit:NO];
4528 [close_ setDrawsShadow:YES];
4529 [close_ setStretchBackground:YES];
4530 [close_ setEnabled:YES];
4531 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4532 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4533 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4534 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4538 - (void) positionViews {
4539 CGRect bounds = [[self view] bounds];
4540 CGSize prgsize = [UIProgressBar defaultSize];
4543 (bounds.size.width - prgsize.width) / 2,
4544 bounds.size.height - prgsize.height - 20
4547 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4549 [progress_ setFrame:prgrect];
4550 [status_ setFrame:CGRectMake(
4552 bounds.size.height - prgsize.height - 50,
4553 bounds.size.width - 20,
4556 [output_ setFrame:CGRectMake(
4559 bounds.size.width - 20,
4560 bounds.size.height - 96
4562 [close_ setFrame:CGRectMake(
4563 (bounds.size.width - closewidth) / 2,
4564 bounds.size.height - prgsize.height - 50,
4570 - (void) viewWillAppear:(BOOL)animated {
4571 [super viewDidAppear:animated];
4572 [[self navigationItem] setHidesBackButton:YES];
4573 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4575 [self positionViews];
4578 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4579 [self positionViews];
4582 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4583 NSString *context([alert context]);
4585 if ([context isEqualToString:@"conffile"]) {
4586 FILE *input = [database_ input];
4587 if (button == [alert cancelButtonIndex])
4588 fprintf(input, "N\n");
4589 else if (button == [alert firstOtherButtonIndex])
4590 fprintf(input, "Y\n");
4595 - (void) closeButtonPushed {
4598 UpdateExternalStatus(0);
4602 [self dismissModalViewControllerAnimated:YES];
4606 [delegate_ terminateWithSuccess];
4607 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4608 [delegate_ suspendWithAnimation:YES];
4610 [delegate_ suspend];*/
4622 system("/usr/bin/sbreload");
4628 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4629 SBReboot(SBSSpringBoardServerPort());
4631 reboot2(RB_AUTOBOOT);
4636 - (void) _retachThread {
4637 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4639 [[self view] addSubview:close_];
4640 [progress_ removeFromSuperview];
4641 [status_ removeFromSuperview];
4643 [database_ popErrorWithTitle:title_];
4644 [delegate_ progressControllerIsComplete:self];
4648 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4651 MMap mmap(file, MMap::ReadOnly);
4653 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4654 if (!(notifyconf_ == sha1.Result()))
4661 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4664 MMap mmap(file, MMap::ReadOnly);
4666 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4667 if (!(springlist_ == sha1.Result()))
4673 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4674 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4675 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4676 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4677 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4681 system("su -c /usr/bin/uicache mobile");
4684 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4686 [delegate_ setStatusBarShowsProgress:NO];
4689 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4690 [[data target] performSelector:[data selector] withObject:[data object]];
4691 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4694 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4695 UpdateExternalStatus(1);
4702 title_ = [title retain];
4704 [[self navigationItem] setTitle:title_];
4706 [status_ setText:nil];
4707 [output_ setText:@""];
4708 [progress_ setProgress:0];
4710 [close_ removeFromSuperview];
4711 [[self view] addSubview:progress_];
4712 [[self view] addSubview:status_];
4714 [delegate_ setStatusBarShowsProgress:YES];
4719 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4722 MMap mmap(file, MMap::ReadOnly);
4724 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4725 notifyconf_ = sha1.Result();
4731 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4734 MMap mmap(file, MMap::ReadOnly);
4736 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4737 springlist_ = sha1.Result();
4742 detachNewThreadSelector:@selector(_detachNewThreadData:)
4744 withObject:[[[ProgressData alloc]
4745 initWithSelector:selector
4752 - (void) repairWithSelector:(SEL)selector {
4754 detachNewThreadSelector:selector
4757 title:UCLocalize("REPAIRING")
4761 - (void) setConfigurationData:(NSString *)data {
4763 performSelectorOnMainThread:@selector(_setConfigurationData:)
4769 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4770 CYAlertView *sheet([[[CYAlertView alloc]
4772 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4773 defaultButtonIndex:0
4776 [sheet setMessage:error];
4777 [sheet yieldToPopupAlertAnimated:YES];
4781 - (void) setProgressTitle:(NSString *)title {
4783 performSelectorOnMainThread:@selector(_setProgressTitle:)
4789 - (void) setProgressPercent:(float)percent {
4791 performSelectorOnMainThread:@selector(_setProgressPercent:)
4792 withObject:[NSNumber numberWithFloat:percent]
4797 - (void) startProgress {
4800 - (void) addProgressOutput:(NSString *)output {
4802 performSelectorOnMainThread:@selector(_addProgressOutput:)
4808 - (bool) isCancelling:(size_t)received {
4812 - (void) _setConfigurationData:(NSString *)data {
4813 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4815 if (!conffile_r(data)) {
4816 lprintf("E:invalid conffile\n");
4820 NSString *ofile = conffile_r[1];
4821 //NSString *nfile = conffile_r[2];
4823 UIAlertView *alert = [[[UIAlertView alloc]
4824 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4825 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4827 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4828 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4829 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4833 [alert setContext:@"conffile"];
4837 - (void) _setProgressTitle:(NSString *)title {
4838 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4839 for (size_t i(0), e([words count]); i != e; ++i) {
4840 NSString *word([words objectAtIndex:i]);
4841 if (Package *package = [database_ packageWithName:word])
4842 [words replaceObjectAtIndex:i withObject:[package name]];
4845 [status_ setText:[words componentsJoinedByString:@" "]];
4848 - (void) _setProgressPercent:(NSNumber *)percent {
4849 [progress_ setProgress:[percent floatValue]];
4852 - (void) _addProgressOutput:(NSString *)output {
4853 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4854 CGSize size = [output_ contentSize];
4855 CGPoint offset = [output_ contentOffset];
4856 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4857 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4858 [output_ scrollRectToVisible:rect animated:YES];
4862 - (BOOL) isRunning {
4869 /* Cell Content View {{{ */
4870 @protocol ContentDelegate
4871 - (void) drawContentRect:(CGRect)rect;
4874 @interface ContentView : UIView {
4875 _transient id<ContentDelegate> delegate_;
4880 @implementation ContentView
4882 - (id) initWithFrame:(CGRect)frame {
4883 if ((self = [super initWithFrame:frame]) != nil) {
4884 [self setNeedsDisplayOnBoundsChange:YES];
4888 - (void) setDelegate:(id<ContentDelegate>)delegate {
4889 delegate_ = delegate;
4892 - (void) drawRect:(CGRect)rect {
4893 [super drawRect:rect];
4894 [delegate_ drawContentRect:rect];
4899 /* Cydia TableView Cell {{{ */
4900 @interface CYTableViewCell : UITableViewCell {
4901 ContentView *content_;
4907 @implementation CYTableViewCell
4914 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4915 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4917 if (view == content_) {
4918 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4919 highlighted_ = highlighted;
4922 [super _updateHighlightColorsForView:view highlighted:highlighted];
4925 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4926 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4927 highlighted_ = selected;
4929 [super setSelected:selected animated:animated];
4930 [content_ setNeedsDisplay];
4936 /* Package Cell {{{ */
4937 @interface PackageCell : CYTableViewCell <
4942 NSString *description_;
4950 - (PackageCell *) init;
4951 - (void) setPackage:(Package *)package;
4953 - (void) drawContentRect:(CGRect)rect;
4957 @implementation PackageCell
4959 - (void) clearPackage {
4970 if (description_ != nil) {
4971 [description_ release];
4975 if (source_ != nil) {
4980 if (badge_ != nil) {
4985 if (placard_ != nil) {
4995 [self clearPackage];
4999 - (PackageCell *) init {
5000 CGRect frame(CGRectMake(0, 0, 320, 74));
5001 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5002 UIView *content([self contentView]);
5003 CGRect bounds([content bounds]);
5005 content_ = [[ContentView alloc] initWithFrame:bounds];
5006 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5007 [content addSubview:content_];
5009 [content_ setDelegate:self];
5010 [content_ setOpaque:YES];
5014 - (NSString *) accessibilityLabel {
5015 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5018 - (void) setPackage:(Package *)package {
5019 [self clearPackage];
5022 Source *source = [package source];
5024 icon_ = [[package icon] retain];
5025 name_ = [[package name] retain];
5028 description_ = [package longDescription];
5029 if (description_ == nil)
5030 description_ = [package shortDescription];
5031 if (description_ != nil)
5032 description_ = [description_ retain];
5034 commercial_ = [package isCommercial];
5036 package_ = [package retain];
5038 NSString *label = nil;
5039 bool trusted = false;
5041 if (source != nil) {
5042 label = [source label];
5043 trusted = [source trusted];
5044 } else if ([[package id] isEqualToString:@"firmware"])
5045 label = UCLocalize("APPLE");
5047 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5049 NSString *from(label);
5051 NSString *section = [package simpleSection];
5052 if (section != nil && ![section isEqualToString:label]) {
5053 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5054 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5057 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5058 source_ = [from retain];
5060 if (NSString *purpose = [package primaryPurpose])
5061 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5062 badge_ = [badge_ retain];
5067 if (NSString *mode = [package_ mode]) {
5068 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5069 color = RemovingColor_;
5070 //placard = @"removing";
5072 color = InstallingColor_;
5073 //placard = @"installing";
5076 // XXX: the removing/installing placards are not @2x
5079 color = [UIColor whiteColor];
5081 if ([package installed] != nil)
5082 placard = @"installed";
5087 [content_ setBackgroundColor:color];
5090 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5091 placard_ = [placard_ retain];
5093 [self setNeedsDisplay];
5094 [content_ setNeedsDisplay];
5097 - (void) drawContentRect:(CGRect)rect {
5098 bool highlighted(highlighted_);
5099 float width([self bounds].size.width);
5102 CGContextRef context(UIGraphicsGetCurrentContext());
5103 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5104 CGContextFillRect(context, rect);
5109 rect.size = [icon_ size];
5111 rect.size.width /= 2;
5112 rect.size.height /= 2;
5114 rect.origin.x = 25 - rect.size.width / 2;
5115 rect.origin.y = 25 - rect.size.height / 2;
5117 [icon_ drawInRect:rect];
5120 if (badge_ != nil) {
5122 rect.size = [badge_ size];
5124 rect.size.width /= 2;
5125 rect.size.height /= 2;
5127 rect.origin.x = 36 - rect.size.width / 2;
5128 rect.origin.y = 36 - rect.size.height / 2;
5130 [badge_ drawInRect:rect];
5137 UISetColor(commercial_ ? Purple_ : Black_);
5138 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5139 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5142 UISetColor(commercial_ ? Purplish_ : Gray_);
5143 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5145 if (placard_ != nil)
5146 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5151 /* Section Cell {{{ */
5152 @interface SectionCell : CYTableViewCell <
5164 - (void) setSection:(Section *)section editing:(BOOL)editing;
5168 @implementation SectionCell
5170 - (void) clearSection {
5171 if (basic_ != nil) {
5176 if (section_ != nil) {
5186 if (count_ != nil) {
5193 [self clearSection];
5199 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5200 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5201 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5202 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5203 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5205 UIView *content([self contentView]);
5206 CGRect bounds([content bounds]);
5208 content_ = [[ContentView alloc] initWithFrame:bounds];
5209 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5210 [content addSubview:content_];
5211 [content_ setBackgroundColor:[UIColor whiteColor]];
5213 [content_ setDelegate:self];
5217 - (void) onSwitch:(id)sender {
5218 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5219 if (metadata == nil) {
5220 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5221 [Sections_ setObject:metadata forKey:basic_];
5224 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5228 - (void) setSection:(Section *)section editing:(BOOL)editing {
5229 if (editing != editing_) {
5231 [switch_ removeFromSuperview];
5233 [self addSubview:switch_];
5237 [self clearSection];
5239 if (section == nil) {
5240 name_ = [UCLocalize("ALL_PACKAGES") retain];
5243 basic_ = [section name];
5245 basic_ = [basic_ retain];
5247 section_ = [section localized];
5248 if (section_ != nil)
5249 section_ = [section_ retain];
5251 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5252 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5255 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5258 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5259 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5261 [content_ setNeedsDisplay];
5264 - (void) setFrame:(CGRect)frame {
5265 [super setFrame:frame];
5267 CGRect rect([switch_ frame]);
5268 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5271 - (NSString *) accessibilityLabel {
5275 - (void) drawContentRect:(CGRect)rect {
5276 bool highlighted(highlighted_ && !editing_);
5278 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5283 float width(rect.size.width);
5289 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5291 CGSize size = [count_ sizeWithFont:Font14_];
5295 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5301 /* File Table {{{ */
5302 @interface FileTable : CYViewController <
5303 UITableViewDataSource,
5306 _transient Database *database_;
5309 NSMutableArray *files_;
5313 - (id) initWithDatabase:(Database *)database;
5314 - (void) setPackage:(Package *)package;
5318 @implementation FileTable
5321 [self releaseSubviews];
5330 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5331 return files_ == nil ? 0 : [files_ count];
5334 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5338 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5339 static NSString *reuseIdentifier = @"Cell";
5341 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5343 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5344 [cell setFont:[UIFont systemFontOfSize:16]];
5346 [cell setText:[files_ objectAtIndex:indexPath.row]];
5347 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5352 - (NSURL *) navigationURL {
5353 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5357 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5359 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5360 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5361 [list_ setRowHeight:24.0f];
5362 [list_ setDataSource:self];
5363 [list_ setDelegate:self];
5364 [[self view] addSubview:list_];
5367 - (void) viewDidLoad {
5368 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5371 - (void) releaseSubviews {
5376 - (id) initWithDatabase:(Database *)database {
5377 if ((self = [super init]) != nil) {
5378 database_ = database;
5380 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5384 - (void) setPackage:(Package *)package {
5385 if (package_ != nil) {
5386 [package_ autorelease];
5395 [files_ removeAllObjects];
5397 if (package != nil) {
5398 package_ = [package retain];
5399 name_ = [[package id] retain];
5401 if (NSArray *files = [package files])
5402 [files_ addObjectsFromArray:files];
5404 if ([files_ count] != 0) {
5405 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5406 [files_ removeObjectAtIndex:0];
5407 [files_ sortUsingSelector:@selector(compareByPath:)];
5409 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5410 [stack addObject:@"/"];
5412 for (int i(0), e([files_ count]); i != e; ++i) {
5413 NSString *file = [files_ objectAtIndex:i];
5414 while (![file hasPrefix:[stack lastObject]])
5415 [stack removeLastObject];
5416 NSString *directory = [stack lastObject];
5417 [stack addObject:[file stringByAppendingString:@"/"]];
5418 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5419 ([stack count] - 2) * 3, "",
5420 [file substringFromIndex:[directory length]]
5429 - (void) reloadData {
5432 [self setPackage:[database_ packageWithName:name_]];
5437 /* Package Controller {{{ */
5438 @interface CYPackageController : CYBrowserController <
5439 UIActionSheetDelegate
5441 _transient Database *database_;
5445 NSMutableArray *buttons_;
5446 UIBarButtonItem *button_;
5449 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5453 @implementation CYPackageController
5456 if (package_ != nil)
5469 - (NSURL *) navigationURL {
5470 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5473 /* XXX: this is not safe at all... localization of /fail/ */
5474 - (void) _clickButtonWithName:(NSString *)name {
5475 if ([name isEqualToString:UCLocalize("CLEAR")])
5476 [delegate_ clearPackage:package_];
5477 else if ([name isEqualToString:UCLocalize("INSTALL")])
5478 [delegate_ installPackage:package_];
5479 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5480 [delegate_ installPackage:package_];
5481 else if ([name isEqualToString:UCLocalize("REMOVE")])
5482 [delegate_ removePackage:package_];
5483 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5484 [delegate_ installPackage:package_];
5485 else _assert(false);
5488 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5489 NSString *context([sheet context]);
5491 if ([context isEqualToString:@"modify"]) {
5492 if (button != [sheet cancelButtonIndex]) {
5493 NSString *buttonName = [buttons_ objectAtIndex:button];
5494 [self _clickButtonWithName:buttonName];
5497 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5501 - (bool) _allowJavaScriptPanel {
5506 - (void) _customButtonClicked {
5507 int count([buttons_ count]);
5512 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5514 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5515 [buttons addObjectsFromArray:buttons_];
5517 UIActionSheet *sheet = [[[UIActionSheet alloc]
5520 cancelButtonTitle:nil
5521 destructiveButtonTitle:nil
5522 otherButtonTitles:nil
5525 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5527 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5528 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5530 [sheet setContext:@"modify"];
5532 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5536 // We don't want to allow non-commercial packages to do custom things to the install button,
5537 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5538 - (void) customButtonClicked {
5540 [super customButtonClicked];
5542 [self _customButtonClicked];
5545 - (void) reloadButtonClicked {
5546 // Don't reload a commerical package by tapping the loading button,
5547 // but if it's not an Install button, we should forward it on.
5548 if (![package_ uninstalled])
5549 [self _customButtonClicked];
5552 - (void) applyLoadingTitle {
5553 // Don't show "Loading" as the title. Ever.
5556 - (UIBarButtonItem *) rightButton {
5561 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5562 if ((self = [super init]) != nil) {
5563 database_ = database;
5564 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5565 name_ = [[NSString alloc] initWithString:name];
5569 - (void) reloadData {
5572 if (package_ != nil)
5573 [package_ autorelease];
5574 package_ = [database_ packageWithName:name_];
5576 [buttons_ removeAllObjects];
5578 if (package_ != nil) {
5581 package_ = [package_ retain];
5582 commercial_ = [package_ isCommercial];
5584 if ([package_ mode] != nil)
5585 [buttons_ addObject:UCLocalize("CLEAR")];
5586 if ([package_ source] == nil);
5587 else if ([package_ upgradableAndEssential:NO])
5588 [buttons_ addObject:UCLocalize("UPGRADE")];
5589 else if ([package_ uninstalled])
5590 [buttons_ addObject:UCLocalize("INSTALL")];
5592 [buttons_ addObject:UCLocalize("REINSTALL")];
5593 if (![package_ uninstalled])
5594 [buttons_ addObject:UCLocalize("REMOVE")];
5601 switch ([buttons_ count]) {
5602 case 0: title = nil; break;
5603 case 1: title = [buttons_ objectAtIndex:0]; break;
5604 default: title = UCLocalize("MODIFY"); break;
5607 button_ = [[UIBarButtonItem alloc]
5609 style:UIBarButtonItemStylePlain
5611 action:@selector(customButtonClicked)
5614 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5617 - (bool) isLoading {
5618 return commercial_ ? [super isLoading] : false;
5624 /* Package List Controller {{{ */
5625 @interface PackageListController : CYViewController <
5626 UITableViewDataSource,
5629 _transient Database *database_;
5631 NSMutableArray *packages_;
5632 NSMutableArray *sections_;
5634 NSMutableArray *index_;
5635 NSMutableDictionary *indices_;
5639 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5640 - (void) setDelegate:(id)delegate;
5641 - (void) resetCursor;
5645 @implementation PackageListController
5648 [packages_ release];
5649 [sections_ release];
5658 - (void) deselectWithAnimation:(BOOL)animated {
5659 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5662 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5663 CGRect base = [[self view] bounds];
5664 base.size.height -= bounds.size.height;
5665 base.origin = [list_ frame].origin;
5667 [UIView beginAnimations:nil context:NULL];
5668 [UIView setAnimationBeginsFromCurrentState:YES];
5669 [UIView setAnimationCurve:curve];
5670 [UIView setAnimationDuration:duration];
5671 [list_ setFrame:base];
5672 [UIView commitAnimations];
5675 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5676 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5679 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5680 [self resizeForKeyboardBounds:bounds duration:0];
5683 - (void) keyboardWillShow:(NSNotification *)notification {
5686 NSTimeInterval duration;
5687 UIViewAnimationCurve curve;
5688 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5689 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5690 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5691 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5693 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);
5694 UIViewController *base = self;
5695 while ([base parentViewController] != nil)
5696 base = [base parentViewController];
5697 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5698 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5700 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5703 - (void) keyboardWillHide:(NSNotification *)notification {
5704 NSTimeInterval duration;
5705 UIViewAnimationCurve curve;
5706 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5707 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5709 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5712 - (void) viewWillAppear:(BOOL)animated {
5713 [super viewWillAppear:animated];
5715 [self resizeForKeyboardBounds:CGRectZero];
5716 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5717 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5720 - (void) viewWillDisappear:(BOOL)animated {
5721 [super viewWillDisappear:animated];
5723 [self resizeForKeyboardBounds:CGRectZero];
5724 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5725 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5728 - (void) viewDidAppear:(BOOL)animated {
5729 [super viewDidAppear:animated];
5730 [self deselectWithAnimation:animated];
5733 - (void) didSelectPackage:(Package *)package {
5734 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5735 [view setDelegate:delegate_];
5736 [[self navigationController] pushViewController:view animated:YES];
5739 #if TryIndexedCollation
5740 + (BOOL) hasIndexedCollation {
5741 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5745 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5746 NSInteger count([sections_ count]);
5747 return count == 0 ? 1 : count;
5750 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5751 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5753 return [[sections_ objectAtIndex:section] name];
5756 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5757 if ([sections_ count] == 0)
5759 return [[sections_ objectAtIndex:section] count];
5762 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5763 @synchronized (database_) {
5764 if ([database_ era] != era_)
5767 Section *section([sections_ objectAtIndex:[path section]]);
5768 NSInteger row([path row]);
5769 Package *package([packages_ objectAtIndex:([section row] + row)]);
5770 return [[package retain] autorelease];
5773 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5774 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5776 cell = [[[PackageCell alloc] init] autorelease];
5777 [cell setPackage:[self packageAtIndexPath:path]];
5781 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5782 Package *package([self packageAtIndexPath:path]);
5783 package = [database_ packageWithName:[package id]];
5784 [self didSelectPackage:package];
5787 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5788 // XXX: is 20 the most optimal number here?
5789 return [packages_ count] > 20 ? index_ : nil;
5792 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5793 #if TryIndexedCollation
5794 if ([[self class] hasIndexedCollation]) {
5795 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5802 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5803 if ((self = [super init]) != nil) {
5804 database_ = database;
5805 title_ = [title copy];
5806 [[self navigationItem] setTitle:title_];
5808 #if TryIndexedCollation
5809 if ([[self class] hasIndexedCollation])
5810 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
5813 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5815 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5817 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5818 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5820 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
5821 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5822 [list_ setRowHeight:73];
5823 [[self view] addSubview:list_];
5825 [list_ setDataSource:self];
5826 [list_ setDelegate:self];
5830 - (void) setDelegate:(id)delegate {
5831 delegate_ = delegate;
5834 - (bool) hasPackage:(Package *)package {
5838 - (void) reloadData {
5841 era_ = [database_ era];
5842 NSArray *packages = [database_ packages];
5844 [packages_ removeAllObjects];
5845 [sections_ removeAllObjects];
5847 _profile(PackageTable$reloadData$Filter)
5848 for (Package *package in packages)
5849 if ([self hasPackage:package])
5850 [packages_ addObject:package];
5853 [indices_ removeAllObjects];
5855 Section *section = nil;
5857 #if TryIndexedCollation
5858 if ([[self class] hasIndexedCollation]) {
5859 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5860 NSArray *titles = [collation sectionIndexTitles];
5863 _profile(PackageTable$reloadData$Section)
5864 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5868 _profile(PackageTable$reloadData$Section$Package)
5869 package = [packages_ objectAtIndex:offset];
5870 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5873 while (secidx < index) {
5876 _profile(PackageTable$reloadData$Section$Allocate)
5877 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5880 _profile(PackageTable$reloadData$Section$Add)
5881 [sections_ addObject:section];
5885 [section addToCount];
5891 [index_ removeAllObjects];
5893 _profile(PackageTable$reloadData$Section)
5894 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5898 _profile(PackageTable$reloadData$Section$Package)
5899 package = [packages_ objectAtIndex:offset];
5900 index = [package index];
5903 if (section == nil || [section index] != index) {
5904 _profile(PackageTable$reloadData$Section$Allocate)
5905 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5908 [index_ addObject:[section name]];
5909 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5911 _profile(PackageTable$reloadData$Section$Add)
5912 [sections_ addObject:section];
5916 [section addToCount];
5921 _profile(PackageTable$reloadData$List)
5926 - (void) resetCursor {
5927 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5932 /* Filtered Package List Controller {{{ */
5933 @interface FilteredPackageListController : PackageListController {
5939 - (void) setObject:(id)object;
5940 - (void) setObject:(id)object forFilter:(SEL)filter;
5942 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5946 @implementation FilteredPackageListController
5954 - (void) setFilter:(SEL)filter {
5957 /* XXX: this is an unsafe optimization of doomy hell */
5958 Method method(class_getInstanceMethod([Package class], filter));
5959 _assert(method != NULL);
5960 imp_ = method_getImplementation(method);
5961 _assert(imp_ != NULL);
5964 - (void) setObject:(id)object {
5970 object_ = [object retain];
5973 - (void) setObject:(id)object forFilter:(SEL)filter {
5974 [self setFilter:filter];
5975 [self setObject:object];
5978 - (bool) hasPackage:(Package *)package {
5979 _profile(FilteredPackageTable$hasPackage)
5980 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5984 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5985 if ((self = [super initWithDatabase:database title:title]) != nil) {
5986 [self setFilter:filter];
5987 [self setObject:object];
5995 /* Home Controller {{{ */
5996 @interface HomeController : CYBrowserController {
6000 @implementation HomeController
6002 + (BOOL) shouldHideNavigationBar {
6006 - (NSURL *) navigationURL {
6007 return [NSURL URLWithString:@"cydia://home"];
6010 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6011 [super _setMoreHeaders:request];
6014 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6015 if (UniqueID_ != nil)
6016 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6018 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6021 - (void) aboutButtonClicked {
6022 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6024 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6025 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6026 [alert setCancelButtonIndex:0];
6029 @"Copyright (C) 2008-2011\n"
6030 "Jay Freeman (saurik)\n"
6031 "saurik@saurik.com\n"
6032 "http://www.saurik.com/"
6038 - (void) viewWillDisappear:(BOOL)animated {
6039 [super viewWillDisappear:animated];
6041 if ([[self class] shouldHideNavigationBar])
6042 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6045 - (void) viewWillAppear:(BOOL)animated {
6046 if (![self hasLoaded])
6047 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6049 [super viewWillAppear:animated];
6051 if ([[self class] shouldHideNavigationBar])
6052 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6055 - (void) viewDidLoad {
6056 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6057 initWithTitle:UCLocalize("ABOUT")
6058 style:UIBarButtonItemStylePlain
6060 action:@selector(aboutButtonClicked)
6066 /* Manage Controller {{{ */
6067 @interface ManageController : CYBrowserController {
6070 - (void) queueStatusDidChange;
6073 @implementation ManageController
6075 - (NSURL *) navigationURL {
6076 return [NSURL URLWithString:@"cydia://manage"];
6079 - (void) viewWillAppear:(BOOL)animated {
6080 if (![self hasLoaded])
6081 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6083 [super viewWillAppear:animated];
6086 - (void) viewDidLoad {
6087 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6089 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6090 initWithTitle:UCLocalize("SETTINGS")
6091 style:UIBarButtonItemStylePlain
6093 action:@selector(settingsButtonClicked)
6096 [self queueStatusDidChange];
6099 - (void) settingsButtonClicked {
6100 [delegate_ showSettings];
6104 - (void) queueButtonClicked {
6108 - (void) applyLoadingTitle {
6109 // Disable "Loading" title.
6112 - (void) applyRightButton {
6113 // Disable right button.
6117 - (void) queueStatusDidChange {
6119 if (!IsWildcat_ && Queuing_) {
6120 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6121 initWithTitle:UCLocalize("QUEUE")
6122 style:UIBarButtonItemStyleDone
6124 action:@selector(queueButtonClicked)
6127 [[self navigationItem] setRightBarButtonItem:nil];
6132 - (bool) isLoading {
6133 // Never show as loading.
6140 /* Refresh Bar {{{ */
6141 @interface RefreshBar : UINavigationBar {
6142 UIProgressIndicator *indicator_;
6143 UITextLabel *prompt_;
6144 UIProgressBar *progress_;
6145 UINavigationButton *cancel_;
6150 @implementation RefreshBar
6153 [indicator_ release];
6155 [progress_ release];
6160 - (void) positionViews {
6161 CGRect frame = [cancel_ frame];
6162 frame.size = [cancel_ sizeThatFits:frame.size];
6163 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6164 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6165 [cancel_ setFrame:frame];
6167 CGSize prgsize = {75, 100};
6169 [self frame].size.width - prgsize.width - 10,
6170 ([self frame].size.height - prgsize.height) / 2
6172 [progress_ setFrame:prgrect];
6174 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6175 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6176 CGRect indrect = {{indoffset, indoffset}, indsize};
6177 [indicator_ setFrame:indrect];
6179 CGSize prmsize = {215, indsize.height + 4};
6181 indoffset * 2 + indsize.width,
6182 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6184 [prompt_ setFrame:prmrect];
6187 - (void)setFrame:(CGRect)frame {
6188 [super setFrame:frame];
6190 [self positionViews];
6193 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6194 if ((self = [super initWithFrame:frame])) {
6195 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6197 [self setBarStyle:UIBarStyleBlack];
6199 UIBarStyle barstyle([self _barStyle:NO]);
6200 bool ugly(barstyle == UIBarStyleDefault);
6202 UIProgressIndicatorStyle style = ugly ?
6203 UIProgressIndicatorStyleMediumBrown :
6204 UIProgressIndicatorStyleMediumWhite;
6206 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6207 [indicator_ setStyle:style];
6208 [indicator_ startAnimation];
6209 [self addSubview:indicator_];
6211 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6212 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6213 [prompt_ setBackgroundColor:[UIColor clearColor]];
6214 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6215 [self addSubview:prompt_];
6217 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6218 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6219 [progress_ setStyle:0];
6220 [self addSubview:progress_];
6222 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6223 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6224 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6225 [cancel_ setBarStyle:barstyle];
6227 [self positionViews];
6232 [cancel_ removeFromSuperview];
6236 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6237 [progress_ setProgress:0];
6238 [self addSubview:cancel_];
6242 [cancel_ removeFromSuperview];
6245 - (void) setPrompt:(NSString *)prompt {
6246 [prompt_ setText:prompt];
6249 - (void) setProgress:(float)progress {
6250 [progress_ setProgress:progress];
6256 @class CYNavigationController;
6258 /* Cydia Tab Bar Controller {{{ */
6259 @interface CYTabBarController : UITabBarController <
6260 UITabBarControllerDelegate,
6263 _transient Database *database_;
6264 RefreshBar *refreshbar_;
6268 // XXX: ok, "updatedelegate_"?...
6269 _transient NSObject<CydiaDelegate> *updatedelegate_;
6272 UIViewController *remembered_;
6273 _transient UIViewController *transient_;
6276 - (NSArray *) navigationURLCollection;
6277 - (void) dropBar:(BOOL)animated;
6278 - (void) beginUpdate;
6279 - (void) raiseBar:(BOOL)animated;
6284 @implementation CYTabBarController
6286 - (void) setUnselectedViewController:(UIViewController *)transient {
6287 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6288 if (transient != nil) {
6289 if (transient_ == nil)
6290 remembered_ = [[controllers objectAtIndex:0] retain];
6291 transient_ = transient;
6292 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6293 [controllers replaceObjectAtIndex:0 withObject:transient_];
6294 [self setSelectedIndex:0];
6295 [self setViewControllers:controllers];
6296 [self concealTabBarSelection];
6297 } else if (remembered_ != nil) {
6298 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6299 transient_ = transient;
6300 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6301 [remembered_ release];
6303 [self setViewControllers:controllers];
6304 [self revealTabBarSelection];
6308 - (UIViewController *) unselectedViewController {
6312 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6313 if ([self unselectedViewController])
6314 [self setUnselectedViewController:nil];
6317 - (NSArray *) navigationURLCollection {
6318 NSMutableArray *items([NSMutableArray array]);
6320 // XXX: Should this deal with transient view controllers?
6321 for (id navigation in [self viewControllers]) {
6322 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6324 [items addObject:stack];
6330 - (void) reloadData {
6331 for (CYViewController *controller in [self viewControllers])
6332 [controller reloadData];
6334 [(CYNavigationController *)[self unselectedViewController] reloadData];
6338 [refreshbar_ release];
6339 [[NSNotificationCenter defaultCenter] removeObserver:self];
6344 - (id) initWithDatabase:(Database *)database {
6345 if ((self = [super init]) != nil) {
6346 database_ = database;
6347 [self setDelegate:self];
6349 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6350 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6352 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6356 - (void) setUpdate:(NSDate *)date {
6360 - (void) beginUpdate {
6361 [refreshbar_ start];
6364 [updatedelegate_ retainNetworkActivityIndicator];
6368 detachNewThreadSelector:@selector(performUpdate)
6374 - (void) performUpdate { _pooled
6376 status.setDelegate(self);
6377 [database_ updateWithStatus:status];
6380 performSelectorOnMainThread:@selector(completeUpdate)
6386 - (void) stopUpdateWithSelector:(SEL)selector {
6388 [updatedelegate_ releaseNetworkActivityIndicator];
6390 [self raiseBar:YES];
6393 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6396 - (void) completeUpdate {
6399 [self stopUpdateWithSelector:@selector(reloadData)];
6402 - (void) cancelUpdate {
6403 [self stopUpdateWithSelector:@selector(updateData)];
6406 - (void) cancelPressed {
6407 [self cancelUpdate];
6414 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6415 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6418 - (void) startProgress {
6421 - (void) setProgressTitle:(NSString *)title {
6423 performSelectorOnMainThread:@selector(_setProgressTitle:)
6429 - (bool) isCancelling:(size_t)received {
6433 - (void) setProgressPercent:(float)percent {
6435 performSelectorOnMainThread:@selector(_setProgressPercent:)
6436 withObject:[NSNumber numberWithFloat:percent]
6441 - (void) addProgressOutput:(NSString *)output {
6443 performSelectorOnMainThread:@selector(_addProgressOutput:)
6449 - (void) _setProgressTitle:(NSString *)title {
6450 [refreshbar_ setPrompt:title];
6453 - (void) _setProgressPercent:(NSNumber *)percent {
6454 [refreshbar_ setProgress:[percent floatValue]];
6457 - (void) _addProgressOutput:(NSString *)output {
6460 - (void) setUpdateDelegate:(id)delegate {
6461 updatedelegate_ = delegate;
6464 - (CGFloat) statusBarHeight {
6465 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6466 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6468 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6472 - (UIView *) transitionView {
6473 if ([self respondsToSelector:@selector(_transitionView)])
6474 return [self _transitionView];
6476 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6479 - (void) dropBar:(BOOL)animated {
6484 UIView *transition([self transitionView]);
6485 [[self view] addSubview:refreshbar_];
6487 CGRect barframe([refreshbar_ frame]);
6489 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6490 barframe.origin.y = [self statusBarHeight];
6492 barframe.origin.y = 0;
6494 [refreshbar_ setFrame:barframe];
6497 [UIView beginAnimations:nil context:NULL];
6499 CGRect viewframe = [transition frame];
6500 viewframe.origin.y += barframe.size.height;
6501 viewframe.size.height -= barframe.size.height;
6502 [transition setFrame:viewframe];
6505 [UIView commitAnimations];
6507 // Ensure bar has the proper width for our view, it might have changed
6508 barframe.size.width = viewframe.size.width;
6509 [refreshbar_ setFrame:barframe];
6511 // XXX: fix Apple's layout bug
6512 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6515 - (void) raiseBar:(BOOL)animated {
6520 UIView *transition([self transitionView]);
6521 [refreshbar_ removeFromSuperview];
6523 CGRect barframe([refreshbar_ frame]);
6526 [UIView beginAnimations:nil context:NULL];
6528 CGRect viewframe = [transition frame];
6529 viewframe.origin.y -= barframe.size.height;
6530 viewframe.size.height += barframe.size.height;
6531 [transition setFrame:viewframe];
6534 [UIView commitAnimations];
6536 // XXX: fix Apple's layout bug
6537 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6541 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6542 // XXX: fix Apple's layout bug
6543 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6547 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6548 bool dropped(dropped_);
6553 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6558 // XXX: fix Apple's layout bug
6559 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6562 - (void) statusBarFrameChanged:(NSNotification *)notification {
6571 /* Cydia Navigation Controller {{{ */
6572 @interface CYNavigationController : UINavigationController {
6573 _transient Database *database_;
6574 _transient id<UINavigationControllerDelegate> delegate_;
6577 - (NSArray *) navigationURLCollection;
6578 - (id) initWithDatabase:(Database *)database;
6579 - (void) reloadData;
6584 @implementation CYNavigationController
6586 - (NSArray *) navigationURLCollection {
6587 NSMutableArray *stack([NSMutableArray array]);
6589 for (CYViewController *controller in [self viewControllers]) {
6590 NSString *url = [[controller navigationURL] absoluteString];
6592 [stack addObject:url];
6598 - (void) reloadData {
6599 for (CYViewController *page in [self viewControllers]) {
6600 // Only reload controllers that have already loaded.
6601 // This prevents a page from accidentally loading too
6602 // early if it hasn't been shown on the screen yet.
6603 if ([page hasLoaded])
6608 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6609 delegate_ = delegate;
6612 - (id) initWithDatabase:(Database *)database {
6613 if ((self = [super init]) != nil) {
6614 database_ = database;
6621 /* Cydia:// Protocol {{{ */
6622 @interface CydiaURLProtocol : NSURLProtocol {
6627 @implementation CydiaURLProtocol
6629 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6630 NSURL *url([request URL]);
6633 NSString *scheme([[url scheme] lowercaseString]);
6634 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6639 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6643 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6644 id<NSURLProtocolClient> client([self client]);
6646 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6648 NSData *data(UIImagePNGRepresentation(icon));
6650 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6651 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6652 [client URLProtocol:self didLoadData:data];
6653 [client URLProtocolDidFinishLoading:self];
6657 - (void) startLoading {
6658 id<NSURLProtocolClient> client([self client]);
6659 NSURLRequest *request([self request]);
6661 NSURL *url([request URL]);
6662 NSString *href([url absoluteString]);
6664 NSString *path([href substringFromIndex:8]);
6665 NSRange slash([path rangeOfString:@"/"]);
6668 if (slash.location == NSNotFound) {
6672 command = [path substringToIndex:slash.location];
6673 path = [path substringFromIndex:(slash.location + 1)];
6676 Database *database([Database sharedInstance]);
6678 if ([command isEqualToString:@"package-icon"]) {
6681 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6682 Package *package([database packageWithName:path]);
6685 UIImage *icon([package icon]);
6686 [self _returnPNGWithImage:icon forRequest:request];
6687 } else if ([command isEqualToString:@"source-icon"]) {
6690 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6691 NSString *source(Simplify(path));
6692 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6694 icon = [UIImage applicationImageNamed:@"unknown.png"];
6695 [self _returnPNGWithImage:icon forRequest:request];
6696 } else if ([command isEqualToString:@"uikit-image"]) {
6699 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6700 UIImage *icon(_UIImageWithName(path));
6701 [self _returnPNGWithImage:icon forRequest:request];
6702 } else if ([command isEqualToString:@"section-icon"]) {
6705 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6706 NSString *section(Simplify(path));
6707 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6709 icon = [UIImage applicationImageNamed:@"unknown.png"];
6710 [self _returnPNGWithImage:icon forRequest:request];
6712 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6716 - (void) stopLoading {
6722 /* Section Controller {{{ */
6723 @interface SectionController : FilteredPackageListController {
6727 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6731 @implementation SectionController
6733 - (NSURL *) navigationURL {
6734 NSString *name = section_;
6738 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6741 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6744 title = UCLocalize("ALL_PACKAGES");
6745 else if (![name isEqual:@""])
6746 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6748 title = UCLocalize("NO_SECTION");
6750 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6757 /* Sections Controller {{{ */
6758 @interface SectionsController : CYViewController <
6759 UITableViewDataSource,
6762 _transient Database *database_;
6763 NSMutableArray *sections_;
6764 NSMutableArray *filtered_;
6769 - (id) initWithDatabase:(Database *)database;
6770 - (void) editButtonClicked;
6774 @implementation SectionsController
6777 [self releaseSubviews];
6778 [sections_ release];
6779 [filtered_ release];
6784 - (NSURL *) navigationURL {
6785 return [NSURL URLWithString:@"cydia://sections"];
6788 - (void) updateNavigationItem {
6789 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6790 if ([sections_ count] == 0) {
6791 [[self navigationItem] setRightBarButtonItem:nil];
6793 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6794 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6796 action:@selector(editButtonClicked)
6797 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6801 - (BOOL) isEditing {
6805 - (void) setEditing:(BOOL)editing {
6806 if ((editing_ = editing))
6809 [delegate_ updateData];
6811 [self updateNavigationItem];
6814 - (void) viewDidAppear:(BOOL)animated {
6815 [super viewDidAppear:animated];
6816 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6819 - (void) viewWillDisappear:(BOOL)animated {
6820 [super viewWillDisappear:animated];
6821 if (editing_) [self setEditing:NO];
6824 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6825 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6829 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6830 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6833 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6837 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6838 static NSString *reuseIdentifier = @"SectionCell";
6840 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6842 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6844 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6849 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6853 Section *section = [self sectionAtIndexPath:indexPath];
6855 SectionController *controller = [[[SectionController alloc]
6856 initWithDatabase:database_
6857 section:[section name]
6859 [controller setDelegate:delegate_];
6861 [[self navigationController] pushViewController:controller animated:YES];
6865 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6867 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6868 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6869 [list_ setRowHeight:45.0f];
6870 [list_ setDataSource:self];
6871 [list_ setDelegate:self];
6872 [[self view] addSubview:list_];
6875 - (void) viewDidLoad {
6876 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6879 - (void) releaseSubviews {
6884 - (id) initWithDatabase:(Database *)database {
6885 if ((self = [super init]) != nil) {
6886 database_ = database;
6888 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6889 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6893 - (void) reloadData {
6896 NSArray *packages = [database_ packages];
6898 [sections_ removeAllObjects];
6899 [filtered_ removeAllObjects];
6901 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6904 for (Package *package in packages) {
6905 NSString *name([package section]);
6906 NSString *key(name == nil ? @"" : name);
6910 _profile(SectionsView$reloadData$Section)
6911 section = [sections objectForKey:key];
6912 if (section == nil) {
6913 _profile(SectionsView$reloadData$Section$Allocate)
6914 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
6915 [sections setObject:section forKey:key];
6920 [section addToCount];
6922 _profile(SectionsView$reloadData$Filter)
6923 if (![package valid] || ![package visible])
6931 [sections_ addObjectsFromArray:[sections allValues]];
6933 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6935 for (Section *section in sections_) {
6936 size_t count([section row]);
6940 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6941 [section setCount:count];
6942 [filtered_ addObject:section];
6945 [self updateNavigationItem];
6950 - (void)editButtonClicked {
6951 [self setEditing:!editing_];
6957 /* Changes Controller {{{ */
6958 @interface ChangesController : CYViewController <
6959 UITableViewDataSource,
6962 _transient Database *database_;
6964 CFMutableArrayRef packages_;
6965 NSMutableArray *sections_;
6968 BOOL hasSentFirstLoad_;
6971 - (id) initWithDatabase:(Database *)database;
6975 @implementation ChangesController
6978 [self releaseSubviews];
6979 CFRelease(packages_);
6980 [sections_ release];
6985 - (NSURL *) navigationURL {
6986 return [NSURL URLWithString:@"cydia://changes"];
6989 - (void) viewWillAppear:(BOOL)animated {
6990 // Loads after it appears, so don't load beforehand.
6992 [super viewWillAppear:animated];
6995 - (void) viewDidAppear:(BOOL)animated {
6996 [super viewDidAppear:animated];
6998 if (!hasSentFirstLoad_) {
6999 hasSentFirstLoad_ = YES;
7000 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7002 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7006 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7007 NSInteger count([sections_ count]);
7008 return count == 0 ? 1 : count;
7011 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7012 if ([sections_ count] == 0)
7014 return [[sections_ objectAtIndex:section] name];
7017 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7018 if ([sections_ count] == 0)
7020 return [[sections_ objectAtIndex:section] count];
7023 - (Package *) packageAtIndex:(NSUInteger)index {
7024 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7027 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7028 @synchronized (database_) {
7029 if ([database_ era] != era_)
7032 NSUInteger sectionIndex([path section]);
7033 if (sectionIndex >= [sections_ count])
7035 Section *section([sections_ objectAtIndex:sectionIndex]);
7036 NSInteger row([path row]);
7037 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7040 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7041 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7043 cell = [[[PackageCell alloc] init] autorelease];
7044 [cell setPackage:[self packageAtIndexPath:path]];
7048 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7049 Package *package([self packageAtIndexPath:path]);
7050 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7051 [view setDelegate:delegate_];
7052 [[self navigationController] pushViewController:view animated:YES];
7056 - (void) refreshButtonClicked {
7057 [delegate_ beginUpdate];
7058 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7061 - (void) upgradeButtonClicked {
7062 [delegate_ distUpgrade];
7066 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7068 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7069 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7070 [list_ setRowHeight:73];
7071 [list_ setDataSource:self];
7072 [list_ setDelegate:self];
7073 [[self view] addSubview:list_];
7076 - (void) viewDidLoad {
7077 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7080 - (void) releaseSubviews {
7085 - (id) initWithDatabase:(Database *)database {
7086 if ((self = [super init]) != nil) {
7087 database_ = database;
7089 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7090 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7094 - (void) _reloadPackages:(NSArray *)packages {
7095 CFRelease(packages_);
7096 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7099 _profile(ChangesController$_reloadPackages$Filter)
7100 for (Package *package in packages)
7101 if ([package upgradableAndEssential:YES] || [package visible])
7102 CFArrayAppendValue(packages_, package);
7105 _profile(ChangesController$_reloadPackages$radixSort)
7106 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7111 - (void) reloadData {
7112 @synchronized (database_) {
7113 era_ = [database_ era];
7114 NSArray *packages = [database_ packages];
7116 [sections_ removeAllObjects];
7119 UIProgressHUD *hud([delegate_ addProgressHUD]);
7120 [hud setText:UCLocalize("LOADING")];
7121 //NSLog(@"HUD:%@::%@", delegate_, hud);
7122 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7123 [delegate_ removeProgressHUD:hud];
7125 [self _reloadPackages:packages];
7128 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7129 Section *ignored = nil;
7130 Section *section = nil;
7134 bool unseens = false;
7136 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7138 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7139 Package *package = [self packageAtIndex:offset];
7141 BOOL uae = [package upgradableAndEssential:YES];
7145 time_t seen([package seen]);
7147 if (section == nil || last != seen) {
7151 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7154 _profile(ChangesController$reloadData$Allocate)
7155 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7156 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7157 [sections_ addObject:section];
7161 [section addToCount];
7162 } else if ([package ignored]) {
7163 if (ignored == nil) {
7164 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7166 [ignored addToCount];
7169 [upgradable addToCount];
7174 CFRelease(formatter);
7177 Section *last = [sections_ lastObject];
7178 size_t count = [last count];
7179 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7180 [sections_ removeLastObject];
7183 if ([ignored count] != 0)
7184 [sections_ insertObject:ignored atIndex:0];
7186 [sections_ insertObject:upgradable atIndex:0];
7191 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7192 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7193 style:UIBarButtonItemStylePlain
7195 action:@selector(upgradeButtonClicked)
7198 if (![delegate_ updating])
7199 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7200 initWithTitle:UCLocalize("REFRESH")
7201 style:UIBarButtonItemStylePlain
7203 action:@selector(refreshButtonClicked)
7211 /* Search Controller {{{ */
7212 @interface SearchController : FilteredPackageListController <
7215 UISearchBar *search_;
7219 - (id) initWithDatabase:(Database *)database;
7220 - (void) setSearchTerm:(NSString *)term;
7221 - (void) reloadData;
7225 @implementation SearchController
7232 - (NSURL *) navigationURL {
7233 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7234 return [NSURL URLWithString:@"cydia://search"];
7236 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7239 - (void) setSearchTerm:(NSString *)searchTerm {
7240 [search_ setText:searchTerm];
7244 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7245 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7246 [search_ resignFirstResponder];
7250 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7251 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7255 - (id) initWithDatabase:(Database *)database {
7256 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7257 search_ = [[UISearchBar alloc] init];
7261 - (void)viewDidAppear:(BOOL)animated {
7262 [super viewDidAppear:animated];
7264 if (!searchloaded_) {
7265 searchloaded_ = YES;
7266 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7267 [search_ layoutSubviews];
7268 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7270 UITextField *textField;
7271 if ([search_ respondsToSelector:@selector(searchField)])
7272 textField = [search_ searchField];
7274 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7276 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7277 [search_ setDelegate:self];
7278 [textField setEnablesReturnKeyAutomatically:NO];
7279 [[self navigationItem] setTitleView:textField];
7283 - (void) reloadData {
7284 [self setObject:[search_ text]];
7289 - (void) didSelectPackage:(Package *)package {
7290 [search_ resignFirstResponder];
7291 [super didSelectPackage:package];
7296 /* Package Settings Controller {{{ */
7297 @interface PackageSettingsController : CYViewController <
7298 UITableViewDataSource,
7301 _transient Database *database_;
7304 UITableView *table_;
7305 UISwitch *subscribedSwitch_;
7306 UISwitch *ignoredSwitch_;
7307 UITableViewCell *subscribedCell_;
7308 UITableViewCell *ignoredCell_;
7311 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7315 @implementation PackageSettingsController
7318 [self releaseSubviews];
7325 - (NSURL *) navigationURL {
7326 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7329 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7330 if (package_ == nil)
7336 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7337 if (package_ == nil)
7343 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7344 return UCLocalize("CHANGE_PACKAGE_SETTINGS");
7347 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7348 return UCLocalize("SHOW_ALL_CHANGES_EX");
7351 - (void) onSubscribed:(id)control {
7352 bool value([control isOn]);
7353 if (package_ == nil)
7355 if ([package_ setSubscribed:value])
7356 [delegate_ updateData];
7359 - (void) onIgnored:(id)control {
7360 // TODO: set Held state - possibly call out to dpkg, etc.
7363 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7364 if (package_ == nil)
7367 switch ([indexPath row]) {
7368 case 0: return subscribedCell_;
7369 case 1: return ignoredCell_;
7378 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7380 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7381 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7382 [table_ setDataSource:self];
7383 [table_ setDelegate:self];
7384 [[self view] addSubview:table_];
7386 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7387 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7388 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7390 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7391 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7392 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7393 // Disable this switch, since it only reflects (not modifies) the ignored state.
7394 [ignoredSwitch_ setUserInteractionEnabled:NO];
7396 subscribedCell_ = [[UITableViewCell alloc] init];
7397 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7398 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7399 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7401 ignoredCell_ = [[UITableViewCell alloc] init];
7402 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7403 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7404 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7405 // FIXME: Ignored state is not saved.
7406 [ignoredCell_ setUserInteractionEnabled:NO];
7409 - (void) viewDidLoad {
7410 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7413 - (void) releaseSubviews {
7414 [ignoredCell_ release];
7417 [subscribedCell_ release];
7418 subscribedCell_ = nil;
7423 [ignoredSwitch_ release];
7424 ignoredSwitch_ = nil;
7426 [subscribedSwitch_ release];
7427 subscribedSwitch_ = nil;
7430 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7431 if ((self = [super init])) {
7432 database_ = database;
7433 name_ = [package retain];
7437 - (void) reloadData {
7440 if (package_ != nil)
7441 [package_ autorelease];
7442 package_ = [database_ packageWithName:name_];
7443 if (package_ != nil) {
7445 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7446 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7449 [table_ reloadData];
7455 /* Installed Controller {{{ */
7456 @interface InstalledController : FilteredPackageListController {
7460 - (id) initWithDatabase:(Database *)database;
7462 - (void) updateRoleButton;
7463 - (void) queueStatusDidChange;
7467 @implementation InstalledController
7473 - (NSURL *) navigationURL {
7474 return [NSURL URLWithString:@"cydia://installed"];
7477 - (id) initWithDatabase:(Database *)database {
7478 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7479 [self updateRoleButton];
7480 [self queueStatusDidChange];
7485 - (void) queueButtonClicked {
7490 - (void) queueStatusDidChange {
7494 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7495 initWithTitle:UCLocalize("QUEUE")
7496 style:UIBarButtonItemStyleDone
7498 action:@selector(queueButtonClicked)
7501 [[self navigationItem] setLeftBarButtonItem:nil];
7507 - (void) updateRoleButton {
7508 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7509 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7510 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7511 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7513 action:@selector(roleButtonClicked)
7517 - (void) roleButtonClicked {
7518 [self setObject:[NSNumber numberWithBool:expert_]];
7522 [self updateRoleButton];
7528 /* Source Cell {{{ */
7529 @interface SourceCell : CYTableViewCell <
7537 - (void) setSource:(Source *)source;
7541 @implementation SourceCell
7543 - (void) clearSource {
7553 - (void) setSource:(Source *)source {
7557 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7559 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7560 icon_ = [icon_ retain];
7562 origin_ = [[source name] retain];
7563 label_ = [[source uri] retain];
7565 [content_ setNeedsDisplay];
7573 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7574 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7575 UIView *content([self contentView]);
7576 CGRect bounds([content bounds]);
7578 content_ = [[ContentView alloc] initWithFrame:bounds];
7579 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7580 [content_ setBackgroundColor:[UIColor whiteColor]];
7581 [content addSubview:content_];
7583 [content_ setDelegate:self];
7584 [content_ setOpaque:YES];
7588 - (NSString *) accessibilityLabel {
7592 - (void) drawContentRect:(CGRect)rect {
7593 bool highlighted(highlighted_);
7594 float width(rect.size.width);
7597 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7604 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7608 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7613 /* Source Controller {{{ */
7614 @interface SourceController : FilteredPackageListController {
7618 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7622 @implementation SourceController
7624 - (NSURL *) navigationURL {
7625 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7628 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7631 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7637 /* Sources Controller {{{ */
7638 @interface SourcesController : CYViewController <
7639 UITableViewDataSource,
7642 _transient Database *database_;
7644 NSMutableArray *sources_;
7648 UIProgressHUD *hud_;
7651 //NSURLConnection *installer_;
7652 NSURLConnection *trivial_;
7653 NSURLConnection *trivial_bz2_;
7654 NSURLConnection *trivial_gz_;
7655 //NSURLConnection *automatic_;
7660 - (id) initWithDatabase:(Database *)database;
7661 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7665 @implementation SourcesController
7667 - (void) _releaseConnection:(NSURLConnection *)connection {
7668 if (connection != nil) {
7669 [connection cancel];
7670 //[connection setDelegate:nil];
7671 [connection release];
7676 [self releaseSubviews];
7682 //[self _releaseConnection:installer_];
7683 [self _releaseConnection:trivial_];
7684 [self _releaseConnection:trivial_gz_];
7685 [self _releaseConnection:trivial_bz2_];
7686 //[self _releaseConnection:automatic_];
7692 - (NSURL *) navigationURL {
7693 return [NSURL URLWithString:@"cydia://sources"];
7696 - (void) viewDidAppear:(BOOL)animated {
7697 [super viewDidAppear:animated];
7698 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7701 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7702 return offset_ == 0 ? 1 : 2;
7705 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7706 switch (section + (offset_ == 0 ? 1 : 0)) {
7707 case 0: return UCLocalize("ENTERED_BY_USER");
7708 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7714 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7715 int count = [sources_ count];
7717 case 0: return (offset_ == 0 ? count : offset_);
7718 case 1: return count - offset_;
7724 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7726 switch (indexPath.section) {
7727 case 0: idx = indexPath.row; break;
7728 case 1: idx = indexPath.row + offset_; break;
7732 return [sources_ objectAtIndex:idx];
7735 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7736 static NSString *cellIdentifier = @"SourceCell";
7738 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7739 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7740 [cell setSource:[self sourceAtIndexPath:indexPath]];
7741 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7746 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7747 Source *source = [self sourceAtIndexPath:indexPath];
7749 SourceController *controller = [[[SourceController alloc]
7750 initWithDatabase:database_
7754 [controller setDelegate:delegate_];
7756 [[self navigationController] pushViewController:controller animated:YES];
7759 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7760 Source *source = [self sourceAtIndexPath:indexPath];
7761 return [source record] != nil;
7764 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7765 Source *source = [self sourceAtIndexPath:indexPath];
7766 [Sources_ removeObjectForKey:[source key]];
7767 [delegate_ syncData];
7771 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
7774 @"./", @"Distribution",
7775 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
7777 [delegate_ syncData];
7780 - (NSString *) getWarning {
7781 NSString *href(href_);
7782 NSRange colon([href rangeOfString:@"://"]);
7783 if (colon.location != NSNotFound)
7784 href = [href substringFromIndex:(colon.location + 3)];
7785 href = [href stringByAddingPercentEscapes];
7786 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7787 href = [href stringByCachingURLWithCurrentCDN];
7789 NSURL *url([NSURL URLWithString:href]);
7791 NSStringEncoding encoding;
7792 NSError *error(nil);
7794 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7795 return [warning length] == 0 ? nil : warning;
7799 - (void) _endConnection:(NSURLConnection *)connection {
7800 // XXX: the memory management in this method is horribly awkward
7802 NSURLConnection **field = NULL;
7803 if (connection == trivial_)
7805 else if (connection == trivial_bz2_)
7806 field = &trivial_bz2_;
7807 else if (connection == trivial_gz_)
7808 field = &trivial_gz_;
7809 _assert(field != NULL);
7810 [connection release];
7815 trivial_bz2_ == nil &&
7821 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7824 UIAlertView *alert = [[[UIAlertView alloc]
7825 initWithTitle:UCLocalize("SOURCE_WARNING")
7828 cancelButtonTitle:UCLocalize("CANCEL")
7829 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
7832 [alert setContext:@"warning"];
7833 [alert setNumberOfRows:1];
7837 } else if (error_ != nil) {
7838 UIAlertView *alert = [[[UIAlertView alloc]
7839 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7840 message:[error_ localizedDescription]
7842 cancelButtonTitle:UCLocalize("OK")
7843 otherButtonTitles:nil
7846 [alert setContext:@"urlerror"];
7849 UIAlertView *alert = [[[UIAlertView alloc]
7850 initWithTitle:UCLocalize("NOT_REPOSITORY")
7851 message:UCLocalize("NOT_REPOSITORY_EX")
7853 cancelButtonTitle:UCLocalize("OK")
7854 otherButtonTitles:nil
7857 [alert setContext:@"trivial"];
7861 [delegate_ setStatusBarShowsProgress:NO];
7862 [delegate_ removeProgressHUD:hud_];
7872 if (error_ != nil) {
7879 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
7880 switch ([response statusCode]) {
7886 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
7887 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7889 error_ = [error retain];
7890 [self _endConnection:connection];
7893 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
7894 [self _endConnection:connection];
7897 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
7898 NSMutableURLRequest *request = [NSMutableURLRequest
7899 requestWithURL:[NSURL URLWithString:href]
7900 cachePolicy:NSURLRequestUseProtocolCachePolicy
7901 timeoutInterval:120.0
7904 [request setHTTPMethod:method];
7906 if (Machine_ != NULL)
7907 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
7908 if (UniqueID_ != nil)
7909 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
7911 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
7913 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
7916 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7917 NSString *context([alert context]);
7919 if ([context isEqualToString:@"source"]) {
7922 NSString *href = [[alert textField] text];
7924 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
7926 if (![href hasSuffix:@"/"])
7927 href_ = [href stringByAppendingString:@"/"];
7930 href_ = [href_ retain];
7932 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
7933 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
7934 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
7935 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
7939 // XXX: this is stupid
7940 hud_ = [[delegate_ addProgressHUD] retain];
7941 [hud_ setText:UCLocalize("VERIFYING_URL")];
7950 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7951 } else if ([context isEqualToString:@"trivial"])
7952 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7953 else if ([context isEqualToString:@"urlerror"])
7954 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7955 else if ([context isEqualToString:@"warning"]) {
7970 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7975 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7977 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7978 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7979 [list_ setRowHeight:56];
7980 [list_ setDataSource:self];
7981 [list_ setDelegate:self];
7982 [[self view] addSubview:list_];
7985 - (void) viewDidLoad {
7986 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
7987 [self updateButtonsForEditingStatus:NO animated:NO];
7990 - (void) releaseSubviews {
7995 - (id) initWithDatabase:(Database *)database {
7996 if ((self = [super init]) != nil) {
7997 database_ = database;
7998 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8002 - (void) reloadData {
8006 if (!list.ReadMainList())
8009 [sources_ removeAllObjects];
8010 [sources_ addObjectsFromArray:[database_ sources]];
8012 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8015 int count([sources_ count]);
8017 for (int i = 0; i != count; i++) {
8018 if ([[sources_ objectAtIndex:i] record] == nil)
8023 [list_ setEditing:NO];
8024 [self updateButtonsForEditingStatus:NO animated:NO];
8028 - (void) showAddSourcePrompt {
8029 UIAlertView *alert = [[[UIAlertView alloc]
8030 initWithTitle:UCLocalize("ENTER_APT_URL")
8033 cancelButtonTitle:UCLocalize("CANCEL")
8034 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
8037 [alert setContext:@"source"];
8038 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8040 [alert setNumberOfRows:1];
8041 [alert addTextFieldWithValue:@"http://" label:@""];
8043 UITextInputTraits *traits = [[alert textField] textInputTraits];
8044 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8045 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8046 [traits setKeyboardType:UIKeyboardTypeURL];
8047 // XXX: UIReturnKeyDone
8048 [traits setReturnKeyType:UIReturnKeyNext];
8053 - (void) addButtonClicked {
8054 [self showAddSourcePrompt];
8057 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8058 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8059 initWithTitle:UCLocalize("ADD")
8060 style:UIBarButtonItemStylePlain
8062 action:@selector(addButtonClicked)
8063 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8065 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8066 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8067 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8069 action:@selector(editButtonClicked)
8070 ] autorelease] animated:animated];
8072 if (IsWildcat_ && !editing)
8073 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8074 initWithTitle:UCLocalize("SETTINGS")
8075 style:UIBarButtonItemStylePlain
8077 action:@selector(settingsButtonClicked)
8081 - (void) settingsButtonClicked {
8082 [delegate_ showSettings];
8085 - (void) editButtonClicked {
8086 [list_ setEditing:![list_ isEditing] animated:YES];
8088 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8094 /* Settings Controller {{{ */
8095 @interface SettingsController : CYViewController <
8096 UITableViewDataSource,
8099 _transient Database *database_;
8100 // XXX: ok, "roledelegate_"?...
8101 _transient id roledelegate_;
8102 UITableView *table_;
8103 UISegmentedControl *segment_;
8107 - (void) showDoneButton;
8108 - (void) resizeSegmentedControl;
8112 @implementation SettingsController
8115 [self releaseSubviews];
8121 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8123 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8124 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8125 [table_ setDelegate:self];
8126 [table_ setDataSource:self];
8127 [[self view] addSubview:table_];
8129 NSArray *items = [NSArray arrayWithObjects:
8131 UCLocalize("HACKER"),
8132 UCLocalize("DEVELOPER"),
8134 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8135 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8136 [container_ addSubview:segment_];
8139 - (void) viewDidLoad {
8140 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8143 if ([Role_ isEqualToString:@"User"]) index = 0;
8144 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8145 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8147 [segment_ setSelectedSegmentIndex:index];
8148 [self showDoneButton];
8151 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8152 [self resizeSegmentedControl];
8155 - (void) releaseSubviews {
8162 [container_ release];
8166 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8167 if ((self = [super init])) {
8168 database_ = database;
8169 roledelegate_ = delegate;
8173 - (void) resizeSegmentedControl {
8174 CGFloat width = [[self view] frame].size.width;
8175 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8178 - (void) viewWillAppear:(BOOL)animated {
8179 [super viewWillAppear:animated];
8181 [self resizeSegmentedControl];
8184 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8185 [self resizeSegmentedControl];
8188 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8189 [self resizeSegmentedControl];
8193 NSString *role(nil);
8195 switch ([segment_ selectedSegmentIndex]) {
8196 case 0: role = @"User"; break;
8197 case 1: role = @"Hacker"; break;
8198 case 2: role = @"Developer"; break;
8203 if (![role isEqualToString:Role_]) {
8204 bool rolling(Role_ == nil);
8207 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8211 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8215 [roledelegate_ loadData];
8217 [roledelegate_ updateData];
8221 - (void) segmentChanged:(UISegmentedControl *)control {
8222 [self showDoneButton];
8225 - (void) saveAndClose {
8228 [[self navigationItem] setRightBarButtonItem:nil];
8229 [[self navigationController] dismissModalViewControllerAnimated:YES];
8232 - (void) doneButtonClicked {
8233 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8234 [spinner startAnimating];
8235 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8236 [[self navigationItem] setRightBarButtonItem:spinItem];
8238 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8241 - (void) showDoneButton {
8242 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8243 initWithTitle:UCLocalize("DONE")
8244 style:UIBarButtonItemStyleDone
8246 action:@selector(doneButtonClicked)
8247 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8250 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8251 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8255 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8259 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8260 return nil; // This method is required by the protocol.
8263 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8265 return UCLocalize("ROLE_EX");
8267 return [NSString stringWithFormat:
8268 @"%@: %@\n%@: %@\n%@: %@",
8269 UCLocalize("USER"), UCLocalize("USER_EX"),
8270 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8271 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8276 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8277 return section == 3 ? 44.0f : 0;
8280 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8281 return section == 3 ? container_ : nil;
8284 - (void) reloadData {
8286 [table_ reloadData];
8291 /* Stash Controller {{{ */
8292 @interface StashController : CYViewController {
8293 UIActivityIndicatorView *spinner_;
8299 @implementation StashController
8302 [self releaseSubviews];
8308 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8309 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8311 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8312 CGRect spinrect = [spinner_ frame];
8313 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8314 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8315 [spinner_ setFrame:spinrect];
8316 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8317 [[self view] addSubview:spinner_];
8318 [spinner_ startAnimating];
8321 captrect.size.width = [[self view] frame].size.width;
8322 captrect.size.height = 40.0f;
8323 captrect.origin.x = 0;
8324 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8325 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8326 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8327 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8328 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8329 [caption_ setTextColor:[UIColor whiteColor]];
8330 [caption_ setBackgroundColor:[UIColor clearColor]];
8331 [caption_ setShadowColor:[UIColor blackColor]];
8332 [caption_ setTextAlignment:UITextAlignmentCenter];
8333 [[self view] addSubview:caption_];
8336 statusrect.size.width = [[self view] frame].size.width;
8337 statusrect.size.height = 30.0f;
8338 statusrect.origin.x = 0;
8339 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8340 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8341 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8342 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8343 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8344 [status_ setTextColor:[UIColor whiteColor]];
8345 [status_ setBackgroundColor:[UIColor clearColor]];
8346 [status_ setShadowColor:[UIColor blackColor]];
8347 [status_ setTextAlignment:UITextAlignmentCenter];
8348 [[self view] addSubview:status_];
8351 - (void) releaseSubviews {
8365 @interface Cydia : UIApplication <
8366 ConfirmationControllerDelegate,
8367 ProgressControllerDelegate,
8369 UINavigationControllerDelegate,
8370 UITabBarControllerDelegate
8372 // XXX: evaluate all fields for _transient
8375 CYTabBarController *tabbar_;
8377 NSMutableArray *essential_;
8378 NSMutableArray *broken_;
8380 Database *database_;
8387 StashController *stash_;
8396 @implementation Cydia
8398 - (void) beginUpdate {
8399 [tabbar_ beginUpdate];
8403 return [tabbar_ updating];
8407 if ([broken_ count] != 0) {
8408 int count = [broken_ count];
8410 UIAlertView *alert = [[[UIAlertView alloc]
8411 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8412 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8414 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8415 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8418 [alert setContext:@"fixhalf"];
8420 } else if (!Ignored_ && [essential_ count] != 0) {
8421 int count = [essential_ count];
8423 UIAlertView *alert = [[[UIAlertView alloc]
8424 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8425 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8427 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8428 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8431 [alert setContext:@"upgrade"];
8436 - (void) _saveConfig {
8442 NSString *error(nil);
8444 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8446 NSError *error(nil);
8447 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8448 NSLog(@"failure to save metadata data: %@", error);
8453 NSLog(@"failure to serialize metadata: %@", error);
8458 // Navigation controller for the queuing badge.
8459 - (CYNavigationController *) queueNavigationController {
8460 NSArray *controllers = [tabbar_ viewControllers];
8461 return [controllers objectAtIndex:3];
8464 - (void) _updateData {
8467 [tabbar_ reloadData];
8469 CYNavigationController *navigation = [self queueNavigationController];
8471 id queuedelegate = nil;
8472 if ([[navigation viewControllers] count] > 0)
8473 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8475 [queuedelegate queueStatusDidChange];
8476 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8479 - (void) _refreshIfPossible {
8480 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8482 bool recently = false;
8483 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8484 if (update != nil) {
8485 NSTimeInterval interval([update timeIntervalSinceNow]);
8486 if (interval <= 0 && interval > -(15*60))
8490 // Don't automatic refresh if:
8491 // - We already refreshed recently.
8492 // - We already auto-refreshed this launch.
8493 // - Auto-refresh is disabled.
8494 if (recently || loaded_ || ManualRefresh) {
8495 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8497 // If we are cancelling, we need to make sure it knows it's already loaded.
8501 // We are going to load, so remember that.
8505 SCNetworkReachabilityFlags flags; {
8506 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8507 SCNetworkReachabilityGetFlags(reachability, &flags);
8508 CFRelease(reachability);
8511 // XXX: this elaborate mess is what Apple is using to determine this? :(
8512 // XXX: do we care if the user has to intervene? maybe that's ok?
8514 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8515 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8516 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8517 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8518 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8519 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8523 // If we can reach the server, auto-refresh!
8525 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8530 - (void) refreshIfPossible {
8531 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8534 - (void) _reloadData {
8535 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8536 [hud setText:UCLocalize("RELOADING_DATA")];
8538 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8541 [self removeProgressHUD:hud];
8545 [essential_ removeAllObjects];
8546 [broken_ removeAllObjects];
8548 NSArray *packages([database_ packages]);
8549 for (Package *package in packages) {
8551 [broken_ addObject:package];
8552 if ([package upgradableAndEssential:NO]) {
8553 if ([package essential])
8554 [essential_ addObject:package];
8559 NSLog(@"changes:#%u", changes);
8561 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8564 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8565 [changesItem setBadgeValue:badge];
8566 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8567 [self setApplicationIconBadgeNumber:changes];
8570 [changesItem setBadgeValue:nil];
8571 [changesItem setAnimatedBadge:NO];
8572 [self setApplicationIconBadgeNumber:0];
8577 [self refreshIfPossible];
8580 - (void) updateData {
8589 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8590 _assert(file != NULL);
8592 for (NSString *key in [Sources_ allKeys]) {
8593 NSDictionary *source([Sources_ objectForKey:key]);
8595 fprintf(file, "%s %s %s\n",
8596 [[source objectForKey:@"Type"] UTF8String],
8597 [[source objectForKey:@"URI"] UTF8String],
8598 [[source objectForKey:@"Distribution"] UTF8String]
8606 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8607 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8609 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8610 [tabbar_ presentModalViewController:navigation animated:YES];
8613 detachNewThreadSelector:@selector(update_)
8616 title:UCLocalize("UPDATING_SOURCES")
8620 - (void) reloadData {
8621 @synchronized (self) {
8627 pkgProblemResolver *resolver = [database_ resolver];
8629 resolver->InstallProtect();
8630 if (!resolver->Resolve(true))
8635 if (![database_ prepare])
8638 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8639 [page setDelegate:self];
8640 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8641 [confirm_ setDelegate:self];
8644 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8645 [tabbar_ presentModalViewController:confirm_ animated:YES];
8651 @synchronized (self) {
8656 - (void) clearPackage:(Package *)package {
8657 @synchronized (self) {
8664 - (void) installPackages:(NSArray *)packages {
8665 @synchronized (self) {
8666 for (Package *package in packages)
8673 - (void) installPackage:(Package *)package {
8674 @synchronized (self) {
8681 - (void) removePackage:(Package *)package {
8682 @synchronized (self) {
8689 - (void) distUpgrade {
8690 @synchronized (self) {
8691 if (![database_ upgrade])
8698 @synchronized (self) {
8703 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8706 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8708 if (navigation != nil) {
8709 [navigation pushViewController:progress animated:YES];
8711 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8713 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8714 [tabbar_ presentModalViewController:navigation animated:YES];
8718 detachNewThreadSelector:@selector(perform)
8721 title:UCLocalize("RUNNING")
8727 - (void) progressControllerIsComplete:(ProgressController *)progress {
8732 - (void) showSettings {
8733 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8734 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8736 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8737 [tabbar_ presentModalViewController:nav animated:YES];
8740 - (void) retainNetworkActivityIndicator {
8741 if (activity_++ == 0)
8742 [self setNetworkActivityIndicatorVisible:YES];
8745 - (void) releaseNetworkActivityIndicator {
8746 if (--activity_ == 0)
8747 [self setNetworkActivityIndicatorVisible:NO];
8750 - (void) cancelAndClear:(bool)clear {
8751 @synchronized (self) {
8763 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8764 NSString *context([alert context]);
8766 if ([context isEqualToString:@"fixhalf"]) {
8767 if (button == [alert cancelButtonIndex]) {
8768 @synchronized (self) {
8769 for (Package *broken in broken_) {
8772 NSString *id = [broken id];
8773 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8774 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8775 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8776 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8782 } else if (button == [alert firstOtherButtonIndex]) {
8783 [broken_ removeAllObjects];
8787 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8788 } else if ([context isEqualToString:@"upgrade"]) {
8789 if (button == [alert firstOtherButtonIndex]) {
8790 @synchronized (self) {
8791 for (Package *essential in essential_)
8792 [essential install];
8797 } else if (button == [alert firstOtherButtonIndex] + 1) {
8799 } else if (button == [alert cancelButtonIndex]) {
8803 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8807 - (void) system:(NSString *)command { _pooled
8809 system([command UTF8String]);
8813 - (void) applicationWillSuspend {
8815 [super applicationWillSuspend];
8818 - (BOOL) isSafeToSuspend {
8819 // Use external process status API internally.
8820 // This is probably a really bad idea.
8821 // XXX: what is the point of this? does this solve anything at all?
8822 uint64_t status = 0;
8824 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8825 notify_get_state(notify_token, &status);
8826 notify_cancel(notify_token);
8829 return locked_ == 0 && status == 0;
8832 - (void) applicationSuspend:(__GSEvent *)event {
8833 if ([self isSafeToSuspend])
8834 [super applicationSuspend:event];
8837 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8838 if ([self isSafeToSuspend])
8839 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8842 - (void) _setSuspended:(BOOL)value {
8843 if ([self isSafeToSuspend])
8844 [super _setSuspended:value];
8847 - (UIProgressHUD *) addProgressHUD {
8848 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8849 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8851 [window_ setUserInteractionEnabled:NO];
8854 UIViewController *target = tabbar_;
8855 while ([target modalViewController] != nil) target = [target modalViewController];
8856 [[target view] addSubview:hud];
8862 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8864 [hud removeFromSuperview];
8865 [window_ setUserInteractionEnabled:YES];
8869 - (CYViewController *) pageForPackage:(NSString *)name {
8870 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
8873 - (CYViewController *) pageForURL:(NSURL *)url {
8874 NSString *scheme([[url scheme] lowercaseString]);
8875 if ([[url absoluteString] length] <= [scheme length] + 3)
8877 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
8878 NSArray *components([path pathComponents]);
8880 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
8881 return [self pageForPackage:[components objectAtIndex:1]];
8883 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
8886 NSString *base([components objectAtIndex:0]);
8888 CYViewController *controller = nil;
8890 if ([base isEqualToString:@"url"]) {
8891 // This kind of URL can contain slashes in the argument, so we can't parse them below.
8892 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
8893 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
8894 } else if ([components count] == 1) {
8895 if ([base isEqualToString:@"manage"]) {
8896 controller = [[[ManageController alloc] init] autorelease];
8899 if ([base isEqualToString:@"sources"]) {
8900 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8903 if ([base isEqualToString:@"home"]) {
8904 controller = [[[HomeController alloc] init] autorelease];
8907 if ([base isEqualToString:@"sections"]) {
8908 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
8911 if ([base isEqualToString:@"search"]) {
8912 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8915 if ([base isEqualToString:@"changes"]) {
8916 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
8919 if ([base isEqualToString:@"installed"]) {
8920 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8922 } else if ([components count] == 2) {
8923 NSString *argument = [components objectAtIndex:1];
8925 if ([base isEqualToString:@"package"]) {
8926 controller = [self pageForPackage:argument];
8929 if ([base isEqualToString:@"search"]) {
8930 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8931 [(SearchController *)controller setSearchTerm:argument];
8934 if ([base isEqualToString:@"sections"]) {
8935 if ([argument isEqualToString:@"all"])
8937 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
8940 if ([base isEqualToString:@"sources"]) {
8941 if ([argument isEqualToString:@"add"]) {
8942 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8943 [(SourcesController *)controller showAddSourcePrompt];
8945 NSArray *sources = [database_ sources];
8946 for (Source *source in sources) {
8947 if ([[source name] caseInsensitiveCompare:argument] == NSOrderedSame) {
8948 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
8955 if ([base isEqualToString:@"launch"]) {
8956 [self launchApplicationWithIdentifier:argument suspended:NO];
8959 } else if ([components count] == 3) {
8960 NSString *arg1 = [components objectAtIndex:1];
8961 NSString *arg2 = [components objectAtIndex:2];
8963 if ([base isEqualToString:@"package"]) {
8964 if ([arg2 isEqualToString:@"settings"]) {
8965 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
8966 } else if ([arg2 isEqualToString:@"files"]) {
8967 if (Package *package = [database_ packageWithName:arg1]) {
8968 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8969 [(FileTable *)controller setPackage:package];
8975 [controller setDelegate:self];
8979 - (BOOL) openCydiaURL:(NSURL *)url {
8980 CYViewController *page([self pageForURL:url]);
8983 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
8984 [nav setViewControllers:[NSArray arrayWithObject:page]];
8985 [tabbar_ setUnselectedViewController:nav];
8991 - (void) applicationOpenURL:(NSURL *)url {
8992 [super applicationOpenURL:url];
8994 if (!loaded_) starturl_ = [url retain];
8995 else [self openCydiaURL:url];
8998 - (void) applicationWillResignActive:(UIApplication *)application {
8999 // Stop refreshing if you get a phone call or lock the device.
9000 if ([tabbar_ updating])
9001 [tabbar_ cancelUpdate];
9003 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9004 [super applicationWillResignActive:application];
9007 - (void) applicationWillTerminate:(UIApplication *)application {
9009 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9010 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9011 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9016 - (void) addStashController {
9018 stash_ = [[StashController alloc] init];
9019 [window_ addSubview:[stash_ view]];
9022 - (void) removeStashController {
9023 [[stash_ view] removeFromSuperview];
9029 [self setIdleTimerDisabled:YES];
9031 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9032 [self setStatusBarShowsProgress:YES];
9033 UpdateExternalStatus(1);
9035 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9037 UpdateExternalStatus(0);
9038 [self setStatusBarShowsProgress:NO];
9040 [self removeStashController];
9042 if (ExecFork() == 0) {
9043 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9044 perror("launchctl stop");
9048 - (void) setupViewControllers {
9049 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9051 NSMutableArray *items([NSMutableArray arrayWithObjects:
9052 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9053 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9054 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9055 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9059 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9060 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9062 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9065 NSMutableArray *controllers([NSMutableArray array]);
9066 for (UITabBarItem *item in items) {
9067 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9068 [controller setTabBarItem:item];
9069 [controllers addObject:controller];
9071 [tabbar_ setViewControllers:controllers];
9073 [tabbar_ setUpdateDelegate:self];
9076 - (CYEmulatedLoadingController *)showEmulatedLoadingControllerInView:(UIView *)view {
9077 static CYEmulatedLoadingController *fake = nil;
9081 fake = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9082 [view addSubview:[fake view]];
9084 [[fake view] removeFromSuperview];
9092 - (void) applicationDidFinishLaunching:(id)unused {
9096 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9097 [self setApplicationSupportsShakeToEdit:NO];
9099 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9100 initWithMemoryCapacity:524288
9101 diskCapacity:10485760
9102 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9105 [CYBrowserController _initialize];
9107 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9109 Font12_ = [[UIFont systemFontOfSize:12] retain];
9110 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9111 Font14_ = [[UIFont systemFontOfSize:14] retain];
9112 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9113 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9115 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9116 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9118 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9119 [window_ orderFront:self];
9120 [window_ makeKey:self];
9121 [window_ setHidden:NO];
9124 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9125 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9126 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9127 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9128 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9129 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9130 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9131 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9132 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9135 [self addStashController];
9136 // XXX: this would be much cleaner as a yieldToSelector:
9137 // that way the removeStashController could happen right here inline
9138 // we also could no longer require the useless stash_ field anymore
9139 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9143 database_ = [Database sharedInstance];
9145 [window_ setUserInteractionEnabled:NO];
9146 [self setupViewControllers];
9147 [self showEmulatedLoadingControllerInView:window_];
9149 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9156 [window_ setUserInteractionEnabled:YES];
9158 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9159 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9161 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9162 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9166 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9167 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9168 [window_ setUserInteractionEnabled:NO];
9174 [window_ addSubview:[tabbar_ view]];
9175 [self showEmulatedLoadingControllerInView:nil];
9176 [window_ setUserInteractionEnabled:YES];
9178 int selectedIndex = 0;
9179 NSMutableArray *items = nil;
9181 bool recently = false;
9182 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9183 if (closed != nil) {
9184 NSTimeInterval interval([closed timeIntervalSinceNow]);
9185 // XXX: Is 15 minutes the optimal time here?
9186 if (interval <= 0 && interval > -(15*60))
9190 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9191 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9194 for (NSArray *entry in items)
9195 if ([entry count] <= 0)
9198 if (!recently || !items || !enough) {
9200 items = [NSMutableArray array];
9201 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9202 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9203 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9205 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9207 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9208 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9210 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9213 [tabbar_ setSelectedIndex:selectedIndex];
9214 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9215 NSArray *stack = [items objectAtIndex:tab];
9216 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9217 NSMutableArray *current = [NSMutableArray array];
9219 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9220 NSString *addr = [stack objectAtIndex:nav];
9221 NSURL *url = [NSURL URLWithString:addr];
9222 CYViewController *page = [self pageForURL:url];
9224 [current addObject:page];
9227 [navigation setViewControllers:current];
9230 // (Try to) show the startup URL.
9231 if (starturl_ != nil) {
9232 [self openCydiaURL:starturl_];
9233 [starturl_ release];
9238 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9239 if (item != nil && IsWildcat_) {
9240 [sheet showFromBarButtonItem:item animated:YES];
9242 [sheet showInView:window_];
9249 id Alloc_(id self, SEL selector) {
9250 id object = alloc_(self, selector);
9251 lprintf("[%s]A-%p\n", self->isa->name, object);
9256 id Dealloc_(id self, SEL selector) {
9257 id object = dealloc_(self, selector);
9258 lprintf("[%s]D-%p\n", self->isa->name, object);
9262 Class $WebDefaultUIKitDelegate;
9264 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9265 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9266 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9267 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9270 static NSNumber *shouldPlayKeyboardSounds;
9274 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9276 case 1104: // Keyboard Button Clicked
9277 case 1105: // Keyboard Delete Repeated
9278 if (shouldPlayKeyboardSounds == nil) {
9279 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9280 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9283 if (![shouldPlayKeyboardSounds boolValue])
9287 _UIHardware$_playSystemSound$(self, _cmd, sound);
9291 Class $UIApplication;
9293 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9294 static BOOL initialized = NO;
9295 static BOOL started = NO;
9297 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9298 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9300 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9301 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9302 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9303 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9305 if (initialized && !enabled) {
9307 [bundle performSelector:@selector(_accessibilityStopServer)];
9308 } else if (enabled) {
9312 [bundle performSelector:@selector(_accessibilityStartServer)];
9318 int main(int argc, char *argv[]) { _pooled
9321 if (Class $UIDevice = objc_getClass("UIDevice")) {
9322 UIDevice *device([$UIDevice currentDevice]);
9323 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9327 UIScreen *screen([UIScreen mainScreen]);
9328 if ([screen respondsToSelector:@selector(scale)])
9329 ScreenScale_ = [screen scale];
9333 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9334 if (ScreenScale_ > 1)
9335 [parts addObject:@"@2x"];
9336 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9337 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9339 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9341 /* Library Hacks {{{ */
9342 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9344 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9345 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9346 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9347 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9348 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9351 $UIHardware = objc_getClass("UIHardware");
9352 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9353 if (UIHardware$_playSystemSound$ != NULL) {
9354 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9355 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9358 $UIApplication = objc_getClass("UIApplication");
9359 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9360 if (UIApplication$_updateApplicationAccessibility != NULL) {
9361 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9362 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9365 /* Set Locale {{{ */
9366 Locale_ = CFLocaleCopyCurrent();
9367 Languages_ = [NSLocale preferredLanguages];
9368 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9369 //NSLog(@"%@", [Languages_ description]);
9372 if (Languages_ == nil || [Languages_ count] == 0)
9373 // XXX: consider just setting to C and then falling through?
9376 lang = [[Languages_ objectAtIndex:0] UTF8String];
9377 setenv("LANG", lang, true);
9380 //std::setlocale(LC_ALL, lang);
9381 NSLog(@"Setting Language: %s", lang);
9384 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9386 /* Parse Arguments {{{ */
9387 bool substrate(false);
9393 for (int argi(1); argi != argc; ++argi)
9394 if (strcmp(argv[argi], "--") == 0) {
9396 argv[argi] = argv[0];
9402 for (int argi(1); argi != arge; ++argi)
9403 if (strcmp(args[argi], "--substrate") == 0)
9406 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9410 App_ = [[NSBundle mainBundle] bundlePath];
9411 Home_ = NSHomeDirectory();
9417 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9418 alloc_ = alloc->method_imp;
9419 alloc->method_imp = (IMP) &Alloc_;*/
9421 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9422 dealloc_ = dealloc->method_imp;
9423 dealloc->method_imp = (IMP) &Dealloc_;*/
9425 /* System Information {{{ */
9429 size = sizeof(maxproc);
9430 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9431 perror("sysctlbyname(\"kern.maxproc\", ?)");
9432 else if (maxproc < 64) {
9434 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9435 perror("sysctlbyname(\"kern.maxproc\", #)");
9438 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9439 char *osversion = new char[size];
9440 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9441 perror("sysctlbyname(\"kern.osversion\", ?)");
9443 System_ = [NSString stringWithUTF8String:osversion];
9445 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9446 char *machine = new char[size];
9447 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9448 perror("sysctlbyname(\"hw.machine\", ?)");
9452 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9453 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9454 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9455 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9459 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9460 NSData *data((NSData *) ecid);
9461 size_t length([data length]);
9462 uint8_t bytes[length];
9463 [data getBytes:bytes];
9464 char string[length * 2 + 1];
9465 for (size_t i(0); i != length; ++i)
9466 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9467 ChipID_ = [NSString stringWithUTF8String:string];
9471 IOObjectRelease(service);
9475 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9477 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9478 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9479 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9481 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9482 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9483 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9485 if (mcc != NULL && mnc != NULL)
9486 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9493 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9494 Build_ = [system objectForKey:@"ProductBuildVersion"];
9495 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9496 Product_ = [info objectForKey:@"SafariProductVersion"];
9497 Safari_ = [info objectForKey:@"CFBundleVersion"];
9500 /* Load Database {{{ */
9502 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9504 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9506 if (Metadata_ == NULL)
9507 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9509 Settings_ = [Metadata_ objectForKey:@"Settings"];
9511 Packages_ = [Metadata_ objectForKey:@"Packages"];
9512 Sections_ = [Metadata_ objectForKey:@"Sections"];
9513 Sources_ = [Metadata_ objectForKey:@"Sources"];
9515 Token_ = [Metadata_ objectForKey:@"Token"];
9518 if (Settings_ != nil)
9519 Role_ = [Settings_ objectForKey:@"Role"];
9521 if (Sections_ == nil) {
9522 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9523 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9526 if (Sources_ == nil) {
9527 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9528 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9533 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9536 if (Packages_ != nil) {
9538 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9542 [Metadata_ removeObjectForKey:@"Packages"];
9548 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9550 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9551 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9552 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9553 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9554 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9555 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9557 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9559 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9560 unlink("/tmp/.cydia.fw");
9562 } else if (access("/User", F_OK) != 0 || version < 2) {
9565 system("/usr/libexec/cydia/firmware.sh");
9569 _assert([[NSFileManager defaultManager]
9570 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9571 withIntermediateDirectories:YES
9576 if (access("/tmp/cydia.chk", F_OK) == 0) {
9577 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9578 _assert(errno == ENOENT);
9579 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9580 _assert(errno == ENOENT);
9583 /* APT Initialization {{{ */
9584 _assert(pkgInitConfig(*_config));
9585 _assert(pkgInitSystem(*_config, _system));
9588 _config->Set("APT::Acquire::Translation", lang);
9590 // XXX: this timeout might be important :(
9591 //_config->Set("Acquire::http::Timeout", 15);
9593 _config->Set("Acquire::http::MaxParallel", 3);
9595 /* Color Choices {{{ */
9596 space_ = CGColorSpaceCreateDeviceRGB();
9598 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9599 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9600 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9601 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9602 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9603 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9604 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9605 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9606 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9608 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9609 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9611 /* UIKit Configuration {{{ */
9612 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9613 if ($GSFontSetUseLegacyFontMetrics != NULL)
9614 $GSFontSetUseLegacyFontMetrics(YES);
9616 // XXX: I have a feeling this was important
9617 //UIKeyboardDisableAutomaticAppearance();
9620 Colon_ = UCLocalize("COLON_DELIMITED");
9621 Elision_ = UCLocalize("ELISION");
9622 Error_ = UCLocalize("ERROR");
9623 Warning_ = UCLocalize("WARNING");
9626 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9628 CGColorSpaceRelease(space_);