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 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3495 cache_->SetReInstall(iterator, false);
3498 - (void) configure {
3499 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3501 system([dpkg UTF8String]);
3506 // XXX: I don't remember this condition
3511 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3513 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3515 if ([self popErrorWithTitle:title])
3519 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3522 public pkgArchiveCleaner
3525 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3530 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3537 fetcher_->Shutdown();
3539 pkgRecords records(cache_);
3541 lock_ = new FileFd();
3542 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3544 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3546 if ([self popErrorWithTitle:title])
3550 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3553 manager_ = (_system->CreatePM(cache_));
3554 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3561 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3563 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3565 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3567 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3568 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3571 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3576 [CydiaApp retainNetworkActivityIndicator];
3578 bool failed = false;
3579 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3580 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3582 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3585 std::string uri = (*item)->DescURI();
3586 std::string error = (*item)->ErrorText;
3588 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3591 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3592 withObject:[NSArray arrayWithObjects:
3593 [NSString stringWithUTF8String:error.c_str()],
3599 [CydiaApp releaseNetworkActivityIndicator];
3607 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3609 if (_error->PendingError()) {
3614 if (result == pkgPackageManager::Failed) {
3619 if (result != pkgPackageManager::Completed) {
3624 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3626 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3628 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3629 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3632 if (![before isEqualToArray:after])
3637 NSString *title(UCLocalize("UPGRADE"));
3638 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3644 [self updateWithStatus:status_];
3647 - (void) updateWithStatus:(Status &)status {
3648 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3649 NSString *title(UCLocalize("REFRESHING_DATA"));
3652 if (!list.ReadMainList())
3653 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3656 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3657 if ([self popErrorWithTitle:title])
3660 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3661 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3662 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3664 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3668 - (void) setDelegate:(id)delegate {
3669 delegate_ = delegate;
3670 status_.setDelegate(delegate);
3671 progress_.setDelegate(delegate);
3674 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3675 SourceMap::const_iterator i(sources_.find(file->ID));
3676 return i == sources_.end() ? nil : i->second;
3679 - (NSString *) mappedSectionForPointer:(const char *)section {
3680 _H<NSString> *mapped;
3682 _profile(Database$mappedSectionForPointer$Cache)
3683 mapped = §ions_[section];
3686 if (*mapped == NULL) {
3687 size_t length(strlen(section));
3688 char spaced[length + 1];
3690 _profile(Database$mappedSectionForPointer$Replace)
3691 for (size_t index(0); index != length; ++index)
3692 spaced[index] = section[index] == '_' ? ' ' : section[index];
3693 spaced[length] = '\0';
3698 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3699 string = [NSString stringWithUTF8String:spaced];
3702 _profile(Database$mappedSectionForPointer$Map)
3703 string = [SectionMap_ objectForKey:string] ?: string;
3713 /* Web Scripting {{{ */
3714 @interface CydiaObject : NSObject {
3716 _transient id delegate_;
3719 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3722 @implementation CydiaObject
3725 [indirect_ release];
3729 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3730 if ((self = [super init]) != nil) {
3731 indirect_ = [indirect retain];
3735 - (void) setDelegate:(id)delegate {
3736 delegate_ = delegate;
3739 + (NSArray *) _attributeKeys {
3740 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3743 - (NSArray *) attributeKeys {
3744 return [[self class] _attributeKeys];
3747 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3748 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3751 - (NSString *) device {
3752 return [[UIDevice currentDevice] uniqueIdentifier];
3755 #if 0 // XXX: implement!
3756 - (NSString *) mac {
3757 if (![indirect_ promptForSensitive:@"Mac Address"])
3761 - (NSString *) serial {
3762 if (![indirect_ promptForSensitive:@"Serial #"])
3766 - (NSString *) firewire {
3767 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3771 - (NSString *) imei {
3772 if (![indirect_ promptForSensitive:@"IMEI"])
3777 + (NSString *) webScriptNameForSelector:(SEL)selector {
3778 if (selector == @selector(close))
3780 else if (selector == @selector(getInstalledPackages))
3781 return @"getInstalledPackages";
3782 else if (selector == @selector(getPackageById:))
3783 return @"getPackageById";
3784 else if (selector == @selector(installPackages:))
3785 return @"installPackages";
3786 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3787 return @"setButtonImage";
3788 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3789 return @"setButtonTitle";
3790 else if (selector == @selector(setPopupHook:))
3791 return @"setPopupHook";
3792 else if (selector == @selector(setSpecial:))
3793 return @"setSpecial";
3794 else if (selector == @selector(setToken:))
3796 else if (selector == @selector(setViewportWidth:))
3797 return @"setViewportWidth";
3798 else if (selector == @selector(supports:))
3800 else if (selector == @selector(stringWithFormat:arguments:))
3802 else if (selector == @selector(localizedStringForKey:value:table:))
3804 else if (selector == @selector(du:))
3806 else if (selector == @selector(statfs:))
3812 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3813 return [self webScriptNameForSelector:selector] == nil;
3816 - (BOOL) supports:(NSString *)feature {
3817 return [feature isEqualToString:@"window.open"];
3820 - (NSArray *) getInstalledPackages {
3821 NSArray *packages([[Database sharedInstance] packages]);
3822 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3823 for (Package *package in packages)
3824 if ([package installed] != nil)
3825 [installed addObject:package];
3829 - (Package *) getPackageById:(NSString *)id {
3830 Package *package([[Database sharedInstance] packageWithName:id]);
3835 - (NSArray *) statfs:(NSString *)path {
3838 if (path == nil || statfs([path UTF8String], &stat) == -1)
3841 return [NSArray arrayWithObjects:
3842 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3843 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3844 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3848 - (NSNumber *) du:(NSString *)path {
3849 NSNumber *value(nil);
3852 _assert(pipe(fds) != -1);
3854 pid_t pid(ExecFork());
3856 _assert(dup2(fds[1], 1) != -1);
3857 _assert(close(fds[0]) != -1);
3858 _assert(close(fds[1]) != -1);
3859 /* XXX: this should probably not use du */
3860 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3865 _assert(close(fds[1]) != -1);
3867 if (FILE *du = fdopen(fds[0], "r")) {
3869 while (fgets(line, sizeof(line), du) != NULL) {
3870 size_t length(strlen(line));
3871 while (length != 0 && line[length - 1] == '\n')
3872 line[--length] = '\0';
3873 if (char *tab = strchr(line, '\t')) {
3875 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3880 } else _assert(close(fds[0]));
3884 if (waitpid(pid, &status, 0) == -1)
3887 else _assert(false);
3896 - (void) installPackages:(NSArray *)packages {
3897 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3900 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3901 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3904 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3905 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3908 - (void) setSpecial:(id)function {
3909 [indirect_ setSpecial:function];
3912 - (void) setToken:(NSString *)token {
3915 Token_ = [token retain];
3917 [Metadata_ setObject:Token_ forKey:@"Token"];
3921 - (void) setPopupHook:(id)function {
3922 [indirect_ setPopupHook:function];
3925 - (void) setViewportWidth:(float)width {
3926 [indirect_ setViewportWidth:width];
3929 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3930 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3931 unsigned count([arguments count]);
3933 for (unsigned i(0); i != count; ++i)
3934 values[i] = [arguments objectAtIndex:i];
3935 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3938 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3939 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3941 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3943 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3949 /* @ Loading... Indicator {{{ */
3950 @interface CYLoadingIndicator : UIView {
3951 UIActivityIndicatorView *spinner_;
3956 @property (readonly, nonatomic) UILabel *label;
3957 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
3961 @implementation CYLoadingIndicator
3963 - (id)initWithFrame:(CGRect)frame {
3964 if ((self = [super initWithFrame:frame])) {
3965 container_ = [[[UIView alloc] init] autorelease];
3966 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
3968 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
3969 [spinner_ startAnimating];
3970 [container_ addSubview:spinner_];
3972 label_ = [[[UILabel alloc] init] autorelease];
3973 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
3974 [label_ setBackgroundColor:[UIColor clearColor]];
3975 [label_ setTextColor:[UIColor blackColor]];
3976 [label_ setShadowColor:[UIColor whiteColor]];
3977 [label_ setShadowOffset:CGSizeMake(0, 1)];
3978 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
3979 [container_ addSubview:label_];
3981 CGSize viewsize = frame.size;
3982 CGSize spinnersize = [spinner_ bounds].size;
3983 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
3984 float bothwidth = spinnersize.width + textsize.width + 5.0f;
3986 CGRect containrect = {
3987 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
3988 CGSizeMake(bothwidth, spinnersize.height)
3991 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
3999 [container_ setFrame:containrect];
4000 [spinner_ setFrame:spinrect];
4001 [label_ setFrame:textrect];
4002 [self addSubview:container_];
4008 - (UILabel *)label { return label_; }
4009 - (UIActivityIndicatorView *)activityIndicatorView { return spinner_; }
4013 /* Emulated Loading Controller {{{ */
4014 @interface CYEmulatedLoadingController : CYViewController <
4016 ConfigurationDelegate
4018 _transient Database *database_;
4019 CYLoadingIndicator *indicator_;
4021 UINavigationBar *navbar_;
4025 @implementation CYEmulatedLoadingController
4028 [self releaseSubviews];
4029 [database_ setDelegate:nil];
4034 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4035 CYAlertView *sheet([[[CYAlertView alloc]
4037 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4038 defaultButtonIndex:0
4041 [sheet setMessage:error];
4042 [sheet yieldToPopupAlertAnimated:YES];
4046 - (void) setProgressTitle:(NSString *)title { }
4047 - (void) setProgressPercent:(float)percent { }
4048 - (void) startProgress { }
4049 - (void) addProgressOutput:(NSString *)output { }
4050 - (bool) isCancelling:(size_t)received { return NO; }
4051 - (void) setConfigurationData:(NSString *)data { }
4053 - (void) repairWithSelector:(SEL)selector {
4054 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("REPAIRING"), nil] waitUntilDone:YES];
4055 [database_ performSelector:selector];
4057 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil] waitUntilDone:YES];
4060 - (id) initWithDatabase:(Database *)database {
4061 if ((self = [super init])) {
4062 database_ = database;
4063 [database_ setDelegate:self];
4068 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4069 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4071 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4072 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4073 [[self view] addSubview:indicator_];
4075 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4076 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4077 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4078 [[self view] addSubview:tabbar_];
4080 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4081 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4082 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4083 [[self view] addSubview:navbar_];
4086 - (void) releaseSubviews {
4087 [indicator_ release];
4100 /* Cydia Browser Controller {{{ */
4101 @interface CYBrowserController : BrowserController {
4102 CydiaObject *cydia_;
4107 @implementation CYBrowserController
4114 - (NSURL *) navigationURL {
4115 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4118 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4121 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4122 [super webView:view didClearWindowObject:window forFrame:frame];
4124 WebDataSource *source([frame dataSource]);
4125 NSURLResponse *response([source response]);
4127 NSURL *url([response URL]);
4128 NSString *scheme([url scheme]);
4129 NSString *host([url host]);
4131 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4132 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4133 NSDictionary *headers([http allHeaderFields]);
4134 [self setHeaders:headers forHost:host];
4138 [host isEqualToString:@"cydia.saurik.com"] ||
4139 [host hasSuffix:@".cydia.saurik.com"] ||
4140 [scheme isEqualToString:@"file"]
4142 [window setValue:cydia_ forKey:@"cydia"];
4145 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4146 if (System_ != NULL)
4147 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4148 if (Machine_ != NULL)
4149 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4151 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4153 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4156 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4157 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4158 [self _setMoreHeaders:copy];
4162 - (void) setDelegate:(id)delegate {
4163 [super setDelegate:delegate];
4164 [cydia_ setDelegate:delegate];
4168 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4169 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4171 WebView *webview([[webview_ _documentView] webView]);
4173 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4175 NSString *application = package == nil ? @"Cydia" : [NSString
4176 stringWithFormat:@"Cydia/%@",
4181 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4183 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4184 if (Product_ != nil)
4185 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4187 [webview setApplicationNameForUserAgent:application];
4195 @interface NSObject (CydiaScript)
4196 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4199 @implementation NSObject (CydiaScript)
4201 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4207 @implementation NSArray (CydiaScript)
4209 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4210 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4211 for (size_t i(0), e([self count]); i != e; ++i)
4212 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4218 @implementation NSDictionary (CydiaScript)
4220 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4221 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4223 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4230 /* Confirmation Controller {{{ */
4231 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4232 if (!iterator.end())
4233 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4234 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4236 pkgCache::PkgIterator package(dep.TargetPkg());
4239 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4246 @protocol ConfirmationControllerDelegate
4247 - (void) cancelAndClear:(bool)clear;
4248 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4252 @interface ConfirmationController : CYBrowserController {
4253 _transient Database *database_;
4254 UIAlertView *essential_;
4261 - (id) initWithDatabase:(Database *)database;
4265 @implementation ConfirmationController
4272 if (essential_ != nil)
4273 [essential_ release];
4277 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4278 NSString *context([alert context]);
4280 if ([context isEqualToString:@"remove"]) {
4281 if (button == [alert cancelButtonIndex]) {
4282 [self dismissModalViewControllerAnimated:YES];
4283 } else if (button == [alert firstOtherButtonIndex]) {
4286 [delegate_ confirmWithNavigationController:[self navigationController]];
4289 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4290 } else if ([context isEqualToString:@"unable"]) {
4291 [self dismissModalViewControllerAnimated:YES];
4292 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4294 [super alertView:alert clickedButtonAtIndex:button];
4298 - (void) _doContinue {
4299 [self dismissModalViewControllerAnimated:YES];
4300 [delegate_ cancelAndClear:NO];
4303 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4304 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4308 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4309 [super webView:view didClearWindowObject:window forFrame:frame];
4310 [window setValue:changes_ forKey:@"changes"];
4311 [window setValue:issues_ forKey:@"issues"];
4312 [window setValue:sizes_ forKey:@"sizes"];
4313 [window setValue:self forKey:@"queue"];
4316 - (id) initWithDatabase:(Database *)database {
4317 if ((self = [super init]) != nil) {
4318 database_ = database;
4320 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4321 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4322 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4323 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4324 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4328 pkgDepCache::Policy *policy([database_ policy]);
4330 pkgCacheFile &cache([database_ cache]);
4331 NSArray *packages = [database_ packages];
4332 for (Package *package in packages) {
4333 pkgCache::PkgIterator iterator = [package iterator];
4334 pkgDepCache::StateCache &state(cache[iterator]);
4336 NSString *name([package name]);
4338 if (state.NewInstall())
4339 [installing addObject:name];
4340 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4341 [reinstalling addObject:name];
4342 else if (state.Upgrade())
4343 [upgrading addObject:name];
4344 else if (state.Downgrade())
4345 [downgrading addObject:name];
4346 else if (state.Delete()) {
4347 if ([package essential])
4349 [removing addObject:name];
4352 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4353 substrate_ |= DepSubstrate(iterator.CurrentVer());
4358 else if (Advanced_) {
4359 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4361 essential_ = [[UIAlertView alloc]
4362 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4363 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4365 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4367 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4371 [essential_ setContext:@"remove"];
4373 essential_ = [[UIAlertView alloc]
4374 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4375 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4377 cancelButtonTitle:UCLocalize("OKAY")
4378 otherButtonTitles:nil
4381 [essential_ setContext:@"unable"];
4384 changes_ = [[NSArray alloc] initWithObjects:
4392 issues_ = [database_ issues];
4394 issues_ = [issues_ retain];
4396 sizes_ = [[NSArray alloc] initWithObjects:
4397 SizeString([database_ fetcher].FetchNeeded()),
4398 SizeString([database_ fetcher].PartialPresent()),
4401 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4403 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4404 initWithTitle:UCLocalize("CANCEL")
4405 style:UIBarButtonItemStylePlain
4407 action:@selector(cancelButtonClicked)
4412 - (void) applyRightButton {
4414 if (issues_ == nil && ![self isLoading])
4415 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4416 initWithTitle:UCLocalize("CONFIRM")
4417 style:UIBarButtonItemStyleDone
4419 action:@selector(confirmButtonClicked)
4422 [super applyRightButton];
4424 [[self navigationItem] setRightBarButtonItem:nil];
4428 - (void) cancelButtonClicked {
4429 [self dismissModalViewControllerAnimated:YES];
4430 [delegate_ cancelAndClear:YES];
4434 - (void) confirmButtonClicked {
4435 if (essential_ != nil)
4440 [delegate_ confirmWithNavigationController:[self navigationController]];
4448 /* Progress Data {{{ */
4449 @interface ProgressData : NSObject {
4451 // XXX: should these really both be _transient?
4452 _transient id target_;
4453 _transient id object_;
4456 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4463 @implementation ProgressData
4465 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4466 if ((self = [super init]) != nil) {
4467 selector_ = selector;
4487 /* Progress Controller {{{ */
4488 @interface ProgressController : CYViewController <
4489 ConfigurationDelegate,
4492 _transient Database *database_;
4493 UIProgressBar *progress_;
4494 UITextView *output_;
4495 UITextLabel *status_;
4496 UIPushButton *close_;
4498 SHA1SumValue springlist_;
4499 SHA1SumValue notifyconf_;
4503 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4505 - (void) _retachThread;
4506 - (void) _detachNewThreadData:(ProgressData *)data;
4507 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4513 @protocol ProgressControllerDelegate
4514 - (void) progressControllerIsComplete:(ProgressController *)sender;
4517 @implementation ProgressController
4520 [database_ setDelegate:nil];
4521 [progress_ release];
4530 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4531 if ((self = [super init]) != nil) {
4532 database_ = database;
4533 [database_ setDelegate:self];
4534 delegate_ = delegate;
4536 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4538 progress_ = [[UIProgressBar alloc] init];
4539 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4540 [progress_ setStyle:0];
4542 status_ = [[UITextLabel alloc] init];
4543 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4544 [status_ setColor:[UIColor whiteColor]];
4545 [status_ setBackgroundColor:[UIColor clearColor]];
4546 [status_ setCentersHorizontally:YES];
4547 //[status_ setFont:font];
4549 output_ = [[UITextView alloc] init];
4550 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4551 //[output_ setTextFont:@"Courier New"];
4552 [output_ setFont:[[output_ font] fontWithSize:12]];
4553 [output_ setTextColor:[UIColor whiteColor]];
4554 [output_ setBackgroundColor:[UIColor clearColor]];
4555 [output_ setMarginTop:0];
4556 [output_ setAllowsRubberBanding:YES];
4557 [output_ setEditable:NO];
4558 [[self view] addSubview:output_];
4560 close_ = [[UIPushButton alloc] init];
4561 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4562 [close_ setAutosizesToFit:NO];
4563 [close_ setDrawsShadow:YES];
4564 [close_ setStretchBackground:YES];
4565 [close_ setEnabled:YES];
4566 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4567 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4568 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4569 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4573 - (void) positionViews {
4574 CGRect bounds = [[self view] bounds];
4575 CGSize prgsize = [UIProgressBar defaultSize];
4578 (bounds.size.width - prgsize.width) / 2,
4579 bounds.size.height - prgsize.height - 20
4582 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4584 [progress_ setFrame:prgrect];
4585 [status_ setFrame:CGRectMake(
4587 bounds.size.height - prgsize.height - 50,
4588 bounds.size.width - 20,
4591 [output_ setFrame:CGRectMake(
4594 bounds.size.width - 20,
4595 bounds.size.height - 96
4597 [close_ setFrame:CGRectMake(
4598 (bounds.size.width - closewidth) / 2,
4599 bounds.size.height - prgsize.height - 50,
4605 - (void) viewWillAppear:(BOOL)animated {
4606 [super viewDidAppear:animated];
4607 [[self navigationItem] setHidesBackButton:YES];
4608 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4610 [self positionViews];
4613 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4614 [self positionViews];
4617 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4618 NSString *context([alert context]);
4620 if ([context isEqualToString:@"conffile"]) {
4621 FILE *input = [database_ input];
4622 if (button == [alert cancelButtonIndex])
4623 fprintf(input, "N\n");
4624 else if (button == [alert firstOtherButtonIndex])
4625 fprintf(input, "Y\n");
4630 - (void) closeButtonPushed {
4633 UpdateExternalStatus(0);
4637 [self dismissModalViewControllerAnimated:YES];
4641 [delegate_ terminateWithSuccess];
4642 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4643 [delegate_ suspendWithAnimation:YES];
4645 [delegate_ suspend];*/
4657 system("/usr/bin/sbreload");
4663 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4664 SBReboot(SBSSpringBoardServerPort());
4666 reboot2(RB_AUTOBOOT);
4671 - (void) _retachThread {
4672 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4674 [[self view] addSubview:close_];
4675 [progress_ removeFromSuperview];
4676 [status_ removeFromSuperview];
4678 [database_ popErrorWithTitle:title_];
4679 [delegate_ progressControllerIsComplete:self];
4683 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4686 MMap mmap(file, MMap::ReadOnly);
4688 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4689 if (!(notifyconf_ == sha1.Result()))
4696 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4699 MMap mmap(file, MMap::ReadOnly);
4701 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4702 if (!(springlist_ == sha1.Result()))
4708 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4709 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4710 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4711 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4712 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4716 system("su -c /usr/bin/uicache mobile");
4719 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4721 [delegate_ setStatusBarShowsProgress:NO];
4724 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4725 [[data target] performSelector:[data selector] withObject:[data object]];
4726 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4729 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4730 UpdateExternalStatus(1);
4737 title_ = [title retain];
4739 [[self navigationItem] setTitle:title_];
4741 [status_ setText:nil];
4742 [output_ setText:@""];
4743 [progress_ setProgress:0];
4745 [close_ removeFromSuperview];
4746 [[self view] addSubview:progress_];
4747 [[self view] addSubview:status_];
4749 [delegate_ setStatusBarShowsProgress:YES];
4754 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4757 MMap mmap(file, MMap::ReadOnly);
4759 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4760 notifyconf_ = sha1.Result();
4766 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4769 MMap mmap(file, MMap::ReadOnly);
4771 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4772 springlist_ = sha1.Result();
4777 detachNewThreadSelector:@selector(_detachNewThreadData:)
4779 withObject:[[[ProgressData alloc]
4780 initWithSelector:selector
4787 - (void) repairWithSelector:(SEL)selector {
4789 detachNewThreadSelector:selector
4792 title:UCLocalize("REPAIRING")
4796 - (void) setConfigurationData:(NSString *)data {
4798 performSelectorOnMainThread:@selector(_setConfigurationData:)
4804 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4805 CYAlertView *sheet([[[CYAlertView alloc]
4807 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4808 defaultButtonIndex:0
4811 [sheet setMessage:error];
4812 [sheet yieldToPopupAlertAnimated:YES];
4816 - (void) setProgressTitle:(NSString *)title {
4818 performSelectorOnMainThread:@selector(_setProgressTitle:)
4824 - (void) setProgressPercent:(float)percent {
4826 performSelectorOnMainThread:@selector(_setProgressPercent:)
4827 withObject:[NSNumber numberWithFloat:percent]
4832 - (void) startProgress {
4835 - (void) addProgressOutput:(NSString *)output {
4837 performSelectorOnMainThread:@selector(_addProgressOutput:)
4843 - (bool) isCancelling:(size_t)received {
4847 - (void) _setConfigurationData:(NSString *)data {
4848 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4850 if (!conffile_r(data)) {
4851 lprintf("E:invalid conffile\n");
4855 NSString *ofile = conffile_r[1];
4856 //NSString *nfile = conffile_r[2];
4858 UIAlertView *alert = [[[UIAlertView alloc]
4859 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4860 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4862 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4864 UCLocalize("ACCEPT_NEW_COPY"),
4865 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4869 [alert setContext:@"conffile"];
4873 - (void) _setProgressTitle:(NSString *)title {
4874 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4875 for (size_t i(0), e([words count]); i != e; ++i) {
4876 NSString *word([words objectAtIndex:i]);
4877 if (Package *package = [database_ packageWithName:word])
4878 [words replaceObjectAtIndex:i withObject:[package name]];
4881 [status_ setText:[words componentsJoinedByString:@" "]];
4884 - (void) _setProgressPercent:(NSNumber *)percent {
4885 [progress_ setProgress:[percent floatValue]];
4888 - (void) _addProgressOutput:(NSString *)output {
4889 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4890 CGSize size = [output_ contentSize];
4891 CGPoint offset = [output_ contentOffset];
4892 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4893 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4894 [output_ scrollRectToVisible:rect animated:YES];
4898 - (BOOL) isRunning {
4905 /* Cell Content View {{{ */
4906 @protocol ContentDelegate
4907 - (void) drawContentRect:(CGRect)rect;
4910 @interface ContentView : UIView {
4911 _transient id<ContentDelegate> delegate_;
4916 @implementation ContentView
4918 - (id) initWithFrame:(CGRect)frame {
4919 if ((self = [super initWithFrame:frame]) != nil) {
4920 [self setNeedsDisplayOnBoundsChange:YES];
4924 - (void) setDelegate:(id<ContentDelegate>)delegate {
4925 delegate_ = delegate;
4928 - (void) drawRect:(CGRect)rect {
4929 [super drawRect:rect];
4930 [delegate_ drawContentRect:rect];
4935 /* Cydia TableView Cell {{{ */
4936 @interface CYTableViewCell : UITableViewCell {
4937 ContentView *content_;
4943 @implementation CYTableViewCell
4950 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4951 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4953 if (view == content_) {
4954 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4955 highlighted_ = highlighted;
4958 [super _updateHighlightColorsForView:view highlighted:highlighted];
4961 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4962 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4963 highlighted_ = selected;
4965 [super setSelected:selected animated:animated];
4966 [content_ setNeedsDisplay];
4972 /* Package Cell {{{ */
4973 @interface PackageCell : CYTableViewCell <
4978 NSString *description_;
4986 - (PackageCell *) init;
4987 - (void) setPackage:(Package *)package;
4989 - (void) drawContentRect:(CGRect)rect;
4993 @implementation PackageCell
4995 - (void) clearPackage {
5006 if (description_ != nil) {
5007 [description_ release];
5011 if (source_ != nil) {
5016 if (badge_ != nil) {
5021 if (placard_ != nil) {
5031 [self clearPackage];
5035 - (PackageCell *) init {
5036 CGRect frame(CGRectMake(0, 0, 320, 74));
5037 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5038 UIView *content([self contentView]);
5039 CGRect bounds([content bounds]);
5041 content_ = [[ContentView alloc] initWithFrame:bounds];
5042 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5043 [content addSubview:content_];
5045 [content_ setDelegate:self];
5046 [content_ setOpaque:YES];
5050 - (NSString *) accessibilityLabel {
5051 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5054 - (void) setPackage:(Package *)package {
5055 [self clearPackage];
5058 Source *source = [package source];
5060 icon_ = [[package icon] retain];
5061 name_ = [[package name] retain];
5064 description_ = [package longDescription];
5065 if (description_ == nil)
5066 description_ = [package shortDescription];
5067 if (description_ != nil)
5068 description_ = [description_ retain];
5070 commercial_ = [package isCommercial];
5072 package_ = [package retain];
5074 NSString *label = nil;
5075 bool trusted = false;
5077 if (source != nil) {
5078 label = [source label];
5079 trusted = [source trusted];
5080 } else if ([[package id] isEqualToString:@"firmware"])
5081 label = UCLocalize("APPLE");
5083 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5085 NSString *from(label);
5087 NSString *section = [package simpleSection];
5088 if (section != nil && ![section isEqualToString:label]) {
5089 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5090 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5093 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5094 source_ = [from retain];
5096 if (NSString *purpose = [package primaryPurpose])
5097 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5098 badge_ = [badge_ retain];
5103 if (NSString *mode = [package_ mode]) {
5104 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5105 color = RemovingColor_;
5106 //placard = @"removing";
5108 color = InstallingColor_;
5109 //placard = @"installing";
5112 // XXX: the removing/installing placards are not @2x
5115 color = [UIColor whiteColor];
5117 if ([package installed] != nil)
5118 placard = @"installed";
5123 [content_ setBackgroundColor:color];
5126 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5127 placard_ = [placard_ retain];
5129 [self setNeedsDisplay];
5130 [content_ setNeedsDisplay];
5133 - (void) drawContentRect:(CGRect)rect {
5134 bool highlighted(highlighted_);
5135 float width([self bounds].size.width);
5138 CGContextRef context(UIGraphicsGetCurrentContext());
5139 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5140 CGContextFillRect(context, rect);
5145 rect.size = [icon_ size];
5147 rect.size.width /= 2;
5148 rect.size.height /= 2;
5150 rect.origin.x = 25 - rect.size.width / 2;
5151 rect.origin.y = 25 - rect.size.height / 2;
5153 [icon_ drawInRect:rect];
5156 if (badge_ != nil) {
5158 rect.size = [badge_ size];
5160 rect.size.width /= 2;
5161 rect.size.height /= 2;
5163 rect.origin.x = 36 - rect.size.width / 2;
5164 rect.origin.y = 36 - rect.size.height / 2;
5166 [badge_ drawInRect:rect];
5173 UISetColor(commercial_ ? Purple_ : Black_);
5174 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5175 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5178 UISetColor(commercial_ ? Purplish_ : Gray_);
5179 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5181 if (placard_ != nil)
5182 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5187 /* Section Cell {{{ */
5188 @interface SectionCell : CYTableViewCell <
5200 - (void) setSection:(Section *)section editing:(BOOL)editing;
5204 @implementation SectionCell
5206 - (void) clearSection {
5207 if (basic_ != nil) {
5212 if (section_ != nil) {
5222 if (count_ != nil) {
5229 [self clearSection];
5235 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5236 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5237 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5238 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5239 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5241 UIView *content([self contentView]);
5242 CGRect bounds([content bounds]);
5244 content_ = [[ContentView alloc] initWithFrame:bounds];
5245 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5246 [content addSubview:content_];
5247 [content_ setBackgroundColor:[UIColor whiteColor]];
5249 [content_ setDelegate:self];
5253 - (void) onSwitch:(id)sender {
5254 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5255 if (metadata == nil) {
5256 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5257 [Sections_ setObject:metadata forKey:basic_];
5260 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5264 - (void) setSection:(Section *)section editing:(BOOL)editing {
5265 if (editing != editing_) {
5267 [switch_ removeFromSuperview];
5269 [self addSubview:switch_];
5273 [self clearSection];
5275 if (section == nil) {
5276 name_ = [UCLocalize("ALL_PACKAGES") retain];
5279 basic_ = [section name];
5281 basic_ = [basic_ retain];
5283 section_ = [section localized];
5284 if (section_ != nil)
5285 section_ = [section_ retain];
5287 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5288 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5291 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5294 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5295 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5297 [content_ setNeedsDisplay];
5300 - (void) setFrame:(CGRect)frame {
5301 [super setFrame:frame];
5303 CGRect rect([switch_ frame]);
5304 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5307 - (NSString *) accessibilityLabel {
5311 - (void) drawContentRect:(CGRect)rect {
5312 bool highlighted(highlighted_ && !editing_);
5314 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5319 float width(rect.size.width);
5325 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5327 CGSize size = [count_ sizeWithFont:Font14_];
5331 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5337 /* File Table {{{ */
5338 @interface FileTable : CYViewController <
5339 UITableViewDataSource,
5342 _transient Database *database_;
5345 NSMutableArray *files_;
5349 - (id) initWithDatabase:(Database *)database;
5350 - (void) setPackage:(Package *)package;
5354 @implementation FileTable
5357 [self releaseSubviews];
5366 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5367 return files_ == nil ? 0 : [files_ count];
5370 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5374 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5375 static NSString *reuseIdentifier = @"Cell";
5377 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5379 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5380 [cell setFont:[UIFont systemFontOfSize:16]];
5382 [cell setText:[files_ objectAtIndex:indexPath.row]];
5383 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5388 - (NSURL *) navigationURL {
5389 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5393 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5395 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5396 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5397 [list_ setRowHeight:24.0f];
5398 [list_ setDataSource:self];
5399 [list_ setDelegate:self];
5400 [[self view] addSubview:list_];
5403 - (void) viewDidLoad {
5404 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5407 - (void) releaseSubviews {
5412 - (id) initWithDatabase:(Database *)database {
5413 if ((self = [super init]) != nil) {
5414 database_ = database;
5416 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5420 - (void) setPackage:(Package *)package {
5421 if (package_ != nil) {
5422 [package_ autorelease];
5431 [files_ removeAllObjects];
5433 if (package != nil) {
5434 package_ = [package retain];
5435 name_ = [[package id] retain];
5437 if (NSArray *files = [package files])
5438 [files_ addObjectsFromArray:files];
5440 if ([files_ count] != 0) {
5441 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5442 [files_ removeObjectAtIndex:0];
5443 [files_ sortUsingSelector:@selector(compareByPath:)];
5445 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5446 [stack addObject:@"/"];
5448 for (int i(0), e([files_ count]); i != e; ++i) {
5449 NSString *file = [files_ objectAtIndex:i];
5450 while (![file hasPrefix:[stack lastObject]])
5451 [stack removeLastObject];
5452 NSString *directory = [stack lastObject];
5453 [stack addObject:[file stringByAppendingString:@"/"]];
5454 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5455 ([stack count] - 2) * 3, "",
5456 [file substringFromIndex:[directory length]]
5465 - (void) reloadData {
5468 [self setPackage:[database_ packageWithName:name_]];
5473 /* Package Controller {{{ */
5474 @interface CYPackageController : CYBrowserController <
5475 UIActionSheetDelegate
5477 _transient Database *database_;
5481 NSMutableArray *buttons_;
5482 UIBarButtonItem *button_;
5485 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5489 @implementation CYPackageController
5492 if (package_ != nil)
5505 - (NSURL *) navigationURL {
5506 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5509 /* XXX: this is not safe at all... localization of /fail/ */
5510 - (void) _clickButtonWithName:(NSString *)name {
5511 if ([name isEqualToString:UCLocalize("CLEAR")])
5512 [delegate_ clearPackage:package_];
5513 else if ([name isEqualToString:UCLocalize("INSTALL")])
5514 [delegate_ installPackage:package_];
5515 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5516 [delegate_ installPackage:package_];
5517 else if ([name isEqualToString:UCLocalize("REMOVE")])
5518 [delegate_ removePackage:package_];
5519 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5520 [delegate_ installPackage:package_];
5521 else _assert(false);
5524 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5525 NSString *context([sheet context]);
5527 if ([context isEqualToString:@"modify"]) {
5528 if (button != [sheet cancelButtonIndex]) {
5529 NSString *buttonName = [buttons_ objectAtIndex:button];
5530 [self _clickButtonWithName:buttonName];
5533 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5537 - (bool) _allowJavaScriptPanel {
5542 - (void) _customButtonClicked {
5543 int count([buttons_ count]);
5548 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5550 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5551 [buttons addObjectsFromArray:buttons_];
5553 UIActionSheet *sheet = [[[UIActionSheet alloc]
5556 cancelButtonTitle:nil
5557 destructiveButtonTitle:nil
5558 otherButtonTitles:nil
5561 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5563 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5564 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5566 [sheet setContext:@"modify"];
5568 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5572 // We don't want to allow non-commercial packages to do custom things to the install button,
5573 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5574 - (void) customButtonClicked {
5576 [super customButtonClicked];
5578 [self _customButtonClicked];
5581 - (void) reloadButtonClicked {
5582 // Don't reload a commerical package by tapping the loading button,
5583 // but if it's not an Install button, we should forward it on.
5584 if (![package_ uninstalled])
5585 [self _customButtonClicked];
5588 - (void) applyLoadingTitle {
5589 // Don't show "Loading" as the title. Ever.
5592 - (UIBarButtonItem *) rightButton {
5597 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5598 if ((self = [super init]) != nil) {
5599 database_ = database;
5600 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5601 name_ = [[NSString alloc] initWithString:name];
5605 - (void) reloadData {
5608 if (package_ != nil)
5609 [package_ autorelease];
5610 package_ = [database_ packageWithName:name_];
5612 [buttons_ removeAllObjects];
5614 if (package_ != nil) {
5617 package_ = [package_ retain];
5618 commercial_ = [package_ isCommercial];
5620 if ([package_ mode] != nil)
5621 [buttons_ addObject:UCLocalize("CLEAR")];
5622 if ([package_ source] == nil);
5623 else if ([package_ upgradableAndEssential:NO])
5624 [buttons_ addObject:UCLocalize("UPGRADE")];
5625 else if ([package_ uninstalled])
5626 [buttons_ addObject:UCLocalize("INSTALL")];
5628 [buttons_ addObject:UCLocalize("REINSTALL")];
5629 if (![package_ uninstalled])
5630 [buttons_ addObject:UCLocalize("REMOVE")];
5637 switch ([buttons_ count]) {
5638 case 0: title = nil; break;
5639 case 1: title = [buttons_ objectAtIndex:0]; break;
5640 default: title = UCLocalize("MODIFY"); break;
5643 button_ = [[UIBarButtonItem alloc]
5645 style:UIBarButtonItemStylePlain
5647 action:@selector(customButtonClicked)
5650 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5653 - (bool) isLoading {
5654 return commercial_ ? [super isLoading] : false;
5660 /* Package List Controller {{{ */
5661 @interface PackageListController : CYViewController <
5662 UITableViewDataSource,
5665 _transient Database *database_;
5667 NSMutableArray *packages_;
5668 NSMutableArray *sections_;
5670 NSMutableArray *index_;
5671 NSMutableDictionary *indices_;
5675 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5676 - (void) setDelegate:(id)delegate;
5677 - (void) resetCursor;
5681 @implementation PackageListController
5684 [packages_ release];
5685 [sections_ release];
5694 - (void) deselectWithAnimation:(BOOL)animated {
5695 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5698 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5699 CGRect base = [[self view] bounds];
5700 base.size.height -= bounds.size.height;
5701 base.origin = [list_ frame].origin;
5703 [UIView beginAnimations:nil context:NULL];
5704 [UIView setAnimationBeginsFromCurrentState:YES];
5705 [UIView setAnimationCurve:curve];
5706 [UIView setAnimationDuration:duration];
5707 [list_ setFrame:base];
5708 [UIView commitAnimations];
5711 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5712 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5715 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5716 [self resizeForKeyboardBounds:bounds duration:0];
5719 - (void) keyboardWillShow:(NSNotification *)notification {
5722 NSTimeInterval duration;
5723 UIViewAnimationCurve curve;
5724 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5725 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5726 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5727 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5729 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);
5730 UIViewController *base = self;
5731 while ([base parentViewController] != nil)
5732 base = [base parentViewController];
5733 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5734 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5736 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5739 - (void) keyboardWillHide:(NSNotification *)notification {
5740 NSTimeInterval duration;
5741 UIViewAnimationCurve curve;
5742 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5743 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5745 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5748 - (void) viewWillAppear:(BOOL)animated {
5749 [super viewWillAppear:animated];
5751 [self resizeForKeyboardBounds:CGRectZero];
5752 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5753 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5756 - (void) viewWillDisappear:(BOOL)animated {
5757 [super viewWillDisappear:animated];
5759 [self resizeForKeyboardBounds:CGRectZero];
5760 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5761 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5764 - (void) viewDidAppear:(BOOL)animated {
5765 [super viewDidAppear:animated];
5766 [self deselectWithAnimation:animated];
5769 - (void) didSelectPackage:(Package *)package {
5770 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5771 [view setDelegate:delegate_];
5772 [[self navigationController] pushViewController:view animated:YES];
5775 #if TryIndexedCollation
5776 + (BOOL) hasIndexedCollation {
5777 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5781 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5782 NSInteger count([sections_ count]);
5783 return count == 0 ? 1 : count;
5786 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5787 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5789 return [[sections_ objectAtIndex:section] name];
5792 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5793 if ([sections_ count] == 0)
5795 return [[sections_ objectAtIndex:section] count];
5798 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5799 @synchronized (database_) {
5800 if ([database_ era] != era_)
5803 Section *section([sections_ objectAtIndex:[path section]]);
5804 NSInteger row([path row]);
5805 Package *package([packages_ objectAtIndex:([section row] + row)]);
5806 return [[package retain] autorelease];
5809 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5810 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5812 cell = [[[PackageCell alloc] init] autorelease];
5813 [cell setPackage:[self packageAtIndexPath:path]];
5817 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5818 Package *package([self packageAtIndexPath:path]);
5819 package = [database_ packageWithName:[package id]];
5820 [self didSelectPackage:package];
5823 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5824 // XXX: is 20 the most optimal number here?
5825 return [packages_ count] > 20 ? index_ : nil;
5828 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5829 #if TryIndexedCollation
5830 if ([[self class] hasIndexedCollation]) {
5831 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5838 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5839 if ((self = [super init]) != nil) {
5840 database_ = database;
5841 title_ = [title copy];
5842 [[self navigationItem] setTitle:title_];
5844 #if TryIndexedCollation
5845 if ([[self class] hasIndexedCollation])
5846 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
5849 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5851 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5853 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5854 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5856 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
5857 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5858 [list_ setRowHeight:73];
5859 [[self view] addSubview:list_];
5861 [list_ setDataSource:self];
5862 [list_ setDelegate:self];
5866 - (void) setDelegate:(id)delegate {
5867 delegate_ = delegate;
5870 - (bool) hasPackage:(Package *)package {
5874 - (void) reloadData {
5877 era_ = [database_ era];
5878 NSArray *packages = [database_ packages];
5880 [packages_ removeAllObjects];
5881 [sections_ removeAllObjects];
5883 _profile(PackageTable$reloadData$Filter)
5884 for (Package *package in packages)
5885 if ([self hasPackage:package])
5886 [packages_ addObject:package];
5889 [indices_ removeAllObjects];
5891 Section *section = nil;
5893 #if TryIndexedCollation
5894 if ([[self class] hasIndexedCollation]) {
5895 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5896 NSArray *titles = [collation sectionIndexTitles];
5899 _profile(PackageTable$reloadData$Section)
5900 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5904 _profile(PackageTable$reloadData$Section$Package)
5905 package = [packages_ objectAtIndex:offset];
5906 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5909 while (secidx < index) {
5912 _profile(PackageTable$reloadData$Section$Allocate)
5913 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5916 _profile(PackageTable$reloadData$Section$Add)
5917 [sections_ addObject:section];
5921 [section addToCount];
5927 [index_ removeAllObjects];
5929 _profile(PackageTable$reloadData$Section)
5930 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5934 _profile(PackageTable$reloadData$Section$Package)
5935 package = [packages_ objectAtIndex:offset];
5936 index = [package index];
5939 if (section == nil || [section index] != index) {
5940 _profile(PackageTable$reloadData$Section$Allocate)
5941 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5944 [index_ addObject:[section name]];
5945 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5947 _profile(PackageTable$reloadData$Section$Add)
5948 [sections_ addObject:section];
5952 [section addToCount];
5957 _profile(PackageTable$reloadData$List)
5962 - (void) resetCursor {
5963 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5968 /* Filtered Package List Controller {{{ */
5969 @interface FilteredPackageListController : PackageListController {
5975 - (void) setObject:(id)object;
5976 - (void) setObject:(id)object forFilter:(SEL)filter;
5978 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5982 @implementation FilteredPackageListController
5990 - (void) setFilter:(SEL)filter {
5993 /* XXX: this is an unsafe optimization of doomy hell */
5994 Method method(class_getInstanceMethod([Package class], filter));
5995 _assert(method != NULL);
5996 imp_ = method_getImplementation(method);
5997 _assert(imp_ != NULL);
6000 - (void) setObject:(id)object {
6006 object_ = [object retain];
6009 - (void) setObject:(id)object forFilter:(SEL)filter {
6010 [self setFilter:filter];
6011 [self setObject:object];
6014 - (bool) hasPackage:(Package *)package {
6015 _profile(FilteredPackageTable$hasPackage)
6016 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6020 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6021 if ((self = [super initWithDatabase:database title:title]) != nil) {
6022 [self setFilter:filter];
6023 [self setObject:object];
6031 /* Home Controller {{{ */
6032 @interface HomeController : CYBrowserController {
6036 @implementation HomeController
6038 + (BOOL) shouldHideNavigationBar {
6042 - (NSURL *) navigationURL {
6043 return [NSURL URLWithString:@"cydia://home"];
6046 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6047 [super _setMoreHeaders:request];
6050 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6051 if (UniqueID_ != nil)
6052 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6054 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6057 - (void) aboutButtonClicked {
6058 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6060 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6061 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6062 [alert setCancelButtonIndex:0];
6065 @"Copyright (C) 2008-2011\n"
6066 "Jay Freeman (saurik)\n"
6067 "saurik@saurik.com\n"
6068 "http://www.saurik.com/"
6074 - (void) viewWillDisappear:(BOOL)animated {
6075 [super viewWillDisappear:animated];
6077 if ([[self class] shouldHideNavigationBar])
6078 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6081 - (void) viewWillAppear:(BOOL)animated {
6082 if (![self hasLoaded])
6083 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6085 [super viewWillAppear:animated];
6087 if ([[self class] shouldHideNavigationBar])
6088 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6091 - (void) viewDidLoad {
6092 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6093 initWithTitle:UCLocalize("ABOUT")
6094 style:UIBarButtonItemStylePlain
6096 action:@selector(aboutButtonClicked)
6102 /* Manage Controller {{{ */
6103 @interface ManageController : CYBrowserController {
6106 - (void) queueStatusDidChange;
6109 @implementation ManageController
6111 - (NSURL *) navigationURL {
6112 return [NSURL URLWithString:@"cydia://manage"];
6115 - (void) viewWillAppear:(BOOL)animated {
6116 if (![self hasLoaded])
6117 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6119 [super viewWillAppear:animated];
6122 - (void) viewDidLoad {
6123 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6124 initWithTitle:UCLocalize("SETTINGS")
6125 style:UIBarButtonItemStylePlain
6127 action:@selector(settingsButtonClicked)
6130 [self queueStatusDidChange];
6133 - (void) settingsButtonClicked {
6134 [delegate_ showSettings];
6138 - (void) queueButtonClicked {
6142 - (void) applyLoadingTitle {
6143 // Disable "Loading" title.
6146 - (void) applyRightButton {
6147 // Disable right button.
6151 - (void) queueStatusDidChange {
6153 if (!IsWildcat_ && Queuing_) {
6154 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6155 initWithTitle:UCLocalize("QUEUE")
6156 style:UIBarButtonItemStyleDone
6158 action:@selector(queueButtonClicked)
6161 [[self navigationItem] setRightBarButtonItem:nil];
6166 - (bool) isLoading {
6167 // Never show as loading.
6174 /* Refresh Bar {{{ */
6175 @interface RefreshBar : UINavigationBar {
6176 UIProgressIndicator *indicator_;
6177 UITextLabel *prompt_;
6178 UIProgressBar *progress_;
6179 UINavigationButton *cancel_;
6184 @implementation RefreshBar
6187 [indicator_ release];
6189 [progress_ release];
6194 - (void) positionViews {
6195 CGRect frame = [cancel_ frame];
6196 frame.size = [cancel_ sizeThatFits:frame.size];
6197 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6198 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6199 [cancel_ setFrame:frame];
6201 CGSize prgsize = {75, 100};
6203 [self frame].size.width - prgsize.width - 10,
6204 ([self frame].size.height - prgsize.height) / 2
6206 [progress_ setFrame:prgrect];
6208 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6209 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6210 CGRect indrect = {{indoffset, indoffset}, indsize};
6211 [indicator_ setFrame:indrect];
6213 CGSize prmsize = {215, indsize.height + 4};
6215 indoffset * 2 + indsize.width,
6216 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6218 [prompt_ setFrame:prmrect];
6221 - (void)setFrame:(CGRect)frame {
6222 [super setFrame:frame];
6224 [self positionViews];
6227 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6228 if ((self = [super initWithFrame:frame])) {
6229 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6231 [self setBarStyle:UIBarStyleBlack];
6233 UIBarStyle barstyle([self _barStyle:NO]);
6234 bool ugly(barstyle == UIBarStyleDefault);
6236 UIProgressIndicatorStyle style = ugly ?
6237 UIProgressIndicatorStyleMediumBrown :
6238 UIProgressIndicatorStyleMediumWhite;
6240 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6241 [indicator_ setStyle:style];
6242 [indicator_ startAnimation];
6243 [self addSubview:indicator_];
6245 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6246 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6247 [prompt_ setBackgroundColor:[UIColor clearColor]];
6248 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6249 [self addSubview:prompt_];
6251 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6252 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6253 [progress_ setStyle:0];
6254 [self addSubview:progress_];
6256 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6257 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6258 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6259 [cancel_ setBarStyle:barstyle];
6261 [self positionViews];
6266 [cancel_ removeFromSuperview];
6270 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6271 [progress_ setProgress:0];
6272 [self addSubview:cancel_];
6276 [cancel_ removeFromSuperview];
6279 - (void) setPrompt:(NSString *)prompt {
6280 [prompt_ setText:prompt];
6283 - (void) setProgress:(float)progress {
6284 [progress_ setProgress:progress];
6290 @class CYNavigationController;
6292 /* Cydia Tab Bar Controller {{{ */
6293 @interface CYTabBarController : UITabBarController <
6294 UITabBarControllerDelegate,
6297 _transient Database *database_;
6298 RefreshBar *refreshbar_;
6302 // XXX: ok, "updatedelegate_"?...
6303 _transient NSObject<CydiaDelegate> *updatedelegate_;
6306 UIViewController *remembered_;
6307 _transient UIViewController *transient_;
6310 - (NSArray *) navigationURLCollection;
6311 - (void) dropBar:(BOOL)animated;
6312 - (void) beginUpdate;
6313 - (void) raiseBar:(BOOL)animated;
6318 @implementation CYTabBarController
6320 - (void) setUnselectedViewController:(UIViewController *)transient {
6321 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6322 if (transient != nil) {
6323 if (transient_ == nil)
6324 remembered_ = [[controllers objectAtIndex:0] retain];
6325 transient_ = transient;
6326 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6327 [controllers replaceObjectAtIndex:0 withObject:transient_];
6328 [self setSelectedIndex:0];
6329 [self setViewControllers:controllers];
6330 [self concealTabBarSelection];
6331 } else if (remembered_ != nil) {
6332 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6333 transient_ = transient;
6334 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6335 [remembered_ release];
6337 [self setViewControllers:controllers];
6338 [self revealTabBarSelection];
6342 - (UIViewController *) unselectedViewController {
6346 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6347 if ([self unselectedViewController])
6348 [self setUnselectedViewController:nil];
6351 - (NSArray *) navigationURLCollection {
6352 NSMutableArray *items([NSMutableArray array]);
6354 // XXX: Should this deal with transient view controllers?
6355 for (id navigation in [self viewControllers]) {
6356 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6358 [items addObject:stack];
6364 - (void) reloadData {
6365 for (CYViewController *controller in [self viewControllers])
6366 [controller reloadData];
6368 [(CYNavigationController *)[self unselectedViewController] reloadData];
6372 [refreshbar_ release];
6373 [[NSNotificationCenter defaultCenter] removeObserver:self];
6378 - (id) initWithDatabase:(Database *)database {
6379 if ((self = [super init]) != nil) {
6380 database_ = database;
6381 [self setDelegate:self];
6383 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6384 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6386 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6390 - (void) setUpdate:(NSDate *)date {
6394 - (void) beginUpdate {
6395 [refreshbar_ start];
6398 [updatedelegate_ retainNetworkActivityIndicator];
6402 detachNewThreadSelector:@selector(performUpdate)
6408 - (void) performUpdate { _pooled
6410 status.setDelegate(self);
6411 [database_ updateWithStatus:status];
6414 performSelectorOnMainThread:@selector(completeUpdate)
6420 - (void) stopUpdateWithSelector:(SEL)selector {
6422 [updatedelegate_ releaseNetworkActivityIndicator];
6424 [self raiseBar:YES];
6427 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6430 - (void) completeUpdate {
6433 [self stopUpdateWithSelector:@selector(reloadData)];
6436 - (void) cancelUpdate {
6437 [self stopUpdateWithSelector:@selector(updateData)];
6440 - (void) cancelPressed {
6441 [self cancelUpdate];
6448 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6449 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6452 - (void) startProgress {
6455 - (void) setProgressTitle:(NSString *)title {
6457 performSelectorOnMainThread:@selector(_setProgressTitle:)
6463 - (bool) isCancelling:(size_t)received {
6467 - (void) setProgressPercent:(float)percent {
6469 performSelectorOnMainThread:@selector(_setProgressPercent:)
6470 withObject:[NSNumber numberWithFloat:percent]
6475 - (void) addProgressOutput:(NSString *)output {
6477 performSelectorOnMainThread:@selector(_addProgressOutput:)
6483 - (void) _setProgressTitle:(NSString *)title {
6484 [refreshbar_ setPrompt:title];
6487 - (void) _setProgressPercent:(NSNumber *)percent {
6488 [refreshbar_ setProgress:[percent floatValue]];
6491 - (void) _addProgressOutput:(NSString *)output {
6494 - (void) setUpdateDelegate:(id)delegate {
6495 updatedelegate_ = delegate;
6498 - (CGFloat) statusBarHeight {
6499 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6500 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6502 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6506 - (UIView *) transitionView {
6507 if ([self respondsToSelector:@selector(_transitionView)])
6508 return [self _transitionView];
6510 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6513 - (void) dropBar:(BOOL)animated {
6518 UIView *transition([self transitionView]);
6519 [[self view] addSubview:refreshbar_];
6521 CGRect barframe([refreshbar_ frame]);
6523 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6524 barframe.origin.y = [self statusBarHeight];
6526 barframe.origin.y = 0;
6528 [refreshbar_ setFrame:barframe];
6531 [UIView beginAnimations:nil context:NULL];
6533 CGRect viewframe = [transition frame];
6534 viewframe.origin.y += barframe.size.height;
6535 viewframe.size.height -= barframe.size.height;
6536 [transition setFrame:viewframe];
6539 [UIView commitAnimations];
6541 // Ensure bar has the proper width for our view, it might have changed
6542 barframe.size.width = viewframe.size.width;
6543 [refreshbar_ setFrame:barframe];
6545 // XXX: fix Apple's layout bug
6546 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6549 - (void) raiseBar:(BOOL)animated {
6554 UIView *transition([self transitionView]);
6555 [refreshbar_ removeFromSuperview];
6557 CGRect barframe([refreshbar_ frame]);
6560 [UIView beginAnimations:nil context:NULL];
6562 CGRect viewframe = [transition frame];
6563 viewframe.origin.y -= barframe.size.height;
6564 viewframe.size.height += barframe.size.height;
6565 [transition setFrame:viewframe];
6568 [UIView commitAnimations];
6570 // XXX: fix Apple's layout bug
6571 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6575 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6576 // XXX: fix Apple's layout bug
6577 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6581 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6582 bool dropped(dropped_);
6587 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6592 // XXX: fix Apple's layout bug
6593 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6596 - (void) statusBarFrameChanged:(NSNotification *)notification {
6605 /* Cydia Navigation Controller {{{ */
6606 @interface CYNavigationController : UINavigationController {
6607 _transient Database *database_;
6608 _transient id<UINavigationControllerDelegate> delegate_;
6611 - (NSArray *) navigationURLCollection;
6612 - (id) initWithDatabase:(Database *)database;
6613 - (void) reloadData;
6618 @implementation CYNavigationController
6620 - (NSArray *) navigationURLCollection {
6621 NSMutableArray *stack([NSMutableArray array]);
6623 for (CYViewController *controller in [self viewControllers]) {
6624 NSString *url = [[controller navigationURL] absoluteString];
6626 [stack addObject:url];
6632 - (void) reloadData {
6633 for (CYViewController *page in [self viewControllers]) {
6634 // Only reload controllers that have already loaded.
6635 // This prevents a page from accidentally loading too
6636 // early if it hasn't been shown on the screen yet.
6637 if ([page hasLoaded])
6642 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6643 delegate_ = delegate;
6646 - (id) initWithDatabase:(Database *)database {
6647 if ((self = [super init]) != nil) {
6648 database_ = database;
6655 /* Cydia:// Protocol {{{ */
6656 @interface CydiaURLProtocol : NSURLProtocol {
6661 @implementation CydiaURLProtocol
6663 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6664 NSURL *url([request URL]);
6667 NSString *scheme([[url scheme] lowercaseString]);
6668 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6673 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6677 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6678 id<NSURLProtocolClient> client([self client]);
6680 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6682 NSData *data(UIImagePNGRepresentation(icon));
6684 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6685 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6686 [client URLProtocol:self didLoadData:data];
6687 [client URLProtocolDidFinishLoading:self];
6691 - (void) startLoading {
6692 id<NSURLProtocolClient> client([self client]);
6693 NSURLRequest *request([self request]);
6695 NSURL *url([request URL]);
6696 NSString *href([url absoluteString]);
6698 NSString *path([href substringFromIndex:8]);
6699 NSRange slash([path rangeOfString:@"/"]);
6702 if (slash.location == NSNotFound) {
6706 command = [path substringToIndex:slash.location];
6707 path = [path substringFromIndex:(slash.location + 1)];
6710 Database *database([Database sharedInstance]);
6712 if ([command isEqualToString:@"package-icon"]) {
6715 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6716 Package *package([database packageWithName:path]);
6719 UIImage *icon([package icon]);
6720 [self _returnPNGWithImage:icon forRequest:request];
6721 } else if ([command isEqualToString:@"source-icon"]) {
6724 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6725 NSString *source(Simplify(path));
6726 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6728 icon = [UIImage applicationImageNamed:@"unknown.png"];
6729 [self _returnPNGWithImage:icon forRequest:request];
6730 } else if ([command isEqualToString:@"uikit-image"]) {
6733 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6734 UIImage *icon(_UIImageWithName(path));
6735 [self _returnPNGWithImage:icon forRequest:request];
6736 } else if ([command isEqualToString:@"section-icon"]) {
6739 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6740 NSString *section(Simplify(path));
6741 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6743 icon = [UIImage applicationImageNamed:@"unknown.png"];
6744 [self _returnPNGWithImage:icon forRequest:request];
6746 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6750 - (void) stopLoading {
6756 /* Section Controller {{{ */
6757 @interface SectionController : FilteredPackageListController {
6761 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6765 @implementation SectionController
6767 - (NSURL *) navigationURL {
6768 NSString *name = section_;
6772 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6775 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6778 title = UCLocalize("ALL_PACKAGES");
6779 else if (![name isEqual:@""])
6780 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6782 title = UCLocalize("NO_SECTION");
6784 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6791 /* Sections Controller {{{ */
6792 @interface SectionsController : CYViewController <
6793 UITableViewDataSource,
6796 _transient Database *database_;
6797 NSMutableArray *sections_;
6798 NSMutableArray *filtered_;
6803 - (id) initWithDatabase:(Database *)database;
6804 - (void) editButtonClicked;
6808 @implementation SectionsController
6811 [self releaseSubviews];
6812 [sections_ release];
6813 [filtered_ release];
6818 - (NSURL *) navigationURL {
6819 return [NSURL URLWithString:@"cydia://sections"];
6822 - (void) updateNavigationItem {
6823 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6824 if ([sections_ count] == 0) {
6825 [[self navigationItem] setRightBarButtonItem:nil];
6827 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6828 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6830 action:@selector(editButtonClicked)
6831 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6835 - (BOOL) isEditing {
6839 - (void) setEditing:(BOOL)editing {
6840 if ((editing_ = editing))
6843 [delegate_ updateData];
6845 [self updateNavigationItem];
6848 - (void) viewDidAppear:(BOOL)animated {
6849 [super viewDidAppear:animated];
6850 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6853 - (void) viewWillDisappear:(BOOL)animated {
6854 [super viewWillDisappear:animated];
6855 if (editing_) [self setEditing:NO];
6858 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6859 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6863 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6864 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6867 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6871 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6872 static NSString *reuseIdentifier = @"SectionCell";
6874 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6876 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6878 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6883 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6887 Section *section = [self sectionAtIndexPath:indexPath];
6889 SectionController *controller = [[[SectionController alloc]
6890 initWithDatabase:database_
6891 section:[section name]
6893 [controller setDelegate:delegate_];
6895 [[self navigationController] pushViewController:controller animated:YES];
6899 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6901 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6902 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6903 [list_ setRowHeight:45.0f];
6904 [list_ setDataSource:self];
6905 [list_ setDelegate:self];
6906 [[self view] addSubview:list_];
6909 - (void) viewDidLoad {
6910 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6913 - (void) releaseSubviews {
6918 - (id) initWithDatabase:(Database *)database {
6919 if ((self = [super init]) != nil) {
6920 database_ = database;
6922 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6923 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6927 - (void) reloadData {
6930 NSArray *packages = [database_ packages];
6932 [sections_ removeAllObjects];
6933 [filtered_ removeAllObjects];
6935 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6938 for (Package *package in packages) {
6939 NSString *name([package section]);
6940 NSString *key(name == nil ? @"" : name);
6944 _profile(SectionsView$reloadData$Section)
6945 section = [sections objectForKey:key];
6946 if (section == nil) {
6947 _profile(SectionsView$reloadData$Section$Allocate)
6948 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
6949 [sections setObject:section forKey:key];
6954 [section addToCount];
6956 _profile(SectionsView$reloadData$Filter)
6957 if (![package valid] || ![package visible])
6965 [sections_ addObjectsFromArray:[sections allValues]];
6967 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6969 for (Section *section in sections_) {
6970 size_t count([section row]);
6974 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6975 [section setCount:count];
6976 [filtered_ addObject:section];
6979 [self updateNavigationItem];
6984 - (void)editButtonClicked {
6985 [self setEditing:!editing_];
6991 /* Changes Controller {{{ */
6992 @interface ChangesController : CYViewController <
6993 UITableViewDataSource,
6996 _transient Database *database_;
6998 CFMutableArrayRef packages_;
6999 NSMutableArray *sections_;
7002 BOOL hasSentFirstLoad_;
7005 - (id) initWithDatabase:(Database *)database;
7009 @implementation ChangesController
7012 [self releaseSubviews];
7013 CFRelease(packages_);
7014 [sections_ release];
7019 - (NSURL *) navigationURL {
7020 return [NSURL URLWithString:@"cydia://changes"];
7023 - (void) viewWillAppear:(BOOL)animated {
7024 // Loads after it appears, so don't load beforehand.
7026 [super viewWillAppear:animated];
7029 - (void) viewDidAppear:(BOOL)animated {
7030 [super viewDidAppear:animated];
7032 if (!hasSentFirstLoad_) {
7033 hasSentFirstLoad_ = YES;
7034 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7036 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7040 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7041 NSInteger count([sections_ count]);
7042 return count == 0 ? 1 : count;
7045 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7046 if ([sections_ count] == 0)
7048 return [[sections_ objectAtIndex:section] name];
7051 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7052 if ([sections_ count] == 0)
7054 return [[sections_ objectAtIndex:section] count];
7057 - (Package *) packageAtIndex:(NSUInteger)index {
7058 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7061 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7062 @synchronized (database_) {
7063 if ([database_ era] != era_)
7066 NSUInteger sectionIndex([path section]);
7067 if (sectionIndex >= [sections_ count])
7069 Section *section([sections_ objectAtIndex:sectionIndex]);
7070 NSInteger row([path row]);
7071 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7074 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7075 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7077 cell = [[[PackageCell alloc] init] autorelease];
7078 [cell setPackage:[self packageAtIndexPath:path]];
7082 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7083 Package *package([self packageAtIndexPath:path]);
7084 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7085 [view setDelegate:delegate_];
7086 [[self navigationController] pushViewController:view animated:YES];
7090 - (void) refreshButtonClicked {
7091 [delegate_ beginUpdate];
7092 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7095 - (void) upgradeButtonClicked {
7096 [delegate_ distUpgrade];
7100 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7102 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7103 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7104 [list_ setRowHeight:73];
7105 [list_ setDataSource:self];
7106 [list_ setDelegate:self];
7107 [[self view] addSubview:list_];
7110 - (void) viewDidLoad {
7111 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7114 - (void) releaseSubviews {
7119 - (id) initWithDatabase:(Database *)database {
7120 if ((self = [super init]) != nil) {
7121 database_ = database;
7123 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7124 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7128 - (void) _reloadPackages:(NSArray *)packages {
7129 CFRelease(packages_);
7130 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7133 _profile(ChangesController$_reloadPackages$Filter)
7134 for (Package *package in packages)
7135 if ([package upgradableAndEssential:YES] || [package visible])
7136 CFArrayAppendValue(packages_, package);
7139 _profile(ChangesController$_reloadPackages$radixSort)
7140 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7145 - (void) reloadData {
7146 @synchronized (database_) {
7147 era_ = [database_ era];
7148 NSArray *packages = [database_ packages];
7150 [sections_ removeAllObjects];
7153 UIProgressHUD *hud([delegate_ addProgressHUD]);
7154 [hud setText:UCLocalize("LOADING")];
7155 //NSLog(@"HUD:%@::%@", delegate_, hud);
7156 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7157 [delegate_ removeProgressHUD:hud];
7159 [self _reloadPackages:packages];
7162 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7163 Section *ignored = nil;
7164 Section *section = nil;
7168 bool unseens = false;
7170 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7172 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7173 Package *package = [self packageAtIndex:offset];
7175 BOOL uae = [package upgradableAndEssential:YES];
7179 time_t seen([package seen]);
7181 if (section == nil || last != seen) {
7185 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7188 _profile(ChangesController$reloadData$Allocate)
7189 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7190 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7191 [sections_ addObject:section];
7195 [section addToCount];
7196 } else if ([package ignored]) {
7197 if (ignored == nil) {
7198 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7200 [ignored addToCount];
7203 [upgradable addToCount];
7208 CFRelease(formatter);
7211 Section *last = [sections_ lastObject];
7212 size_t count = [last count];
7213 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7214 [sections_ removeLastObject];
7217 if ([ignored count] != 0)
7218 [sections_ insertObject:ignored atIndex:0];
7220 [sections_ insertObject:upgradable atIndex:0];
7225 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7226 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7227 style:UIBarButtonItemStylePlain
7229 action:@selector(upgradeButtonClicked)
7232 if (![delegate_ updating])
7233 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7234 initWithTitle:UCLocalize("REFRESH")
7235 style:UIBarButtonItemStylePlain
7237 action:@selector(refreshButtonClicked)
7245 /* Search Controller {{{ */
7246 @interface SearchController : FilteredPackageListController <
7249 UISearchBar *search_;
7253 - (id) initWithDatabase:(Database *)database;
7254 - (void) setSearchTerm:(NSString *)term;
7255 - (void) reloadData;
7259 @implementation SearchController
7266 - (NSURL *) navigationURL {
7267 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7268 return [NSURL URLWithString:@"cydia://search"];
7270 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7273 - (void) setSearchTerm:(NSString *)searchTerm {
7274 [search_ setText:searchTerm];
7278 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7279 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7280 [search_ resignFirstResponder];
7284 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7285 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7289 - (id) initWithDatabase:(Database *)database {
7290 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7291 search_ = [[UISearchBar alloc] init];
7295 - (void)viewDidAppear:(BOOL)animated {
7296 [super viewDidAppear:animated];
7298 if (!searchloaded_) {
7299 searchloaded_ = YES;
7300 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7301 [search_ layoutSubviews];
7302 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7304 UITextField *textField;
7305 if ([search_ respondsToSelector:@selector(searchField)])
7306 textField = [search_ searchField];
7308 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7310 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7311 [search_ setDelegate:self];
7312 [textField setEnablesReturnKeyAutomatically:NO];
7313 [[self navigationItem] setTitleView:textField];
7317 - (void) reloadData {
7318 [self setObject:[search_ text]];
7323 - (void) didSelectPackage:(Package *)package {
7324 [search_ resignFirstResponder];
7325 [super didSelectPackage:package];
7330 /* Package Settings Controller {{{ */
7331 @interface PackageSettingsController : CYViewController <
7332 UITableViewDataSource,
7335 _transient Database *database_;
7338 UITableView *table_;
7339 UISwitch *subscribedSwitch_;
7340 UISwitch *ignoredSwitch_;
7341 UITableViewCell *subscribedCell_;
7342 UITableViewCell *ignoredCell_;
7345 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7349 @implementation PackageSettingsController
7352 [self releaseSubviews];
7359 - (NSURL *) navigationURL {
7360 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7363 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7364 if (package_ == nil)
7370 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7371 if (package_ == nil)
7377 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7378 return UCLocalize("CHANGE_PACKAGE_SETTINGS");
7381 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7382 return UCLocalize("SHOW_ALL_CHANGES_EX");
7385 - (void) onSubscribed:(id)control {
7386 bool value([control isOn]);
7387 if (package_ == nil)
7389 if ([package_ setSubscribed:value])
7390 [delegate_ updateData];
7393 - (void) onIgnored:(id)control {
7394 // TODO: set Held state - possibly call out to dpkg, etc.
7397 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7398 if (package_ == nil)
7401 switch ([indexPath row]) {
7402 case 0: return subscribedCell_;
7403 case 1: return ignoredCell_;
7412 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7414 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7415 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7416 [table_ setDataSource:self];
7417 [table_ setDelegate:self];
7418 [[self view] addSubview:table_];
7420 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7421 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7422 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7424 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7425 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7426 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7427 // Disable this switch, since it only reflects (not modifies) the ignored state.
7428 [ignoredSwitch_ setUserInteractionEnabled:NO];
7430 subscribedCell_ = [[UITableViewCell alloc] init];
7431 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7432 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7433 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7435 ignoredCell_ = [[UITableViewCell alloc] init];
7436 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7437 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7438 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7439 // FIXME: Ignored state is not saved.
7440 [ignoredCell_ setUserInteractionEnabled:NO];
7443 - (void) viewDidLoad {
7444 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7447 - (void) releaseSubviews {
7448 [ignoredCell_ release];
7451 [subscribedCell_ release];
7452 subscribedCell_ = nil;
7457 [ignoredSwitch_ release];
7458 ignoredSwitch_ = nil;
7460 [subscribedSwitch_ release];
7461 subscribedSwitch_ = nil;
7464 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7465 if ((self = [super init])) {
7466 database_ = database;
7467 name_ = [package retain];
7471 - (void) reloadData {
7474 if (package_ != nil)
7475 [package_ autorelease];
7476 package_ = [database_ packageWithName:name_];
7477 if (package_ != nil) {
7479 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7480 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7483 [table_ reloadData];
7489 /* Installed Controller {{{ */
7490 @interface InstalledController : FilteredPackageListController {
7494 - (id) initWithDatabase:(Database *)database;
7496 - (void) updateRoleButton;
7497 - (void) queueStatusDidChange;
7501 @implementation InstalledController
7507 - (NSURL *) navigationURL {
7508 return [NSURL URLWithString:@"cydia://installed"];
7511 - (id) initWithDatabase:(Database *)database {
7512 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7513 [self updateRoleButton];
7514 [self queueStatusDidChange];
7519 - (void) queueButtonClicked {
7524 - (void) queueStatusDidChange {
7528 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7529 initWithTitle:UCLocalize("QUEUE")
7530 style:UIBarButtonItemStyleDone
7532 action:@selector(queueButtonClicked)
7535 [[self navigationItem] setLeftBarButtonItem:nil];
7541 - (void) updateRoleButton {
7542 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7543 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7544 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7545 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7547 action:@selector(roleButtonClicked)
7551 - (void) roleButtonClicked {
7552 [self setObject:[NSNumber numberWithBool:expert_]];
7556 [self updateRoleButton];
7562 /* Source Cell {{{ */
7563 @interface SourceCell : CYTableViewCell <
7571 - (void) setSource:(Source *)source;
7575 @implementation SourceCell
7577 - (void) clearSource {
7587 - (void) setSource:(Source *)source {
7591 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7593 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7594 icon_ = [icon_ retain];
7596 origin_ = [[source name] retain];
7597 label_ = [[source uri] retain];
7599 [content_ setNeedsDisplay];
7607 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7608 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7609 UIView *content([self contentView]);
7610 CGRect bounds([content bounds]);
7612 content_ = [[ContentView alloc] initWithFrame:bounds];
7613 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7614 [content_ setBackgroundColor:[UIColor whiteColor]];
7615 [content addSubview:content_];
7617 [content_ setDelegate:self];
7618 [content_ setOpaque:YES];
7622 - (NSString *) accessibilityLabel {
7626 - (void) drawContentRect:(CGRect)rect {
7627 bool highlighted(highlighted_);
7628 float width(rect.size.width);
7631 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7638 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7642 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7647 /* Source Controller {{{ */
7648 @interface SourceController : FilteredPackageListController {
7652 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7656 @implementation SourceController
7658 - (NSURL *) navigationURL {
7659 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7662 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7665 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7671 /* Sources Controller {{{ */
7672 @interface SourcesController : CYViewController <
7673 UITableViewDataSource,
7676 _transient Database *database_;
7678 NSMutableArray *sources_;
7682 UIProgressHUD *hud_;
7685 //NSURLConnection *installer_;
7686 NSURLConnection *trivial_;
7687 NSURLConnection *trivial_bz2_;
7688 NSURLConnection *trivial_gz_;
7689 //NSURLConnection *automatic_;
7694 - (id) initWithDatabase:(Database *)database;
7695 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7699 @implementation SourcesController
7701 - (void) _releaseConnection:(NSURLConnection *)connection {
7702 if (connection != nil) {
7703 [connection cancel];
7704 //[connection setDelegate:nil];
7705 [connection release];
7710 [self releaseSubviews];
7716 //[self _releaseConnection:installer_];
7717 [self _releaseConnection:trivial_];
7718 [self _releaseConnection:trivial_gz_];
7719 [self _releaseConnection:trivial_bz2_];
7720 //[self _releaseConnection:automatic_];
7726 - (NSURL *) navigationURL {
7727 return [NSURL URLWithString:@"cydia://sources"];
7730 - (void) viewDidAppear:(BOOL)animated {
7731 [super viewDidAppear:animated];
7732 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7735 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7736 return offset_ == 0 ? 1 : 2;
7739 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7740 switch (section + (offset_ == 0 ? 1 : 0)) {
7741 case 0: return UCLocalize("ENTERED_BY_USER");
7742 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7748 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7749 int count = [sources_ count];
7751 case 0: return (offset_ == 0 ? count : offset_);
7752 case 1: return count - offset_;
7758 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7760 switch (indexPath.section) {
7761 case 0: idx = indexPath.row; break;
7762 case 1: idx = indexPath.row + offset_; break;
7766 return [sources_ objectAtIndex:idx];
7769 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7770 static NSString *cellIdentifier = @"SourceCell";
7772 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7773 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7774 [cell setSource:[self sourceAtIndexPath:indexPath]];
7775 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7780 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7781 Source *source = [self sourceAtIndexPath:indexPath];
7783 SourceController *controller = [[[SourceController alloc]
7784 initWithDatabase:database_
7788 [controller setDelegate:delegate_];
7790 [[self navigationController] pushViewController:controller animated:YES];
7793 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7794 Source *source = [self sourceAtIndexPath:indexPath];
7795 return [source record] != nil;
7798 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7799 Source *source = [self sourceAtIndexPath:indexPath];
7800 [Sources_ removeObjectForKey:[source key]];
7801 [delegate_ syncData];
7805 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
7808 @"./", @"Distribution",
7809 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
7811 [delegate_ syncData];
7814 - (NSString *) getWarning {
7815 NSString *href(href_);
7816 NSRange colon([href rangeOfString:@"://"]);
7817 if (colon.location != NSNotFound)
7818 href = [href substringFromIndex:(colon.location + 3)];
7819 href = [href stringByAddingPercentEscapes];
7820 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7821 href = [href stringByCachingURLWithCurrentCDN];
7823 NSURL *url([NSURL URLWithString:href]);
7825 NSStringEncoding encoding;
7826 NSError *error(nil);
7828 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7829 return [warning length] == 0 ? nil : warning;
7833 - (void) _endConnection:(NSURLConnection *)connection {
7834 // XXX: the memory management in this method is horribly awkward
7836 NSURLConnection **field = NULL;
7837 if (connection == trivial_)
7839 else if (connection == trivial_bz2_)
7840 field = &trivial_bz2_;
7841 else if (connection == trivial_gz_)
7842 field = &trivial_gz_;
7843 _assert(field != NULL);
7844 [connection release];
7849 trivial_bz2_ == nil &&
7855 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7858 UIAlertView *alert = [[[UIAlertView alloc]
7859 initWithTitle:UCLocalize("SOURCE_WARNING")
7862 cancelButtonTitle:UCLocalize("CANCEL")
7864 UCLocalize("ADD_ANYWAY"),
7868 [alert setContext:@"warning"];
7869 [alert setNumberOfRows:1];
7873 } else if (error_ != nil) {
7874 UIAlertView *alert = [[[UIAlertView alloc]
7875 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7876 message:[error_ localizedDescription]
7878 cancelButtonTitle:UCLocalize("OK")
7879 otherButtonTitles:nil
7882 [alert setContext:@"urlerror"];
7885 UIAlertView *alert = [[[UIAlertView alloc]
7886 initWithTitle:UCLocalize("NOT_REPOSITORY")
7887 message:UCLocalize("NOT_REPOSITORY_EX")
7889 cancelButtonTitle:UCLocalize("OK")
7890 otherButtonTitles:nil
7893 [alert setContext:@"trivial"];
7897 [delegate_ setStatusBarShowsProgress:NO];
7898 [delegate_ removeProgressHUD:hud_];
7908 if (error_ != nil) {
7915 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
7916 switch ([response statusCode]) {
7922 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
7923 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7925 error_ = [error retain];
7926 [self _endConnection:connection];
7929 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
7930 [self _endConnection:connection];
7933 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
7934 NSMutableURLRequest *request = [NSMutableURLRequest
7935 requestWithURL:[NSURL URLWithString:href]
7936 cachePolicy:NSURLRequestUseProtocolCachePolicy
7937 timeoutInterval:120.0
7940 [request setHTTPMethod:method];
7942 if (Machine_ != NULL)
7943 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
7944 if (UniqueID_ != nil)
7945 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
7947 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
7949 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
7952 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7953 NSString *context([alert context]);
7955 if ([context isEqualToString:@"source"]) {
7958 NSString *href = [[alert textField] text];
7960 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
7962 if (![href hasSuffix:@"/"])
7963 href_ = [href stringByAppendingString:@"/"];
7966 href_ = [href_ retain];
7968 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
7969 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
7970 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
7971 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
7975 // XXX: this is stupid
7976 hud_ = [[delegate_ addProgressHUD] retain];
7977 [hud_ setText:UCLocalize("VERIFYING_URL")];
7986 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7987 } else if ([context isEqualToString:@"trivial"])
7988 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7989 else if ([context isEqualToString:@"urlerror"])
7990 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7991 else if ([context isEqualToString:@"warning"]) {
8006 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8011 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8013 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8014 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8015 [list_ setRowHeight:56];
8016 [list_ setDataSource:self];
8017 [list_ setDelegate:self];
8018 [[self view] addSubview:list_];
8021 - (void) viewDidLoad {
8022 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8023 [self updateButtonsForEditingStatus:NO animated:NO];
8026 - (void) releaseSubviews {
8031 - (id) initWithDatabase:(Database *)database {
8032 if ((self = [super init]) != nil) {
8033 database_ = database;
8034 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8038 - (void) reloadData {
8042 if (!list.ReadMainList())
8045 [sources_ removeAllObjects];
8046 [sources_ addObjectsFromArray:[database_ sources]];
8048 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8051 int count([sources_ count]);
8053 for (int i = 0; i != count; i++) {
8054 if ([[sources_ objectAtIndex:i] record] == nil)
8059 [list_ setEditing:NO];
8060 [self updateButtonsForEditingStatus:NO animated:NO];
8064 - (void) showAddSourcePrompt {
8065 UIAlertView *alert = [[[UIAlertView alloc]
8066 initWithTitle:UCLocalize("ENTER_APT_URL")
8069 cancelButtonTitle:UCLocalize("CANCEL")
8071 UCLocalize("ADD_SOURCE"),
8075 [alert setContext:@"source"];
8076 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8078 [alert setNumberOfRows:1];
8079 [alert addTextFieldWithValue:@"http://" label:@""];
8081 UITextInputTraits *traits = [[alert textField] textInputTraits];
8082 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8083 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8084 [traits setKeyboardType:UIKeyboardTypeURL];
8085 // XXX: UIReturnKeyDone
8086 [traits setReturnKeyType:UIReturnKeyNext];
8091 - (void) addButtonClicked {
8092 [self showAddSourcePrompt];
8095 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8096 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8097 initWithTitle:UCLocalize("ADD")
8098 style:UIBarButtonItemStylePlain
8100 action:@selector(addButtonClicked)
8101 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8103 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8104 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8105 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8107 action:@selector(editButtonClicked)
8108 ] autorelease] animated:animated];
8110 if (IsWildcat_ && !editing)
8111 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8112 initWithTitle:UCLocalize("SETTINGS")
8113 style:UIBarButtonItemStylePlain
8115 action:@selector(settingsButtonClicked)
8119 - (void) settingsButtonClicked {
8120 [delegate_ showSettings];
8123 - (void) editButtonClicked {
8124 [list_ setEditing:![list_ isEditing] animated:YES];
8126 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8132 /* Settings Controller {{{ */
8133 @interface SettingsController : CYViewController <
8134 UITableViewDataSource,
8137 _transient Database *database_;
8138 // XXX: ok, "roledelegate_"?...
8139 _transient id roledelegate_;
8140 UITableView *table_;
8141 UISegmentedControl *segment_;
8145 - (void) showDoneButton;
8146 - (void) resizeSegmentedControl;
8150 @implementation SettingsController
8153 [self releaseSubviews];
8159 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8161 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8162 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8163 [table_ setDelegate:self];
8164 [table_ setDataSource:self];
8165 [[self view] addSubview:table_];
8167 NSArray *items = [NSArray arrayWithObjects:
8169 UCLocalize("HACKER"),
8170 UCLocalize("DEVELOPER"),
8172 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8173 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8174 [container_ addSubview:segment_];
8177 - (void) viewDidLoad {
8178 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8181 if ([Role_ isEqualToString:@"User"]) index = 0;
8182 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8183 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8185 [segment_ setSelectedSegmentIndex:index];
8186 [self showDoneButton];
8189 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8190 [self resizeSegmentedControl];
8193 - (void) releaseSubviews {
8200 [container_ release];
8204 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8205 if ((self = [super init])) {
8206 database_ = database;
8207 roledelegate_ = delegate;
8211 - (void) resizeSegmentedControl {
8212 CGFloat width = [[self view] frame].size.width;
8213 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8216 - (void) viewWillAppear:(BOOL)animated {
8217 [super viewWillAppear:animated];
8219 [self resizeSegmentedControl];
8222 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8223 [self resizeSegmentedControl];
8226 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8227 [self resizeSegmentedControl];
8231 NSString *role(nil);
8233 switch ([segment_ selectedSegmentIndex]) {
8234 case 0: role = @"User"; break;
8235 case 1: role = @"Hacker"; break;
8236 case 2: role = @"Developer"; break;
8241 if (![role isEqualToString:Role_]) {
8242 bool rolling(Role_ == nil);
8245 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8249 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8253 [roledelegate_ loadData];
8255 [roledelegate_ updateData];
8259 - (void) segmentChanged:(UISegmentedControl *)control {
8260 [self showDoneButton];
8263 - (void) saveAndClose {
8266 [[self navigationItem] setRightBarButtonItem:nil];
8267 [[self navigationController] dismissModalViewControllerAnimated:YES];
8270 - (void) doneButtonClicked {
8271 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8272 [spinner startAnimating];
8273 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8274 [[self navigationItem] setRightBarButtonItem:spinItem];
8276 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8279 - (void) showDoneButton {
8280 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8281 initWithTitle:UCLocalize("DONE")
8282 style:UIBarButtonItemStyleDone
8284 action:@selector(doneButtonClicked)
8285 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8288 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8289 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8293 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8297 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8298 return nil; // This method is required by the protocol.
8301 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8303 return UCLocalize("ROLE_EX");
8305 return [NSString stringWithFormat:
8306 @"%@: %@\n%@: %@\n%@: %@",
8307 UCLocalize("USER"), UCLocalize("USER_EX"),
8308 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8309 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8314 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8315 return section == 3 ? 44.0f : 0;
8318 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8319 return section == 3 ? container_ : nil;
8322 - (void) reloadData {
8324 [table_ reloadData];
8329 /* Stash Controller {{{ */
8330 @interface StashController : CYViewController {
8331 UIActivityIndicatorView *spinner_;
8337 @implementation StashController
8340 [self releaseSubviews];
8346 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8347 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8349 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8350 CGRect spinrect = [spinner_ frame];
8351 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8352 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8353 [spinner_ setFrame:spinrect];
8354 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8355 [[self view] addSubview:spinner_];
8356 [spinner_ startAnimating];
8359 captrect.size.width = [[self view] frame].size.width;
8360 captrect.size.height = 40.0f;
8361 captrect.origin.x = 0;
8362 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8363 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8364 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8365 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8366 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8367 [caption_ setTextColor:[UIColor whiteColor]];
8368 [caption_ setBackgroundColor:[UIColor clearColor]];
8369 [caption_ setShadowColor:[UIColor blackColor]];
8370 [caption_ setTextAlignment:UITextAlignmentCenter];
8371 [[self view] addSubview:caption_];
8374 statusrect.size.width = [[self view] frame].size.width;
8375 statusrect.size.height = 30.0f;
8376 statusrect.origin.x = 0;
8377 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8378 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8379 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8380 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8381 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8382 [status_ setTextColor:[UIColor whiteColor]];
8383 [status_ setBackgroundColor:[UIColor clearColor]];
8384 [status_ setShadowColor:[UIColor blackColor]];
8385 [status_ setTextAlignment:UITextAlignmentCenter];
8386 [[self view] addSubview:status_];
8389 - (void) releaseSubviews {
8403 @interface Cydia : UIApplication <
8404 ConfirmationControllerDelegate,
8405 ProgressControllerDelegate,
8407 UINavigationControllerDelegate,
8408 UITabBarControllerDelegate
8410 // XXX: evaluate all fields for _transient
8413 CYTabBarController *tabbar_;
8415 NSMutableArray *essential_;
8416 NSMutableArray *broken_;
8418 Database *database_;
8425 StashController *stash_;
8434 @implementation Cydia
8436 - (void) beginUpdate {
8437 [tabbar_ beginUpdate];
8441 return [tabbar_ updating];
8445 if ([broken_ count] != 0) {
8446 int count = [broken_ count];
8448 UIAlertView *alert = [[[UIAlertView alloc]
8449 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8450 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8452 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8454 UCLocalize("TEMPORARY_IGNORE"),
8458 [alert setContext:@"fixhalf"];
8460 } else if (!Ignored_ && [essential_ count] != 0) {
8461 int count = [essential_ count];
8463 UIAlertView *alert = [[[UIAlertView alloc]
8464 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8465 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8467 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8469 UCLocalize("UPGRADE_ESSENTIAL"),
8470 UCLocalize("COMPLETE_UPGRADE"),
8474 [alert setContext:@"upgrade"];
8479 - (void) _saveConfig {
8485 NSString *error(nil);
8487 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8489 NSError *error(nil);
8490 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8491 NSLog(@"failure to save metadata data: %@", error);
8496 NSLog(@"failure to serialize metadata: %@", error);
8501 // Navigation controller for the queuing badge.
8502 - (CYNavigationController *) queueNavigationController {
8503 NSArray *controllers = [tabbar_ viewControllers];
8504 return [controllers objectAtIndex:3];
8507 - (void) _updateData {
8510 [tabbar_ reloadData];
8512 CYNavigationController *navigation = [self queueNavigationController];
8514 id queuedelegate = nil;
8515 if ([[navigation viewControllers] count] > 0)
8516 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8518 [queuedelegate queueStatusDidChange];
8519 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8522 - (void) _refreshIfPossible {
8523 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8525 bool recently = false;
8526 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8527 if (update != nil) {
8528 NSTimeInterval interval([update timeIntervalSinceNow]);
8529 if (interval <= 0 && interval > -(15*60))
8533 // Don't automatic refresh if:
8534 // - We already refreshed recently.
8535 // - We already auto-refreshed this launch.
8536 // - Auto-refresh is disabled.
8537 if (recently || loaded_ || ManualRefresh) {
8538 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8540 // If we are cancelling, we need to make sure it knows it's already loaded.
8544 // We are going to load, so remember that.
8548 SCNetworkReachabilityFlags flags; {
8549 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8550 SCNetworkReachabilityGetFlags(reachability, &flags);
8551 CFRelease(reachability);
8554 // XXX: this elaborate mess is what Apple is using to determine this? :(
8555 // XXX: do we care if the user has to intervene? maybe that's ok?
8557 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8558 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8559 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8560 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8561 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8562 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8566 // If we can reach the server, auto-refresh!
8568 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8573 - (void) refreshIfPossible {
8574 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8577 - (void) _reloadData {
8578 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8579 [hud setText:UCLocalize("RELOADING_DATA")];
8581 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8584 [self removeProgressHUD:hud];
8588 [essential_ removeAllObjects];
8589 [broken_ removeAllObjects];
8591 NSArray *packages([database_ packages]);
8592 for (Package *package in packages) {
8594 [broken_ addObject:package];
8595 if ([package upgradableAndEssential:NO]) {
8596 if ([package essential])
8597 [essential_ addObject:package];
8602 NSLog(@"changes:#%u", changes);
8604 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8607 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8608 [changesItem setBadgeValue:badge];
8609 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8610 [self setApplicationIconBadgeNumber:changes];
8613 [changesItem setBadgeValue:nil];
8614 [changesItem setAnimatedBadge:NO];
8615 [self setApplicationIconBadgeNumber:0];
8620 [self refreshIfPossible];
8623 - (void) updateData {
8632 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8633 _assert(file != NULL);
8635 for (NSString *key in [Sources_ allKeys]) {
8636 NSDictionary *source([Sources_ objectForKey:key]);
8638 fprintf(file, "%s %s %s\n",
8639 [[source objectForKey:@"Type"] UTF8String],
8640 [[source objectForKey:@"URI"] UTF8String],
8641 [[source objectForKey:@"Distribution"] UTF8String]
8649 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8650 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8652 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8653 [tabbar_ presentModalViewController:navigation animated:YES];
8656 detachNewThreadSelector:@selector(update_)
8659 title:UCLocalize("UPDATING_SOURCES")
8663 - (void) reloadData {
8664 @synchronized (self) {
8670 pkgProblemResolver *resolver = [database_ resolver];
8672 resolver->InstallProtect();
8673 if (!resolver->Resolve(true))
8678 // XXX: this is a really crappy way of doing this.
8679 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8680 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8681 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8682 if ([tabbar_ updating])
8683 [tabbar_ cancelUpdate];
8685 if (![database_ prepare])
8688 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8689 [page setDelegate:self];
8690 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8691 [confirm_ setDelegate:self];
8694 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8695 [tabbar_ presentModalViewController:confirm_ animated:YES];
8701 @synchronized (self) {
8706 - (void) clearPackage:(Package *)package {
8707 @synchronized (self) {
8714 - (void) installPackages:(NSArray *)packages {
8715 @synchronized (self) {
8716 for (Package *package in packages)
8723 - (void) installPackage:(Package *)package {
8724 @synchronized (self) {
8731 - (void) removePackage:(Package *)package {
8732 @synchronized (self) {
8739 - (void) distUpgrade {
8740 @synchronized (self) {
8741 if (![database_ upgrade])
8748 @synchronized (self) {
8753 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8756 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8758 if (navigation != nil) {
8759 [navigation pushViewController:progress animated:YES];
8761 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8763 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8764 [tabbar_ presentModalViewController:navigation animated:YES];
8768 detachNewThreadSelector:@selector(perform)
8771 title:UCLocalize("RUNNING")
8777 - (void) progressControllerIsComplete:(ProgressController *)progress {
8782 - (void) showSettings {
8783 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8784 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8786 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8787 [tabbar_ presentModalViewController:nav animated:YES];
8790 - (void) retainNetworkActivityIndicator {
8791 if (activity_++ == 0)
8792 [self setNetworkActivityIndicatorVisible:YES];
8795 - (void) releaseNetworkActivityIndicator {
8796 if (--activity_ == 0)
8797 [self setNetworkActivityIndicatorVisible:NO];
8800 - (void) cancelAndClear:(bool)clear {
8801 @synchronized (self) {
8813 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8814 NSString *context([alert context]);
8816 if ([context isEqualToString:@"fixhalf"]) {
8817 if (button == [alert cancelButtonIndex]) {
8818 @synchronized (self) {
8819 for (Package *broken in broken_) {
8822 NSString *id = [broken id];
8823 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8824 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8825 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8826 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8832 } else if (button == [alert firstOtherButtonIndex]) {
8833 [broken_ removeAllObjects];
8837 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8838 } else if ([context isEqualToString:@"upgrade"]) {
8839 if (button == [alert firstOtherButtonIndex]) {
8840 @synchronized (self) {
8841 for (Package *essential in essential_)
8842 [essential install];
8847 } else if (button == [alert firstOtherButtonIndex] + 1) {
8849 } else if (button == [alert cancelButtonIndex]) {
8853 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8857 - (void) system:(NSString *)command { _pooled
8859 system([command UTF8String]);
8863 - (void) applicationWillSuspend {
8865 [super applicationWillSuspend];
8868 - (BOOL) isSafeToSuspend {
8869 // Use external process status API internally.
8870 // This is probably a really bad idea.
8871 // XXX: what is the point of this? does this solve anything at all?
8872 uint64_t status = 0;
8874 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8875 notify_get_state(notify_token, &status);
8876 notify_cancel(notify_token);
8879 return locked_ == 0 && status == 0;
8882 - (void) applicationSuspend:(__GSEvent *)event {
8883 if ([self isSafeToSuspend])
8884 [super applicationSuspend:event];
8887 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8888 if ([self isSafeToSuspend])
8889 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8892 - (void) _setSuspended:(BOOL)value {
8893 if ([self isSafeToSuspend])
8894 [super _setSuspended:value];
8897 - (UIProgressHUD *) addProgressHUD {
8898 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8899 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8901 [window_ setUserInteractionEnabled:NO];
8904 UIViewController *target = tabbar_;
8905 while ([target modalViewController] != nil) target = [target modalViewController];
8906 [[target view] addSubview:hud];
8912 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8914 [hud removeFromSuperview];
8915 [window_ setUserInteractionEnabled:YES];
8919 - (CYViewController *) pageForPackage:(NSString *)name {
8920 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
8923 - (CYViewController *) pageForURL:(NSURL *)url {
8924 NSString *scheme([[url scheme] lowercaseString]);
8925 if ([[url absoluteString] length] <= [scheme length] + 3)
8927 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
8928 NSArray *components([path pathComponents]);
8930 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
8931 return [self pageForPackage:[components objectAtIndex:1]];
8933 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
8936 NSString *base([components objectAtIndex:0]);
8938 CYViewController *controller = nil;
8940 if ([base isEqualToString:@"url"]) {
8941 // This kind of URL can contain slashes in the argument, so we can't parse them below.
8942 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
8943 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
8944 } else if ([components count] == 1) {
8945 if ([base isEqualToString:@"manage"]) {
8946 controller = [[[ManageController alloc] init] autorelease];
8949 if ([base isEqualToString:@"sources"]) {
8950 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8953 if ([base isEqualToString:@"home"]) {
8954 controller = [[[HomeController alloc] init] autorelease];
8957 if ([base isEqualToString:@"sections"]) {
8958 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
8961 if ([base isEqualToString:@"search"]) {
8962 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8965 if ([base isEqualToString:@"changes"]) {
8966 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
8969 if ([base isEqualToString:@"installed"]) {
8970 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8972 } else if ([components count] == 2) {
8973 NSString *argument = [components objectAtIndex:1];
8975 if ([base isEqualToString:@"package"]) {
8976 controller = [self pageForPackage:argument];
8979 if ([base isEqualToString:@"search"]) {
8980 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8981 [(SearchController *)controller setSearchTerm:argument];
8984 if ([base isEqualToString:@"sections"]) {
8985 if ([argument isEqualToString:@"all"])
8987 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
8990 if ([base isEqualToString:@"sources"]) {
8991 if ([argument isEqualToString:@"add"]) {
8992 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8993 [(SourcesController *)controller showAddSourcePrompt];
8995 NSArray *sources = [database_ sources];
8996 for (Source *source in sources) {
8997 if ([[source name] caseInsensitiveCompare:argument] == NSOrderedSame) {
8998 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9005 if ([base isEqualToString:@"launch"]) {
9006 [self launchApplicationWithIdentifier:argument suspended:NO];
9009 } else if ([components count] == 3) {
9010 NSString *arg1 = [components objectAtIndex:1];
9011 NSString *arg2 = [components objectAtIndex:2];
9013 if ([base isEqualToString:@"package"]) {
9014 if ([arg2 isEqualToString:@"settings"]) {
9015 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9016 } else if ([arg2 isEqualToString:@"files"]) {
9017 if (Package *package = [database_ packageWithName:arg1]) {
9018 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9019 [(FileTable *)controller setPackage:package];
9025 [controller setDelegate:self];
9029 - (BOOL) openCydiaURL:(NSURL *)url {
9030 CYViewController *page([self pageForURL:url]);
9033 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9034 [nav setViewControllers:[NSArray arrayWithObject:page]];
9035 [tabbar_ setUnselectedViewController:nav];
9041 - (void) applicationOpenURL:(NSURL *)url {
9042 [super applicationOpenURL:url];
9044 if (!loaded_) starturl_ = [url retain];
9045 else [self openCydiaURL:url];
9048 - (void) applicationWillResignActive:(UIApplication *)application {
9049 // Stop refreshing if you get a phone call or lock the device.
9050 if ([tabbar_ updating])
9051 [tabbar_ cancelUpdate];
9053 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9054 [super applicationWillResignActive:application];
9057 - (void) applicationWillTerminate:(UIApplication *)application {
9059 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9060 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9061 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9066 - (void) addStashController {
9068 stash_ = [[StashController alloc] init];
9069 [window_ addSubview:[stash_ view]];
9072 - (void) removeStashController {
9073 [[stash_ view] removeFromSuperview];
9079 [self setIdleTimerDisabled:YES];
9081 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9082 [self setStatusBarShowsProgress:YES];
9083 UpdateExternalStatus(1);
9085 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9087 UpdateExternalStatus(0);
9088 [self setStatusBarShowsProgress:NO];
9090 [self removeStashController];
9092 if (ExecFork() == 0) {
9093 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9094 perror("launchctl stop");
9098 - (void) setupViewControllers {
9099 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9101 NSMutableArray *items([NSMutableArray arrayWithObjects:
9102 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9103 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9104 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9105 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9109 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9110 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9112 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9115 NSMutableArray *controllers([NSMutableArray array]);
9116 for (UITabBarItem *item in items) {
9117 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9118 [controller setTabBarItem:item];
9119 [controllers addObject:controller];
9121 [tabbar_ setViewControllers:controllers];
9123 [tabbar_ setUpdateDelegate:self];
9126 - (CYEmulatedLoadingController *)showEmulatedLoadingControllerInView:(UIView *)view {
9127 static CYEmulatedLoadingController *fake = nil;
9131 fake = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9132 [view addSubview:[fake view]];
9134 [[fake view] removeFromSuperview];
9142 - (void) applicationDidFinishLaunching:(id)unused {
9146 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9147 [self setApplicationSupportsShakeToEdit:NO];
9149 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9150 initWithMemoryCapacity:524288
9151 diskCapacity:10485760
9152 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9155 [CYBrowserController _initialize];
9157 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9159 Font12_ = [[UIFont systemFontOfSize:12] retain];
9160 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9161 Font14_ = [[UIFont systemFontOfSize:14] retain];
9162 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9163 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9165 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9166 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9168 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9169 [window_ orderFront:self];
9170 [window_ makeKey:self];
9171 [window_ setHidden:NO];
9174 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9175 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9176 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9177 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9178 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9179 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9180 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9181 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9182 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9185 [self addStashController];
9186 // XXX: this would be much cleaner as a yieldToSelector:
9187 // that way the removeStashController could happen right here inline
9188 // we also could no longer require the useless stash_ field anymore
9189 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9193 database_ = [Database sharedInstance];
9195 [window_ setUserInteractionEnabled:NO];
9196 [self setupViewControllers];
9197 [self showEmulatedLoadingControllerInView:window_];
9199 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9206 [window_ setUserInteractionEnabled:YES];
9208 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9209 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9211 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9212 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9216 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9217 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9218 [window_ setUserInteractionEnabled:NO];
9224 [window_ addSubview:[tabbar_ view]];
9225 [self showEmulatedLoadingControllerInView:nil];
9226 [window_ setUserInteractionEnabled:YES];
9228 int selectedIndex = 0;
9229 NSMutableArray *items = nil;
9231 bool recently = false;
9232 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9233 if (closed != nil) {
9234 NSTimeInterval interval([closed timeIntervalSinceNow]);
9235 // XXX: Is 15 minutes the optimal time here?
9236 if (interval <= 0 && interval > -(15*60))
9240 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9241 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9244 for (NSArray *entry in items)
9245 if ([entry count] <= 0)
9248 if (!recently || !items || !enough) {
9250 items = [NSMutableArray array];
9251 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9252 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9253 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9255 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9257 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9258 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9260 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9263 [tabbar_ setSelectedIndex:selectedIndex];
9264 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9265 NSArray *stack = [items objectAtIndex:tab];
9266 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9267 NSMutableArray *current = [NSMutableArray array];
9269 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9270 NSString *addr = [stack objectAtIndex:nav];
9271 NSURL *url = [NSURL URLWithString:addr];
9272 CYViewController *page = [self pageForURL:url];
9274 [current addObject:page];
9277 [navigation setViewControllers:current];
9280 // (Try to) show the startup URL.
9281 if (starturl_ != nil) {
9282 [self openCydiaURL:starturl_];
9283 [starturl_ release];
9288 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9289 if (item != nil && IsWildcat_) {
9290 [sheet showFromBarButtonItem:item animated:YES];
9292 [sheet showInView:window_];
9299 id Alloc_(id self, SEL selector) {
9300 id object = alloc_(self, selector);
9301 lprintf("[%s]A-%p\n", self->isa->name, object);
9306 id Dealloc_(id self, SEL selector) {
9307 id object = dealloc_(self, selector);
9308 lprintf("[%s]D-%p\n", self->isa->name, object);
9312 Class $WebDefaultUIKitDelegate;
9314 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9315 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9316 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9317 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9320 static NSNumber *shouldPlayKeyboardSounds;
9324 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9326 case 1104: // Keyboard Button Clicked
9327 case 1105: // Keyboard Delete Repeated
9328 if (shouldPlayKeyboardSounds == nil) {
9329 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9330 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9333 if (![shouldPlayKeyboardSounds boolValue])
9337 _UIHardware$_playSystemSound$(self, _cmd, sound);
9341 Class $UIApplication;
9343 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9344 static BOOL initialized = NO;
9345 static BOOL started = NO;
9347 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9348 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9350 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9351 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9352 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9353 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9355 if (initialized && !enabled) {
9357 [bundle performSelector:@selector(_accessibilityStopServer)];
9358 } else if (enabled) {
9362 [bundle performSelector:@selector(_accessibilityStartServer)];
9368 int main(int argc, char *argv[]) { _pooled
9371 if (Class $UIDevice = objc_getClass("UIDevice")) {
9372 UIDevice *device([$UIDevice currentDevice]);
9373 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9377 UIScreen *screen([UIScreen mainScreen]);
9378 if ([screen respondsToSelector:@selector(scale)])
9379 ScreenScale_ = [screen scale];
9383 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9384 if (ScreenScale_ > 1)
9385 [parts addObject:@"@2x"];
9386 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9387 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9389 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9391 /* Library Hacks {{{ */
9392 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9394 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9395 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9396 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9397 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9398 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9401 $UIHardware = objc_getClass("UIHardware");
9402 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9403 if (UIHardware$_playSystemSound$ != NULL) {
9404 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9405 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9408 $UIApplication = objc_getClass("UIApplication");
9409 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9410 if (UIApplication$_updateApplicationAccessibility != NULL) {
9411 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9412 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9415 /* Set Locale {{{ */
9416 Locale_ = CFLocaleCopyCurrent();
9417 Languages_ = [NSLocale preferredLanguages];
9418 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9419 //NSLog(@"%@", [Languages_ description]);
9422 if (Languages_ == nil || [Languages_ count] == 0)
9423 // XXX: consider just setting to C and then falling through?
9426 lang = [[Languages_ objectAtIndex:0] UTF8String];
9427 setenv("LANG", lang, true);
9430 //std::setlocale(LC_ALL, lang);
9431 NSLog(@"Setting Language: %s", lang);
9434 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9436 /* Parse Arguments {{{ */
9437 bool substrate(false);
9443 for (int argi(1); argi != argc; ++argi)
9444 if (strcmp(argv[argi], "--") == 0) {
9446 argv[argi] = argv[0];
9452 for (int argi(1); argi != arge; ++argi)
9453 if (strcmp(args[argi], "--substrate") == 0)
9456 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9460 App_ = [[NSBundle mainBundle] bundlePath];
9461 Home_ = NSHomeDirectory();
9467 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9468 alloc_ = alloc->method_imp;
9469 alloc->method_imp = (IMP) &Alloc_;*/
9471 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9472 dealloc_ = dealloc->method_imp;
9473 dealloc->method_imp = (IMP) &Dealloc_;*/
9475 /* System Information {{{ */
9479 size = sizeof(maxproc);
9480 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9481 perror("sysctlbyname(\"kern.maxproc\", ?)");
9482 else if (maxproc < 64) {
9484 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9485 perror("sysctlbyname(\"kern.maxproc\", #)");
9488 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9489 char *osversion = new char[size];
9490 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9491 perror("sysctlbyname(\"kern.osversion\", ?)");
9493 System_ = [NSString stringWithUTF8String:osversion];
9495 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9496 char *machine = new char[size];
9497 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9498 perror("sysctlbyname(\"hw.machine\", ?)");
9502 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9503 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9504 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9505 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9509 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9510 NSData *data((NSData *) ecid);
9511 size_t length([data length]);
9512 uint8_t bytes[length];
9513 [data getBytes:bytes];
9514 char string[length * 2 + 1];
9515 for (size_t i(0); i != length; ++i)
9516 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9517 ChipID_ = [NSString stringWithUTF8String:string];
9521 IOObjectRelease(service);
9525 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9527 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9528 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9529 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9531 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9532 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9533 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9535 if (mcc != NULL && mnc != NULL)
9536 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9543 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9544 Build_ = [system objectForKey:@"ProductBuildVersion"];
9545 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9546 Product_ = [info objectForKey:@"SafariProductVersion"];
9547 Safari_ = [info objectForKey:@"CFBundleVersion"];
9550 /* Load Database {{{ */
9552 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9554 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9556 if (Metadata_ == NULL)
9557 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9559 Settings_ = [Metadata_ objectForKey:@"Settings"];
9561 Packages_ = [Metadata_ objectForKey:@"Packages"];
9562 Sections_ = [Metadata_ objectForKey:@"Sections"];
9563 Sources_ = [Metadata_ objectForKey:@"Sources"];
9565 Token_ = [Metadata_ objectForKey:@"Token"];
9568 if (Settings_ != nil)
9569 Role_ = [Settings_ objectForKey:@"Role"];
9571 if (Sections_ == nil) {
9572 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9573 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9576 if (Sources_ == nil) {
9577 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9578 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9583 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9586 if (Packages_ != nil) {
9588 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9592 [Metadata_ removeObjectForKey:@"Packages"];
9598 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9600 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9601 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9602 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9603 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9604 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9605 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9607 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9609 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9610 unlink("/tmp/.cydia.fw");
9612 } else if (access("/User", F_OK) != 0 || version < 2) {
9615 system("/usr/libexec/cydia/firmware.sh");
9619 _assert([[NSFileManager defaultManager]
9620 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9621 withIntermediateDirectories:YES
9626 if (access("/tmp/cydia.chk", F_OK) == 0) {
9627 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9628 _assert(errno == ENOENT);
9629 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9630 _assert(errno == ENOENT);
9633 /* APT Initialization {{{ */
9634 _assert(pkgInitConfig(*_config));
9635 _assert(pkgInitSystem(*_config, _system));
9638 _config->Set("APT::Acquire::Translation", lang);
9640 // XXX: this timeout might be important :(
9641 //_config->Set("Acquire::http::Timeout", 15);
9643 _config->Set("Acquire::http::MaxParallel", 3);
9645 /* Color Choices {{{ */
9646 space_ = CGColorSpaceCreateDeviceRGB();
9648 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9649 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9650 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9651 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9652 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9653 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9654 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9655 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9656 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9658 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9659 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9661 /* UIKit Configuration {{{ */
9662 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9663 if ($GSFontSetUseLegacyFontMetrics != NULL)
9664 $GSFontSetUseLegacyFontMetrics(YES);
9666 // XXX: I have a feeling this was important
9667 //UIKeyboardDisableAutomaticAppearance();
9670 Colon_ = UCLocalize("COLON_DELIMITED");
9671 Elision_ = UCLocalize("ELISION");
9672 Error_ = UCLocalize("ERROR");
9673 Warning_ = UCLocalize("WARNING");
9676 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9678 CGColorSpaceRelease(space_);