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 static _finline const char *StripVersion_(const char *version) {
1052 const char *colon(strchr(version, ':'));
1053 return colon == NULL ? version : colon + 1;
1056 NSString *LocalizeSection(NSString *section) {
1057 static Pcre title_r("^(.*?) \\((.*)\\)$");
1058 if (title_r(section)) {
1059 NSString *parent(title_r[1]);
1060 NSString *child(title_r[2]);
1062 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1063 LocalizeSection(parent),
1064 LocalizeSection(child)
1068 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1071 NSString *Simplify(NSString *title) {
1072 const char *data = [title UTF8String];
1073 size_t size = [title length];
1075 static Pcre square_r("^\\[(.*)\\]$");
1076 if (square_r(data, size))
1077 return Simplify(square_r[1]);
1079 static Pcre paren_r("^\\((.*)\\)$");
1080 if (paren_r(data, size))
1081 return Simplify(paren_r[1]);
1083 static Pcre title_r("^(.*?) \\((.*)\\)$");
1084 if (title_r(data, size))
1085 return Simplify(title_r[1]);
1091 NSString *GetLastUpdate() {
1092 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1095 return UCLocalize("NEVER_OR_UNKNOWN");
1097 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1098 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1100 CFRelease(formatter);
1102 return [(NSString *) formatted autorelease];
1105 bool isSectionVisible(NSString *section) {
1106 NSDictionary *metadata([Sections_ objectForKey:section]);
1107 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1108 return hidden == nil || ![hidden boolValue];
1113 /* Delegate Prototypes {{{ */
1117 @interface NSObject (ProgressDelegate)
1120 @protocol ProgressDelegate
1121 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1122 - (void) setProgressTitle:(NSString *)title;
1123 - (void) setProgressPercent:(float)percent;
1124 - (void) startProgress;
1125 - (void) addProgressOutput:(NSString *)output;
1126 - (bool) isCancelling:(size_t)received;
1129 @protocol ConfigurationDelegate
1130 - (void) repairWithSelector:(SEL)selector;
1131 - (void) setConfigurationData:(NSString *)data;
1134 @class CYPackageController;
1136 @protocol CydiaDelegate
1137 - (void) retainNetworkActivityIndicator;
1138 - (void) releaseNetworkActivityIndicator;
1139 - (void) clearPackage:(Package *)package;
1140 - (void) installPackage:(Package *)package;
1141 - (void) installPackages:(NSArray *)packages;
1142 - (void) removePackage:(Package *)package;
1143 - (void) beginUpdate;
1145 - (void) distUpgrade;
1147 - (void) updateData;
1149 - (void) showSettings;
1150 - (UIProgressHUD *) addProgressHUD;
1151 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1152 - (CYViewController *) pageForPackage:(NSString *)name;
1153 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1156 static id<CydiaDelegate> CydiaApp;
1159 /* Status Delegation {{{ */
1161 public pkgAcquireStatus
1164 _transient NSObject<ProgressDelegate> *delegate_;
1172 void setDelegate(id delegate) {
1173 delegate_ = delegate;
1176 NSObject<ProgressDelegate> *getDelegate() const {
1180 virtual bool MediaChange(std::string media, std::string drive) {
1184 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1187 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1188 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1189 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1192 virtual void Done(pkgAcquire::ItemDesc &item) {
1195 virtual void Fail(pkgAcquire::ItemDesc &item) {
1197 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1198 item.Owner->Status == pkgAcquire::Item::StatDone
1202 std::string &error(item.Owner->ErrorText);
1206 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1207 NSArray *fields([description componentsSeparatedByString:@" "]);
1208 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1210 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1211 withObject:[NSArray arrayWithObjects:
1212 [NSString stringWithUTF8String:error.c_str()],
1219 virtual bool Pulse(pkgAcquire *Owner) {
1220 bool value = pkgAcquireStatus::Pulse(Owner);
1223 double(CurrentBytes + CurrentItems) /
1224 double(TotalBytes + TotalItems)
1227 [delegate_ setProgressPercent:percent];
1228 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1231 virtual void Start() {
1232 [delegate_ startProgress];
1235 virtual void Stop() {
1239 /* Progress Delegation {{{ */
1244 _transient id<ProgressDelegate> delegate_;
1248 virtual void Update() {
1249 /*if (abs(Percent - percent_) > 2)
1250 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1254 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1255 [delegate_ setProgressPercent:(Percent / 100)];*/
1265 void setDelegate(id delegate) {
1266 delegate_ = delegate;
1269 id getDelegate() const {
1273 virtual void Done() {
1275 //[delegate_ setProgressPercent:1];
1280 /* Database Interface {{{ */
1281 typedef std::map< unsigned long, _H<Source> > SourceMap;
1283 @interface Database : NSObject {
1289 pkgCacheFile cache_;
1290 pkgDepCache::Policy *policy_;
1291 pkgRecords *records_;
1292 pkgProblemResolver *resolver_;
1293 pkgAcquire *fetcher_;
1295 SPtr<pkgPackageManager> manager_;
1296 pkgSourceList *list_;
1299 CFMutableArrayRef deadSources_;
1300 CFMutableArrayRef packages_;
1302 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1310 std::map<const char *, _H<NSString> > sections_;
1313 + (Database *) sharedInstance;
1316 - (void) _readCydia:(NSNumber *)fd;
1317 - (void) _readStatus:(NSNumber *)fd;
1318 - (void) _readOutput:(NSNumber *)fd;
1322 - (Package *) packageWithName:(NSString *)name;
1324 - (pkgCacheFile &) cache;
1325 - (pkgDepCache::Policy *) policy;
1326 - (pkgRecords *) records;
1327 - (pkgProblemResolver *) resolver;
1328 - (pkgAcquire &) fetcher;
1329 - (pkgSourceList &) list;
1330 - (NSArray *) packages;
1331 - (NSArray *) sources;
1332 - (void) reloadData;
1340 - (void) updateWithStatus:(Status &)status;
1342 - (void) setDelegate:(id)delegate;
1343 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1345 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1349 /* Delegate Helpers {{{ */
1350 @implementation NSObject (ProgressDelegate)
1352 - (void) _setProgressErrorPackage:(NSArray *)args {
1353 [self performSelector:@selector(setProgressError:forPackage:)
1354 withObject:[args objectAtIndex:0]
1355 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1359 - (void) _setProgressErrorTitle:(NSArray *)args {
1360 [self performSelector:@selector(setProgressError:withTitle:)
1361 withObject:[args objectAtIndex:0]
1362 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1366 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1367 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1368 withObject:[NSArray arrayWithObjects:error, title, nil]
1373 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1374 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1376 [self performSelector:@selector(setProgressError:withTitle:)
1378 withObject:(package == nil ? id : [package name])
1385 // Cytore Definitions {{{
1386 struct PackageValue :
1389 Cytore::Offset<PackageValue> next_;
1391 uint32_t index_ : 23;
1392 uint32_t subscribed_ : 1;
1409 Cytore::Offset<PackageValue> packages_[1 << 16];
1412 static Cytore::File<MetaValue> MetaFile_;
1414 // Cytore Helper Functions {{{
1415 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1416 SplitHash nhash = { hashlittle(name, length) };
1418 PackageValue *metadata;
1420 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1421 offset: if (offset->IsNull()) {
1422 *offset = MetaFile_.New<PackageValue>(length + 1);
1423 metadata = &MetaFile_.Get(*offset);
1425 if (metadata == NULL) {
1429 metadata = new PackageValue();
1430 memset(metadata, 0, sizeof(*metadata));
1433 memcpy(metadata->name_, name, length + 1);
1434 metadata->nhash_ = nhash.u16[1];
1436 metadata = &MetaFile_.Get(*offset);
1438 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1439 offset = &metadata->next_;
1447 static void PackageImport(const void *key, const void *value, void *context) {
1448 bool &fail(*reinterpret_cast<bool *>(context));
1451 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1452 NSLog(@"failed to import package %@", key);
1456 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1457 NSDictionary *package((NSDictionary *) value);
1459 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1460 if ([subscribed boolValue] && !metadata->subscribed_)
1461 metadata->subscribed_ = true;
1463 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1464 time_t time([date timeIntervalSince1970]);
1465 if (metadata->first_ > time || metadata->first_ == 0)
1466 metadata->first_ = time;
1469 NSDate *date([package objectForKey:@"LastSeen"]);
1470 NSString *version([package objectForKey:@"LastVersion"]);
1472 if (date != nil && version != nil) {
1473 time_t time([date timeIntervalSince1970]);
1474 if (metadata->last_ < time || metadata->last_ == 0)
1475 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1476 size_t length(strlen(buffer));
1477 uint16_t vhash(hashlittle(buffer, length));
1479 size_t capped(std::min<size_t>(8, length));
1480 char *latest(buffer + length - capped);
1482 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1483 metadata->vhash_ = vhash;
1485 metadata->last_ = time;
1491 /* Source Class {{{ */
1492 @interface Source : NSObject {
1493 CYString depiction_;
1494 CYString description_;
1500 CYString distribution_;
1505 NSString *authority_;
1507 CYString defaultIcon_;
1509 NSDictionary *record_;
1513 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1515 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1517 - (NSString *) depictionForPackage:(NSString *)package;
1518 - (NSString *) supportForPackage:(NSString *)package;
1520 - (NSDictionary *) record;
1524 - (NSString *) distribution;
1525 - (NSString *) type;
1527 - (NSString *) host;
1529 - (NSString *) name;
1530 - (NSString *) description;
1531 - (NSString *) label;
1532 - (NSString *) origin;
1533 - (NSString *) version;
1535 - (NSString *) defaultIcon;
1539 @implementation Source
1543 distribution_.clear();
1546 description_.clear();
1552 defaultIcon_.clear();
1554 if (record_ != nil) {
1564 if (authority_ != nil) {
1565 [authority_ release];
1571 // XXX: this is a very inefficient way to call these deconstructors
1576 + (NSArray *) _attributeKeys {
1577 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1580 - (NSArray *) attributeKeys {
1581 return [[self class] _attributeKeys];
1584 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1585 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1588 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1591 trusted_ = index->IsTrusted();
1593 uri_.set(pool, index->GetURI());
1594 distribution_.set(pool, index->GetDist());
1595 type_.set(pool, index->GetType());
1597 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1598 if (dindex != NULL) {
1600 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1603 pkgTagFile tags(&fd);
1605 pkgTagSection section;
1612 {"default-icon", &defaultIcon_},
1613 {"depiction", &depiction_},
1614 {"description", &description_},
1616 {"origin", &origin_},
1617 {"support", &support_},
1618 {"version", &version_},
1621 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1622 const char *start, *end;
1624 if (section.Find(names[i].name_, start, end)) {
1625 CYString &value(*names[i].value_);
1626 value.set(pool, start, end - start);
1632 record_ = [Sources_ objectForKey:[self key]];
1634 record_ = [record_ retain];
1636 NSURL *url([NSURL URLWithString:uri_]);
1640 host_ = [[host_ lowercaseString] retain];
1645 authority_ = [url path];
1647 if (authority_ != nil)
1648 authority_ = [authority_ retain];
1651 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1652 if ((self = [super init]) != nil) {
1653 [self setMetaIndex:index inPool:pool];
1657 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1658 NSDictionary *lhr = [self record];
1659 NSDictionary *rhr = [source record];
1662 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1664 NSString *lhs = [self name];
1665 NSString *rhs = [source name];
1667 if ([lhs length] != 0 && [rhs length] != 0) {
1668 unichar lhc = [lhs characterAtIndex:0];
1669 unichar rhc = [rhs characterAtIndex:0];
1671 if (isalpha(lhc) && !isalpha(rhc))
1672 return NSOrderedAscending;
1673 else if (!isalpha(lhc) && isalpha(rhc))
1674 return NSOrderedDescending;
1677 return [lhs compare:rhs options:LaxCompareOptions_];
1680 - (NSString *) depictionForPackage:(NSString *)package {
1681 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1684 - (NSString *) supportForPackage:(NSString *)package {
1685 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1688 - (NSDictionary *) record {
1696 - (NSString *) uri {
1700 - (NSString *) distribution {
1701 return distribution_;
1704 - (NSString *) type {
1708 - (NSString *) key {
1709 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1712 - (NSString *) host {
1716 - (NSString *) name {
1717 return origin_.empty() ? authority_ : origin_;
1720 - (NSString *) description {
1721 return description_;
1724 - (NSString *) label {
1725 return label_.empty() ? authority_ : label_;
1728 - (NSString *) origin {
1732 - (NSString *) version {
1736 - (NSString *) defaultIcon {
1737 return defaultIcon_;
1742 /* Relationship Class {{{ */
1743 @interface Relationship : NSObject {
1748 - (NSString *) type;
1750 - (NSString *) name;
1754 @implementation Relationship
1762 - (NSString *) type {
1770 - (NSString *) name {
1777 /* Package Class {{{ */
1778 struct ParsedPackage {
1783 CYString depiction_;
1793 @interface Package : NSObject {
1796 uint32_t essential_ : 1;
1797 uint32_t obsolete_ : 1;
1798 uint32_t ignored_ : 1;
1802 _transient Database *database_;
1804 pkgCache::VerIterator version_;
1805 pkgCache::PkgIterator iterator_;
1806 pkgCache::VerFileIterator file_;
1812 CYString installed_;
1814 const char *section_;
1815 _transient NSString *section$_;
1819 PackageValue *metadata_;
1820 ParsedPackage *parsed_;
1822 NSMutableArray *tags_;
1825 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1826 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1828 - (pkgCache::PkgIterator) iterator;
1831 - (NSString *) section;
1832 - (NSString *) simpleSection;
1834 - (NSString *) longSection;
1835 - (NSString *) shortSection;
1839 - (Address *) maintainer;
1841 - (NSString *) longDescription;
1842 - (NSString *) shortDescription;
1845 - (PackageValue *) metadata;
1848 - (bool) subscribed;
1849 - (bool) setSubscribed:(bool)subscribed;
1853 - (NSString *) latest;
1854 - (NSString *) installed;
1855 - (BOOL) uninstalled;
1858 - (BOOL) upgradableAndEssential:(BOOL)essential;
1861 - (BOOL) unfiltered;
1865 - (BOOL) halfConfigured;
1866 - (BOOL) halfInstalled;
1868 - (NSString *) mode;
1871 - (NSString *) name;
1873 - (NSString *) homepage;
1874 - (NSString *) depiction;
1875 - (Address *) author;
1877 - (NSString *) support;
1879 - (NSArray *) files;
1880 - (NSArray *) warnings;
1881 - (NSArray *) applications;
1883 - (Source *) source;
1885 - (BOOL) matches:(NSString *)text;
1887 - (bool) hasSupportingRole;
1888 - (BOOL) hasTag:(NSString *)tag;
1889 - (NSString *) primaryPurpose;
1890 - (NSArray *) purposes;
1891 - (bool) isCommercial;
1893 - (void) setIndex:(size_t)index;
1895 - (CYString &) cyname;
1897 - (uint32_t) compareBySection:(NSArray *)sections;
1902 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1903 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1904 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1905 - (bool) isVisibleInSection:(NSString *)section;
1906 - (bool) isVisibleInSource:(Source *)source;
1910 uint32_t PackageChangesRadix(Package *self, void *) {
1915 uint32_t timestamp : 30;
1916 uint32_t ignored : 1;
1917 uint32_t upgradable : 1;
1921 bool upgradable([self upgradableAndEssential:YES]);
1922 value.bits.upgradable = upgradable ? 1 : 0;
1925 value.bits.timestamp = 0;
1926 value.bits.ignored = [self ignored] ? 0 : 1;
1927 value.bits.upgradable = 1;
1929 value.bits.timestamp = [self seen] >> 2;
1930 value.bits.ignored = 0;
1931 value.bits.upgradable = 0;
1934 return _not(uint32_t) - value.key;
1937 uint32_t PackagePrefixRadix(Package *self, void *context) {
1938 size_t offset(reinterpret_cast<size_t>(context));
1939 CYString &name([self cyname]);
1941 size_t size(name.size());
1944 char *text(name.data());
1947 if (!isdigit(text[0]))
1951 while (size != digits && isdigit(text[digits]))
1959 if (offset == 0 && zeros != 0) {
1960 memset(data, '0', zeros);
1961 memcpy(data + zeros, text, 4 - zeros);
1963 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1964 if (size <= offset - zeros)
1967 text += offset - zeros;
1968 size -= offset - zeros;
1971 memcpy(data, text, 4);
1973 memcpy(data, text, size);
1974 memset(data + size, 0, 4 - size);
1977 for (size_t i(0); i != 4; ++i)
1978 if (isalpha(data[i]))
1986 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1988 /* XXX: ntohl may be more honest */
1989 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1992 CYString &(*PackageName)(Package *self, SEL sel);
1994 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1995 _profile(PackageNameCompare)
1996 CYString &lhi(PackageName(lhs, @selector(cyname)));
1997 CYString &rhi(PackageName(rhs, @selector(cyname)));
1998 CFStringRef lhn(lhi), rhn(rhi);
2001 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2002 else if (rhn == NULL)
2003 return NSOrderedDescending;
2005 _profile(PackageNameCompare$NumbersLast)
2006 if (!lhi.empty() && !rhi.empty()) {
2007 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2008 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2009 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2010 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2011 return lha ? NSOrderedAscending : NSOrderedDescending;
2015 CFIndex length = CFStringGetLength(lhn);
2017 _profile(PackageNameCompare$Compare)
2018 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2023 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2024 return PackageNameCompare(*lhs, *rhs, context);
2027 struct PackageNameOrdering :
2028 std::binary_function<Package *, Package *, bool>
2030 _finline bool operator ()(Package *lhs, Package *rhs) const {
2031 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2035 @implementation Package
2037 - (NSString *) description {
2038 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2042 if (parsed_ != NULL)
2051 + (NSString *) webScriptNameForSelector:(SEL)selector {
2052 if (selector == @selector(hasTag:))
2058 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2059 return [self webScriptNameForSelector:selector] == nil;
2062 + (NSArray *) _attributeKeys {
2063 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];
2066 - (NSArray *) attributeKeys {
2067 return [[self class] _attributeKeys];
2070 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2071 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2075 if (parsed_ != NULL)
2077 @synchronized (database_) {
2078 if ([database_ era] != era_ || file_.end())
2081 ParsedPackage *parsed(new ParsedPackage);
2084 _profile(Package$parse)
2085 pkgRecords::Parser *parser;
2087 _profile(Package$parse$Lookup)
2088 parser = &[database_ records]->Lookup(file_);
2093 _profile(Package$parse$Find)
2098 {"icon", &parsed->icon_},
2099 {"depiction", &parsed->depiction_},
2100 {"homepage", &parsed->homepage_},
2101 {"website", &website},
2102 {"bugs", &parsed->bugs_},
2103 {"support", &parsed->support_},
2104 {"sponsor", &parsed->sponsor_},
2105 {"author", &parsed->author_},
2108 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2109 const char *start, *end;
2111 if (parser->Find(names[i].name_, start, end)) {
2112 CYString &value(*names[i].value_);
2113 _profile(Package$parse$Value)
2114 value.set(pool_, start, end - start);
2120 _profile(Package$parse$Tagline)
2121 const char *start, *end;
2122 if (parser->ShortDesc(start, end)) {
2123 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2126 while (stop != start && stop[-1] == '\r')
2128 parsed->tagline_.set(pool_, start, stop - start);
2132 _profile(Package$parse$Retain)
2133 if (parsed->homepage_.empty())
2134 parsed->homepage_ = website;
2135 if (parsed->homepage_ == parsed->depiction_)
2136 parsed->homepage_.clear();
2141 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2142 if ((self = [super init]) != nil) {
2143 _profile(Package$initWithVersion)
2146 database_ = database;
2147 era_ = [database era];
2151 pkgCache::PkgIterator iterator(version.ParentPkg());
2152 iterator_ = iterator;
2154 _profile(Package$initWithVersion$Version)
2155 if (!version_.end())
2156 file_ = version_.FileList();
2158 pkgCache &cache([database_ cache]);
2159 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2163 _profile(Package$initWithVersion$Cache)
2164 name_.set(NULL, iterator.Display());
2166 latest_.set(NULL, StripVersion_(version_.VerStr()));
2168 pkgCache::VerIterator current(iterator.CurrentVer());
2170 installed_.set(NULL, StripVersion_(current.VerStr()));
2173 _profile(Package$initWithVersion$Tags)
2174 pkgCache::TagIterator tag(iterator.TagList());
2176 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2178 const char *name(tag.Name());
2179 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2181 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2182 if (strcmp(name + 6, "enduser") == 0)
2184 else if (strcmp(name + 6, "hacker") == 0)
2186 else if (strcmp(name + 6, "developer") == 0)
2188 else if (strcmp(name + 6, "cydia") == 0)
2194 if (strncmp(name, "cydia::", 7) == 0) {
2195 if (strcmp(name + 7, "essential") == 0)
2197 else if (strcmp(name + 7, "obsolete") == 0)
2202 } while (!tag.end());
2206 _profile(Package$initWithVersion$Metadata)
2207 const char *mixed(iterator.Name());
2208 size_t size(strlen(mixed));
2209 char lower[size + 1];
2211 for (size_t i(0); i != size; ++i)
2212 lower[i] = mixed[i] | 0x20;
2215 PackageValue *metadata(PackageFind(lower, size));
2216 metadata_ = metadata;
2218 id_.set(NULL, metadata->name_, size);
2220 const char *latest(version_.VerStr());
2221 size_t length(strlen(latest));
2223 uint16_t vhash(hashlittle(latest, length));
2225 size_t capped(std::min<size_t>(8, length));
2226 latest = latest + length - capped;
2228 if (metadata->first_ == 0)
2229 metadata->first_ = now_;
2231 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2232 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2233 metadata->vhash_ = vhash;
2234 metadata->last_ = now_;
2235 } else if (metadata->last_ == 0)
2236 metadata->last_ = metadata->first_;
2239 _profile(Package$initWithVersion$Section)
2240 section_ = iterator.Section();
2243 _profile(Package$initWithVersion$Flags)
2244 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2245 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2250 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2251 pkgCache::VerIterator version;
2253 _profile(Package$packageWithIterator$GetCandidateVer)
2254 version = [database policy]->GetCandidateVer(iterator);
2262 _profile(Package$packageWithIterator$Allocate)
2263 package = [Package allocWithZone:zone];
2266 _profile(Package$packageWithIterator$Initialize)
2268 initWithVersion:version
2275 _profile(Package$packageWithIterator$Autorelease)
2276 package = [package autorelease];
2282 - (pkgCache::PkgIterator) iterator {
2286 - (NSString *) section {
2287 if (section$_ == nil) {
2288 if (section_ == NULL)
2291 _profile(Package$section$mappedSectionForPointer)
2292 section$_ = [database_ mappedSectionForPointer:section_];
2297 - (NSString *) simpleSection {
2298 if (NSString *section = [self section])
2299 return Simplify(section);
2304 - (NSString *) longSection {
2305 return LocalizeSection([self section]);
2308 - (NSString *) shortSection {
2309 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2312 - (NSString *) uri {
2315 pkgIndexFile *index;
2316 pkgCache::PkgFileIterator file(file_.File());
2317 if (![database_ list].FindIndex(file, index))
2319 return [NSString stringWithUTF8String:iterator_->Path];
2320 //return [NSString stringWithUTF8String:file.Site()];
2321 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2325 - (Address *) maintainer {
2326 @synchronized (database_) {
2327 if ([database_ era] != era_ || file_.end())
2330 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2331 const std::string &maintainer(parser->Maintainer());
2332 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2336 @synchronized (database_) {
2337 if ([database_ era] != era_ || version_.end())
2340 return version_->InstalledSize;
2343 - (NSString *) longDescription {
2344 @synchronized (database_) {
2345 if ([database_ era] != era_ || file_.end())
2348 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2349 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2351 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2352 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2353 if ([lines count] < 2)
2356 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2357 for (size_t i(1), e([lines count]); i != e; ++i) {
2358 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2359 [trimmed addObject:trim];
2362 return [trimmed componentsJoinedByString:@"\n"];
2365 - (NSString *) shortDescription {
2366 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2370 _profile(Package$index)
2371 CFStringRef name((CFStringRef) [self name]);
2372 if (CFStringGetLength(name) == 0)
2374 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2375 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2377 return toupper(character);
2381 - (PackageValue *) metadata {
2386 PackageValue *metadata([self metadata]);
2387 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2390 - (bool) subscribed {
2391 return [self metadata]->subscribed_;
2394 - (bool) setSubscribed:(bool)subscribed {
2395 PackageValue *metadata([self metadata]);
2396 if (metadata->subscribed_ == subscribed)
2398 metadata->subscribed_ = subscribed;
2406 - (NSString *) latest {
2410 - (NSString *) installed {
2414 - (BOOL) uninstalled {
2415 return installed_.empty();
2419 return !version_.end();
2422 - (BOOL) upgradableAndEssential:(BOOL)essential {
2423 _profile(Package$upgradableAndEssential)
2424 pkgCache::VerIterator current(iterator_.CurrentVer());
2426 return essential && essential_;
2428 return !version_.end() && version_ != current;
2432 - (BOOL) essential {
2437 return [database_ cache][iterator_].InstBroken();
2440 - (BOOL) unfiltered {
2441 _profile(Package$unfiltered$obsolete)
2442 if (_unlikely(obsolete_))
2446 _profile(Package$unfiltered$hasSupportingRole)
2447 if (_unlikely(![self hasSupportingRole]))
2455 if (![self unfiltered])
2460 _profile(Package$visible$section)
2461 section = [self section];
2464 _profile(Package$visible$isSectionVisible)
2465 if (section != nil && !isSectionVisible(section))
2473 unsigned char current(iterator_->CurrentState);
2474 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2477 - (BOOL) halfConfigured {
2478 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2481 - (BOOL) halfInstalled {
2482 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2486 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2487 return state.Mode != pkgDepCache::ModeKeep;
2490 - (NSString *) mode {
2491 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2493 switch (state.Mode) {
2494 case pkgDepCache::ModeDelete:
2495 if ((state.iFlags & pkgDepCache::Purge) != 0)
2499 case pkgDepCache::ModeKeep:
2500 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2501 return @"REINSTALL";
2502 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2506 case pkgDepCache::ModeInstall:
2507 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2508 return @"REINSTALL";
2509 else*/ switch (state.Status) {
2511 return @"DOWNGRADE";
2517 return @"NEW_INSTALL";
2528 - (NSString *) name {
2529 return name_.empty() ? id_ : name_;
2532 - (UIImage *) icon {
2533 NSString *section = [self simpleSection];
2536 if (parsed_ != NULL)
2537 if (NSString *href = parsed_->icon_)
2538 if ([href hasPrefix:@"file:///"])
2539 // XXX: correct escaping
2540 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2541 if (icon == nil) if (section != nil)
2542 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2543 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2544 if ([dicon hasPrefix:@"file:///"])
2545 // XXX: correct escaping
2546 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2548 icon = [UIImage applicationImageNamed:@"unknown.png"];
2552 - (NSString *) homepage {
2553 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2556 - (NSString *) depiction {
2557 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2560 - (Address *) sponsor {
2561 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2564 - (Address *) author {
2565 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2568 - (NSString *) support {
2569 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2572 - (NSArray *) files {
2573 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2574 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2577 fin.open([path UTF8String]);
2582 while (std::getline(fin, line))
2583 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2588 - (NSArray *) warnings {
2589 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2590 const char *name(iterator_.Name());
2592 size_t length(strlen(name));
2593 if (length < 2) invalid:
2594 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2595 else for (size_t i(0); i != length; ++i)
2597 /* XXX: technically this is not allowed */
2598 (name[i] < 'A' || name[i] > 'Z') &&
2599 (name[i] < 'a' || name[i] > 'z') &&
2600 (name[i] < '0' || name[i] > '9') &&
2601 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2604 if (strcmp(name, "cydia") != 0) {
2607 bool _private = false;
2610 bool repository = [[self section] isEqualToString:@"Repositories"];
2612 if (NSArray *files = [self files])
2613 for (NSString *file in files)
2614 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2616 else if (!user && [file isEqualToString:@"/User"])
2618 else if (!_private && [file isEqualToString:@"/private"])
2620 else if (!stash && [file isEqualToString:@"/var/stash"])
2623 /* XXX: this is not sensitive enough. only some folders are valid. */
2624 if (cydia && !repository)
2625 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2627 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2629 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2631 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2634 return [warnings count] == 0 ? nil : warnings;
2637 - (NSArray *) applications {
2638 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2640 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2642 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2643 if (NSArray *files = [self files])
2644 for (NSString *file in files)
2645 if (application_r(file)) {
2646 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2647 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2648 if ([id isEqualToString:me])
2651 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2653 display = application_r[1];
2655 NSString *bundle([file stringByDeletingLastPathComponent]);
2656 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2657 if (icon == nil || [icon length] == 0)
2659 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2661 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2662 [applications addObject:application];
2664 [application addObject:id];
2665 [application addObject:display];
2666 [application addObject:url];
2669 return [applications count] == 0 ? nil : applications;
2672 - (Source *) source {
2673 if (source_ == nil) {
2674 @synchronized (database_) {
2675 if ([database_ era] != era_ || file_.end())
2676 source_ = (Source *) [NSNull null];
2678 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2682 return source_ == (Source *) [NSNull null] ? nil : source_;
2685 - (BOOL) matches:(NSString *)text {
2691 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2692 if (range.location != NSNotFound)
2695 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2696 if (range.location != NSNotFound)
2701 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2702 if (range.location != NSNotFound)
2708 - (bool) hasSupportingRole {
2713 if ([Role_ isEqualToString:@"User"])
2717 if ([Role_ isEqualToString:@"Hacker"])
2721 if ([Role_ isEqualToString:@"Developer"])
2726 - (BOOL) hasTag:(NSString *)tag {
2727 return tags_ == nil ? NO : [tags_ containsObject:tag];
2730 - (NSString *) primaryPurpose {
2731 for (NSString *tag in tags_)
2732 if ([tag hasPrefix:@"purpose::"])
2733 return [tag substringFromIndex:9];
2737 - (NSArray *) purposes {
2738 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2739 for (NSString *tag in tags_)
2740 if ([tag hasPrefix:@"purpose::"])
2741 [purposes addObject:[tag substringFromIndex:9]];
2742 return [purposes count] == 0 ? nil : purposes;
2745 - (bool) isCommercial {
2746 return [self hasTag:@"cydia::commercial"];
2749 - (void) setIndex:(size_t)index {
2750 if (metadata_->index_ != index)
2751 metadata_->index_ = index;
2754 - (CYString &) cyname {
2755 return name_.empty() ? id_ : name_;
2758 - (uint32_t) compareBySection:(NSArray *)sections {
2759 NSString *section([self section]);
2760 for (size_t i(0), e([sections count]); i != e; ++i) {
2761 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2765 return _not(uint32_t);
2769 @synchronized (database_) {
2770 pkgProblemResolver *resolver = [database_ resolver];
2771 resolver->Clear(iterator_);
2773 pkgCacheFile &cache([database_ cache]);
2774 cache->SetReInstall(iterator_, false);
2775 cache->MarkKeep(iterator_, false);
2779 @synchronized (database_) {
2780 pkgProblemResolver *resolver = [database_ resolver];
2781 resolver->Clear(iterator_);
2782 resolver->Protect(iterator_);
2784 pkgCacheFile &cache([database_ cache]);
2785 cache->SetReInstall(iterator_, false);
2786 cache->MarkInstall(iterator_, false);
2788 pkgDepCache::StateCache &state((*cache)[iterator_]);
2789 if (!state.Install())
2790 cache->SetReInstall(iterator_, true);
2794 @synchronized (database_) {
2795 pkgProblemResolver *resolver = [database_ resolver];
2796 resolver->Clear(iterator_);
2797 resolver->Remove(iterator_);
2798 resolver->Protect(iterator_);
2800 pkgCacheFile &cache([database_ cache]);
2801 cache->SetReInstall(iterator_, false);
2802 cache->MarkDelete(iterator_, true);
2805 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2806 _profile(Package$isUnfilteredAndSearchedForBy)
2809 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2810 value &= [self unfiltered];
2813 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2814 value &= [self matches:search];
2821 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2822 if ([search length] == 0)
2825 _profile(Package$isUnfilteredAndSelectedForBy)
2828 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2829 value &= [self unfiltered];
2832 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2833 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2840 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2841 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2844 - (bool) isVisibleInSection:(NSString *)name {
2845 NSString *section([self section]);
2849 section == nil && [name length] == 0 ||
2850 [name isEqualToString:section]
2851 ) && [self visible];
2854 - (bool) isVisibleInSource:(Source *)source {
2855 return [self source] == source && [self visible];
2860 /* Section Class {{{ */
2861 @interface Section : NSObject {
2866 NSString *localized_;
2869 - (NSComparisonResult) compareByLocalized:(Section *)section;
2870 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2871 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2872 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2873 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2874 - (NSString *) name;
2881 - (void) addToCount;
2883 - (void) setCount:(size_t)count;
2884 - (NSString *) localized;
2888 @implementation Section
2892 if (localized_ != nil)
2893 [localized_ release];
2897 - (NSComparisonResult) compareByLocalized:(Section *)section {
2898 NSString *lhs(localized_);
2899 NSString *rhs([section localized]);
2901 /*if ([lhs length] != 0 && [rhs length] != 0) {
2902 unichar lhc = [lhs characterAtIndex:0];
2903 unichar rhc = [rhs characterAtIndex:0];
2905 if (isalpha(lhc) && !isalpha(rhc))
2906 return NSOrderedAscending;
2907 else if (!isalpha(lhc) && isalpha(rhc))
2908 return NSOrderedDescending;
2911 return [lhs compare:rhs options:LaxCompareOptions_];
2914 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2915 if ((self = [self initWithName:name localize:NO]) != nil) {
2916 if (localized != nil)
2917 localized_ = [localized retain];
2921 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2922 return [self initWithName:name row:0 localize:localize];
2925 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2926 if ((self = [super init]) != nil) {
2927 name_ = [name retain];
2931 localized_ = [LocalizeSection(name_) retain];
2935 /* XXX: localize the index thingees */
2936 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2937 if ((self = [super init]) != nil) {
2938 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2944 - (NSString *) name {
2964 - (void) addToCount {
2968 - (void) setCount:(size_t)count {
2972 - (NSString *) localized {
2979 static NSString *Colon_;
2980 static NSString *Elision_;
2981 static NSString *Error_;
2982 static NSString *Warning_;
2984 /* Database Implementation {{{ */
2985 @implementation Database
2987 + (Database *) sharedInstance {
2988 static Database *instance;
2989 if (instance == nil)
2990 instance = [[Database alloc] init];
2998 - (void) releasePackages {
2999 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3000 CFArrayRemoveAllValues(packages_);
3004 // XXX: actually implement this thing
3007 CFRelease(deadSources_);
3008 [self releasePackages];
3009 apr_pool_destroy(pool_);
3010 NSRecycleZone(zone_);
3014 - (void) _readCydia:(NSNumber *)fd { _pooled
3015 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3016 std::istream is(&ib);
3019 static Pcre finish_r("^finish:([^:]*)$");
3021 while (std::getline(is, line)) {
3022 const char *data(line.c_str());
3023 size_t size = line.size();
3024 lprintf("C:%s\n", data);
3026 if (finish_r(data, size)) {
3027 NSString *finish = finish_r[1];
3028 int index = [Finishes_ indexOfObject:finish];
3029 if (index != INT_MAX && index > Finish_)
3037 - (void) _readStatus:(NSNumber *)fd { _pooled
3038 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3039 std::istream is(&ib);
3042 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3043 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3045 while (std::getline(is, line)) {
3046 const char *data(line.c_str());
3047 size_t size(line.size());
3048 lprintf("S:%s\n", data);
3050 if (conffile_r(data, size)) {
3051 [delegate_ setConfigurationData:conffile_r[1]];
3052 } else if (strncmp(data, "status: ", 8) == 0) {
3053 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3054 [delegate_ setProgressTitle:string];
3055 } else if (pmstatus_r(data, size)) {
3056 std::string type([pmstatus_r[1] UTF8String]);
3057 NSString *id = pmstatus_r[2];
3059 float percent([pmstatus_r[3] floatValue]);
3060 [delegate_ setProgressPercent:(percent / 100)];
3062 NSString *string = pmstatus_r[4];
3064 if (type == "pmerror")
3065 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3066 withObject:[NSArray arrayWithObjects:string, id, nil]
3069 else if (type == "pmstatus") {
3070 [delegate_ setProgressTitle:string];
3071 } else if (type == "pmconffile")
3072 [delegate_ setConfigurationData:string];
3074 lprintf("E:unknown pmstatus\n");
3076 lprintf("E:unknown status\n");
3082 - (void) _readOutput:(NSNumber *)fd { _pooled
3083 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3084 std::istream is(&ib);
3087 while (std::getline(is, line)) {
3088 lprintf("O:%s\n", line.c_str());
3089 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3099 - (Package *) packageWithName:(NSString *)name {
3100 @synchronized (self) {
3101 if (static_cast<pkgDepCache *>(cache_) == NULL)
3103 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3104 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3108 if ((self = [super init]) != nil) {
3115 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3116 apr_pool_create(&pool_, NULL);
3118 size_t capacity(MetaFile_->active_);
3124 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3125 deadSources_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
3129 _assert(pipe(fds) != -1);
3132 _config->Set("APT::Keep-Fds::", cydiafd_);
3133 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3136 detachNewThreadSelector:@selector(_readCydia:)
3138 withObject:[NSNumber numberWithInt:fds[0]]
3141 _assert(pipe(fds) != -1);
3145 detachNewThreadSelector:@selector(_readStatus:)
3147 withObject:[NSNumber numberWithInt:fds[0]]
3150 _assert(pipe(fds) != -1);
3151 _assert(dup2(fds[0], 0) != -1);
3152 _assert(close(fds[0]) != -1);
3154 input_ = fdopen(fds[1], "a");
3156 _assert(pipe(fds) != -1);
3157 _assert(dup2(fds[1], 1) != -1);
3158 _assert(close(fds[1]) != -1);
3161 detachNewThreadSelector:@selector(_readOutput:)
3163 withObject:[NSNumber numberWithInt:fds[0]]
3168 - (pkgCacheFile &) cache {
3172 - (pkgDepCache::Policy *) policy {
3176 - (pkgRecords *) records {
3180 - (pkgProblemResolver *) resolver {
3184 - (pkgAcquire &) fetcher {
3188 - (pkgSourceList &) list {
3192 - (NSArray *) packages {
3193 return (NSArray *) packages_;
3196 - (NSArray *) sources {
3197 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3198 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3199 [sources addObject:i->second];
3200 [sources addObjectsFromArray:(NSArray *)deadSources_];
3204 - (bool) popErrorWithTitle:(NSString *)title {
3206 std::string message;
3208 while (!_error->empty()) {
3210 bool warning(!_error->PopMessage(error));
3214 size_t size(error.size());
3215 if (size == 0 || error[size - 1] != '\n')
3217 error.resize(size - 1);
3219 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3221 if (!message.empty())
3226 if (fatal && !message.empty())
3227 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3232 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3233 return [self popErrorWithTitle:title] || !success;
3236 - (void) reloadData { CYPoolStart() {
3237 @synchronized (self) {
3240 [self releasePackages];
3243 CFArrayRemoveAllValues(deadSources_);
3263 apr_pool_clear(pool_);
3265 NSRecycleZone(zone_);
3266 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3268 int chk(creat("/tmp/cydia.chk", 0644));
3272 NSString *title(UCLocalize("DATABASE"));
3275 while (!cache_.Open(progress_, true)) { pop:
3277 bool warning(!_error->PopMessage(error));
3278 lprintf("cache_.Open():[%s]\n", error.c_str());
3280 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3281 [delegate_ repairWithSelector:@selector(configure)];
3282 else if (error == "The package lists or status file could not be parsed or opened.")
3283 [delegate_ repairWithSelector:@selector(update)];
3284 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3285 else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3286 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, Error_, title]];
3287 // else if (error == "The list of sources could not be read.")
3289 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3299 unlink("/tmp/cydia.chk");
3301 now_ = [[NSDate date] timeIntervalSince1970];
3303 policy_ = new pkgDepCache::Policy();
3304 records_ = new pkgRecords(cache_);
3305 resolver_ = new pkgProblemResolver(cache_);
3306 fetcher_ = new pkgAcquire(&status_);
3309 list_ = new pkgSourceList();
3310 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3313 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3314 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3318 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3321 if (cache_->BrokenCount() != 0) {
3322 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3325 if (cache_->BrokenCount() != 0) {
3326 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3330 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3334 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3336 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3337 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3338 // XXX: this could be more intelligent
3339 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3340 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3341 if (!cached.end()) {
3342 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3347 CFArrayAppendValue(deadSources_, [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3351 /*std::vector<Package *> packages;
3352 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3353 [packages_ release];
3358 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3359 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3360 //packages.push_back(package);
3361 CFArrayAppendValue(packages_, [package retain]);
3365 /*if (packages.empty())
3366 packages_ = [[NSArray alloc] init];
3368 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3371 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3372 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3373 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3381 /*if (!packages.empty())
3382 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3383 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3385 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3387 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3389 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3393 size_t count(CFArrayGetCount(packages_));
3394 MetaFile_->active_ = count;
3396 for (size_t index(0); index != count; ++index)
3397 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3401 } } CYPoolEnd() _trace(); }
3404 @synchronized (self) {
3406 resolver_ = new pkgProblemResolver(cache_);
3408 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3409 if (!cache_[iterator].Keep())
3410 cache_->MarkKeep(iterator, false);
3411 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3412 cache_->SetReInstall(iterator, false);
3415 - (void) configure {
3416 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3418 system([dpkg UTF8String]);
3423 // XXX: I don't remember this condition
3428 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3430 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3432 if ([self popErrorWithTitle:title])
3436 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3439 public pkgArchiveCleaner
3442 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3447 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3454 fetcher_->Shutdown();
3456 pkgRecords records(cache_);
3458 lock_ = new FileFd();
3459 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3461 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3463 if ([self popErrorWithTitle:title])
3467 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3470 manager_ = (_system->CreatePM(cache_));
3471 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3478 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3480 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3482 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3484 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3485 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3488 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3493 [CydiaApp retainNetworkActivityIndicator];
3495 bool failed = false;
3496 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3497 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3499 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3502 std::string uri = (*item)->DescURI();
3503 std::string error = (*item)->ErrorText;
3505 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3508 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3509 withObject:[NSArray arrayWithObjects:
3510 [NSString stringWithUTF8String:error.c_str()],
3516 [CydiaApp releaseNetworkActivityIndicator];
3524 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3526 if (_error->PendingError()) {
3531 if (result == pkgPackageManager::Failed) {
3536 if (result != pkgPackageManager::Completed) {
3541 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3543 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3545 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3546 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3549 if (![before isEqualToArray:after])
3554 NSString *title(UCLocalize("UPGRADE"));
3555 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3561 [self updateWithStatus:status_];
3564 - (void) updateWithStatus:(Status &)status {
3565 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3566 NSString *title(UCLocalize("REFRESHING_DATA"));
3569 if (!list.ReadMainList())
3570 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3573 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3574 if ([self popErrorWithTitle:title])
3577 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3578 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3579 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3581 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3585 - (void) setDelegate:(id)delegate {
3586 delegate_ = delegate;
3587 status_.setDelegate(delegate);
3588 progress_.setDelegate(delegate);
3591 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3592 SourceMap::const_iterator i(sources_.find(file->ID));
3593 return i == sources_.end() ? nil : i->second;
3596 - (NSString *) mappedSectionForPointer:(const char *)section {
3597 _H<NSString> *mapped;
3599 _profile(Database$mappedSectionForPointer$Cache)
3600 mapped = §ions_[section];
3603 if (*mapped == NULL) {
3604 size_t length(strlen(section));
3605 char spaced[length + 1];
3607 _profile(Database$mappedSectionForPointer$Replace)
3608 for (size_t index(0); index != length; ++index)
3609 spaced[index] = section[index] == '_' ? ' ' : section[index];
3610 spaced[length] = '\0';
3615 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3616 string = [NSString stringWithUTF8String:spaced];
3619 _profile(Database$mappedSectionForPointer$Map)
3620 string = [SectionMap_ objectForKey:string] ?: string;
3630 /* Web Scripting {{{ */
3631 @interface CydiaObject : NSObject {
3633 _transient id delegate_;
3636 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3639 @implementation CydiaObject
3642 [indirect_ release];
3646 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3647 if ((self = [super init]) != nil) {
3648 indirect_ = [indirect retain];
3652 - (void) setDelegate:(id)delegate {
3653 delegate_ = delegate;
3656 + (NSArray *) _attributeKeys {
3657 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3660 - (NSArray *) attributeKeys {
3661 return [[self class] _attributeKeys];
3664 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3665 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3668 - (NSString *) device {
3669 return [[UIDevice currentDevice] uniqueIdentifier];
3672 #if 0 // XXX: implement!
3673 - (NSString *) mac {
3674 if (![indirect_ promptForSensitive:@"Mac Address"])
3678 - (NSString *) serial {
3679 if (![indirect_ promptForSensitive:@"Serial #"])
3683 - (NSString *) firewire {
3684 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3688 - (NSString *) imei {
3689 if (![indirect_ promptForSensitive:@"IMEI"])
3694 + (NSString *) webScriptNameForSelector:(SEL)selector {
3695 if (selector == @selector(close))
3697 else if (selector == @selector(getInstalledPackages))
3698 return @"getInstalledPackages";
3699 else if (selector == @selector(getPackageById:))
3700 return @"getPackageById";
3701 else if (selector == @selector(installPackages:))
3702 return @"installPackages";
3703 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3704 return @"setButtonImage";
3705 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3706 return @"setButtonTitle";
3707 else if (selector == @selector(setPopupHook:))
3708 return @"setPopupHook";
3709 else if (selector == @selector(setSpecial:))
3710 return @"setSpecial";
3711 else if (selector == @selector(setToken:))
3713 else if (selector == @selector(setViewportWidth:))
3714 return @"setViewportWidth";
3715 else if (selector == @selector(supports:))
3717 else if (selector == @selector(stringWithFormat:arguments:))
3719 else if (selector == @selector(localizedStringForKey:value:table:))
3721 else if (selector == @selector(du:))
3723 else if (selector == @selector(statfs:))
3729 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3730 return [self webScriptNameForSelector:selector] == nil;
3733 - (BOOL) supports:(NSString *)feature {
3734 return [feature isEqualToString:@"window.open"];
3737 - (NSArray *) getInstalledPackages {
3738 NSArray *packages([[Database sharedInstance] packages]);
3739 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3740 for (Package *package in packages)
3741 if ([package installed] != nil)
3742 [installed addObject:package];
3746 - (Package *) getPackageById:(NSString *)id {
3747 Package *package([[Database sharedInstance] packageWithName:id]);
3752 - (NSArray *) statfs:(NSString *)path {
3755 if (path == nil || statfs([path UTF8String], &stat) == -1)
3758 return [NSArray arrayWithObjects:
3759 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3760 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3761 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3765 - (NSNumber *) du:(NSString *)path {
3766 NSNumber *value(nil);
3769 _assert(pipe(fds) != -1);
3771 pid_t pid(ExecFork());
3773 _assert(dup2(fds[1], 1) != -1);
3774 _assert(close(fds[0]) != -1);
3775 _assert(close(fds[1]) != -1);
3776 /* XXX: this should probably not use du */
3777 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3782 _assert(close(fds[1]) != -1);
3784 if (FILE *du = fdopen(fds[0], "r")) {
3786 while (fgets(line, sizeof(line), du) != NULL) {
3787 size_t length(strlen(line));
3788 while (length != 0 && line[length - 1] == '\n')
3789 line[--length] = '\0';
3790 if (char *tab = strchr(line, '\t')) {
3792 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3797 } else _assert(close(fds[0]));
3801 if (waitpid(pid, &status, 0) == -1)
3804 else _assert(false);
3813 - (void) installPackages:(NSArray *)packages {
3814 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3817 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3818 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3821 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3822 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3825 - (void) setSpecial:(id)function {
3826 [indirect_ setSpecial:function];
3829 - (void) setToken:(NSString *)token {
3832 Token_ = [token retain];
3834 [Metadata_ setObject:Token_ forKey:@"Token"];
3838 - (void) setPopupHook:(id)function {
3839 [indirect_ setPopupHook:function];
3842 - (void) setViewportWidth:(float)width {
3843 [indirect_ setViewportWidth:width];
3846 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3847 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3848 unsigned count([arguments count]);
3850 for (unsigned i(0); i != count; ++i)
3851 values[i] = [arguments objectAtIndex:i];
3852 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3855 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3856 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3858 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3860 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3866 /* @ Loading... Indicator {{{ */
3867 @interface CYLoadingIndicator : UIView {
3868 UIActivityIndicatorView *spinner_;
3873 @property (readonly, nonatomic) UILabel *label;
3874 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
3878 @implementation CYLoadingIndicator
3880 - (id)initWithFrame:(CGRect)frame {
3881 if ((self = [super initWithFrame:frame])) {
3882 container_ = [[[UIView alloc] init] autorelease];
3883 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
3885 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
3886 [spinner_ startAnimating];
3887 [container_ addSubview:spinner_];
3889 label_ = [[[UILabel alloc] init] autorelease];
3890 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
3891 [label_ setBackgroundColor:[UIColor clearColor]];
3892 [label_ setTextColor:[UIColor blackColor]];
3893 [label_ setShadowColor:[UIColor whiteColor]];
3894 [label_ setShadowOffset:CGSizeMake(0, 1)];
3895 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
3896 [container_ addSubview:label_];
3898 CGSize viewsize = frame.size;
3899 CGSize spinnersize = [spinner_ bounds].size;
3900 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
3901 float bothwidth = spinnersize.width + textsize.width + 5.0f;
3903 CGRect containrect = {
3904 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
3905 CGSizeMake(bothwidth, spinnersize.height)
3908 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
3916 [container_ setFrame:containrect];
3917 [spinner_ setFrame:spinrect];
3918 [label_ setFrame:textrect];
3919 [self addSubview:container_];
3925 - (UILabel *)label { return label_; }
3926 - (UIActivityIndicatorView *)activityIndicatorView { return spinner_; }
3930 /* Emulated Loading Controller {{{ */
3931 @interface CYEmulatedLoadingController : CYViewController <
3933 ConfigurationDelegate
3935 _transient Database *database_;
3936 CYLoadingIndicator *indicator_;
3938 UINavigationBar *navbar_;
3942 @implementation CYEmulatedLoadingController
3945 [self releaseSubviews];
3946 [database_ setDelegate:nil];
3951 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
3952 CYAlertView *sheet([[[CYAlertView alloc]
3954 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
3955 defaultButtonIndex:0
3958 [sheet setMessage:error];
3959 [sheet yieldToPopupAlertAnimated:YES];
3963 - (void) setProgressTitle:(NSString *)title { }
3964 - (void) setProgressPercent:(float)percent { }
3965 - (void) startProgress { }
3966 - (void) addProgressOutput:(NSString *)output { }
3967 - (bool) isCancelling:(size_t)received { return NO; }
3968 - (void) setConfigurationData:(NSString *)data { }
3970 - (void) repairWithSelector:(SEL)selector {
3971 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("REPAIRING"), nil] waitUntilDone:YES];
3972 [database_ performSelector:selector];
3974 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil] waitUntilDone:YES];
3977 - (id) initWithDatabase:(Database *)database {
3978 if ((self = [super init])) {
3979 database_ = database;
3980 [database_ setDelegate:self];
3985 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
3986 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
3988 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
3989 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
3990 [[self view] addSubview:indicator_];
3992 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
3993 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
3994 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
3995 [[self view] addSubview:tabbar_];
3997 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
3998 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
3999 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4000 [[self view] addSubview:navbar_];
4003 - (void) releaseSubviews {
4004 [indicator_ release];
4017 /* Cydia Browser Controller {{{ */
4018 @interface CYBrowserController : BrowserController {
4019 CydiaObject *cydia_;
4024 @implementation CYBrowserController
4031 - (NSURL *) navigationURL {
4032 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4035 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4038 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4039 [super webView:view didClearWindowObject:window forFrame:frame];
4041 WebDataSource *source([frame dataSource]);
4042 NSURLResponse *response([source response]);
4044 NSURL *url([response URL]);
4045 NSString *scheme([url scheme]);
4046 NSString *host([url host]);
4048 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4049 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4050 NSDictionary *headers([http allHeaderFields]);
4051 [self setHeaders:headers forHost:host];
4055 [host isEqualToString:@"cydia.saurik.com"] ||
4056 [host hasSuffix:@".cydia.saurik.com"] ||
4057 [scheme isEqualToString:@"file"]
4059 [window setValue:cydia_ forKey:@"cydia"];
4062 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4063 if (System_ != NULL)
4064 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4065 if (Machine_ != NULL)
4066 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4068 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4070 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4073 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4074 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4075 [self _setMoreHeaders:copy];
4079 - (void) setDelegate:(id)delegate {
4080 [super setDelegate:delegate];
4081 [cydia_ setDelegate:delegate];
4085 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4086 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4088 WebView *webview([[webview_ _documentView] webView]);
4090 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4092 NSString *application = package == nil ? @"Cydia" : [NSString
4093 stringWithFormat:@"Cydia/%@",
4098 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4100 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4101 if (Product_ != nil)
4102 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4104 [webview setApplicationNameForUserAgent:application];
4112 @interface NSObject (CydiaScript)
4113 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4116 @implementation NSObject (CydiaScript)
4118 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4124 @implementation NSArray (CydiaScript)
4126 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4127 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4128 for (size_t i(0), e([self count]); i != e; ++i)
4129 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4135 @implementation NSDictionary (CydiaScript)
4137 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4138 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4140 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4147 /* Confirmation Controller {{{ */
4148 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4149 if (!iterator.end())
4150 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4151 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4153 pkgCache::PkgIterator package(dep.TargetPkg());
4156 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4163 @protocol ConfirmationControllerDelegate
4164 - (void) cancelAndClear:(bool)clear;
4165 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4169 @interface ConfirmationController : CYBrowserController {
4170 _transient Database *database_;
4172 UIAlertView *essential_;
4174 NSDictionary *changes_;
4175 NSMutableArray *issues_;
4176 NSDictionary *sizes_;
4181 - (id) initWithDatabase:(Database *)database;
4185 @implementation ConfirmationController
4192 if (essential_ != nil)
4193 [essential_ release];
4198 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4199 NSString *context([alert context]);
4201 if ([context isEqualToString:@"remove"]) {
4202 if (button == [alert cancelButtonIndex]) {
4203 [self dismissModalViewControllerAnimated:YES];
4204 } else if (button == [alert firstOtherButtonIndex]) {
4207 [delegate_ confirmWithNavigationController:[self navigationController]];
4210 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4211 } else if ([context isEqualToString:@"unable"]) {
4212 [self dismissModalViewControllerAnimated:YES];
4213 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4215 [super alertView:alert clickedButtonAtIndex:button];
4219 - (void) _doContinue {
4220 [self dismissModalViewControllerAnimated:YES];
4221 [delegate_ cancelAndClear:NO];
4224 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4225 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4229 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4230 [super webView:view didClearWindowObject:window forFrame:frame];
4232 [window setValue:[changes_ Cydia$webScriptObjectInContext:window] forKey:@"changes"];
4233 [window setValue:[issues_ Cydia$webScriptObjectInContext:window] forKey:@"issues"];
4234 [window setValue:[sizes_ Cydia$webScriptObjectInContext:window] forKey:@"sizes"];
4236 [window setValue:self forKey:@"queue"];
4239 - (id) initWithDatabase:(Database *)database {
4240 if ((self = [super init]) != nil) {
4241 database_ = database;
4243 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4244 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4245 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4246 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4247 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4251 pkgCacheFile &cache([database_ cache]);
4252 NSArray *packages([database_ packages]);
4253 pkgDepCache::Policy *policy([database_ policy]);
4255 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4257 for (Package *package in packages) {
4258 pkgCache::PkgIterator iterator([package iterator]);
4259 NSString *name([package id]);
4261 if ([package broken]) {
4262 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4264 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4266 reasons, @"reasons",
4269 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4273 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4274 pkgCache::DepIterator start;
4275 pkgCache::DepIterator end;
4276 dep.GlobOr(start, end); // ++dep
4278 if (!cache->IsImportantDep(end))
4280 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4284 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4286 pkgCache::PkgIterator target(start.TargetPkg());
4287 if (target->ProvidesList != 0)
4288 reason = @"missing";
4290 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4292 reason = @"installed";
4293 installed = [NSString stringWithUTF8String:ver.VerStr()];
4294 } else if (!cache[target].CandidateVerIter(cache).end())
4295 reason = @"uninstalled";
4296 else if (target->ProvidesList == 0)
4297 reason = @"uninstallable";
4299 reason = @"virtual";
4302 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4303 [NSString stringWithUTF8String:start.CompType()], @"operator",
4304 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4307 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4308 [NSString stringWithUTF8String:start.DepType()], @"relation",
4309 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4310 version, @"version",
4312 installed, @"installed",
4315 // yes, seriously. (wtf?)
4323 pkgDepCache::StateCache &state(cache[iterator]);
4325 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4327 if (state.NewInstall())
4328 [installs addObject:name];
4329 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4330 [reinstalls addObject:name];
4331 else if (state.Upgrade())
4332 [upgrades addObject:name];
4333 else if (state.Downgrade())
4334 [downgrades addObject:name];
4335 else if (!state.Delete())
4337 else if (special_r(name))
4338 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4339 [NSNull null], @"package",
4340 [NSArray arrayWithObjects:
4341 [NSDictionary dictionaryWithObjectsAndKeys:
4342 @"Conflicts", @"relation",
4344 [NSNull null], @"version",
4345 @"installed", @"reason",
4350 if ([package essential])
4352 [removes addObject:name];
4355 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4356 substrate_ |= DepSubstrate(iterator.CurrentVer());
4361 else if (Advanced_) {
4362 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4364 essential_ = [[UIAlertView alloc]
4365 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4366 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4368 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4370 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4374 [essential_ setContext:@"remove"];
4376 essential_ = [[UIAlertView alloc]
4377 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4378 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4380 cancelButtonTitle:UCLocalize("OKAY")
4381 otherButtonTitles:nil
4384 [essential_ setContext:@"unable"];
4387 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4388 installs, @"installs",
4389 reinstalls, @"reinstalls",
4390 upgrades, @"upgrades",
4391 downgrades, @"downgrades",
4392 removes, @"removes",
4395 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4396 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4397 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4400 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4402 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4403 initWithTitle:UCLocalize("CANCEL")
4404 style:UIBarButtonItemStylePlain
4406 action:@selector(cancelButtonClicked)
4412 - (void) applyRightButton {
4413 if ([issues_ count] == 0 && ![self isLoading])
4414 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4415 initWithTitle:UCLocalize("CONFIRM")
4416 style:UIBarButtonItemStyleDone
4418 action:@selector(confirmButtonClicked)
4421 [[self navigationItem] setRightBarButtonItem:nil];
4425 - (void) cancelButtonClicked {
4426 [self dismissModalViewControllerAnimated:YES];
4427 [delegate_ cancelAndClear:YES];
4431 - (void) confirmButtonClicked {
4432 if (essential_ != nil)
4437 [delegate_ confirmWithNavigationController:[self navigationController]];
4445 /* Progress Data {{{ */
4446 @interface ProgressData : NSObject {
4448 // XXX: should these really both be _transient?
4449 _transient id target_;
4450 _transient id object_;
4453 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4460 @implementation ProgressData
4462 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4463 if ((self = [super init]) != nil) {
4464 selector_ = selector;
4484 /* Progress Controller {{{ */
4485 @interface ProgressController : CYViewController <
4486 ConfigurationDelegate,
4489 _transient Database *database_;
4490 UIProgressBar *progress_;
4491 UITextView *output_;
4492 UITextLabel *status_;
4493 UIPushButton *close_;
4495 SHA1SumValue springlist_;
4496 SHA1SumValue notifyconf_;
4500 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4502 - (void) _retachThread;
4503 - (void) _detachNewThreadData:(ProgressData *)data;
4504 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4510 @protocol ProgressControllerDelegate
4511 - (void) progressControllerIsComplete:(ProgressController *)sender;
4514 @implementation ProgressController
4517 [database_ setDelegate:nil];
4518 [progress_ release];
4527 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4528 if ((self = [super init]) != nil) {
4529 database_ = database;
4530 [database_ setDelegate:self];
4531 delegate_ = delegate;
4533 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4535 progress_ = [[UIProgressBar alloc] init];
4536 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4537 [progress_ setStyle:0];
4539 status_ = [[UITextLabel alloc] init];
4540 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4541 [status_ setColor:[UIColor whiteColor]];
4542 [status_ setBackgroundColor:[UIColor clearColor]];
4543 [status_ setCentersHorizontally:YES];
4544 //[status_ setFont:font];
4546 output_ = [[UITextView alloc] init];
4547 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4548 //[output_ setTextFont:@"Courier New"];
4549 [output_ setFont:[[output_ font] fontWithSize:12]];
4550 [output_ setTextColor:[UIColor whiteColor]];
4551 [output_ setBackgroundColor:[UIColor clearColor]];
4552 [output_ setMarginTop:0];
4553 [output_ setAllowsRubberBanding:YES];
4554 [output_ setEditable:NO];
4555 [[self view] addSubview:output_];
4557 close_ = [[UIPushButton alloc] init];
4558 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4559 [close_ setAutosizesToFit:NO];
4560 [close_ setDrawsShadow:YES];
4561 [close_ setStretchBackground:YES];
4562 [close_ setEnabled:YES];
4563 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4564 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4565 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4566 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4570 - (void) positionViews {
4571 CGRect bounds = [[self view] bounds];
4572 CGSize prgsize = [UIProgressBar defaultSize];
4575 (bounds.size.width - prgsize.width) / 2,
4576 bounds.size.height - prgsize.height - 20
4579 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4581 [progress_ setFrame:prgrect];
4582 [status_ setFrame:CGRectMake(
4584 bounds.size.height - prgsize.height - 50,
4585 bounds.size.width - 20,
4588 [output_ setFrame:CGRectMake(
4591 bounds.size.width - 20,
4592 bounds.size.height - 96
4594 [close_ setFrame:CGRectMake(
4595 (bounds.size.width - closewidth) / 2,
4596 bounds.size.height - prgsize.height - 50,
4602 - (void) viewWillAppear:(BOOL)animated {
4603 [super viewDidAppear:animated];
4604 [[self navigationItem] setHidesBackButton:YES];
4605 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4607 [self positionViews];
4610 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4611 [self positionViews];
4614 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4615 NSString *context([alert context]);
4617 if ([context isEqualToString:@"conffile"]) {
4618 FILE *input = [database_ input];
4619 if (button == [alert cancelButtonIndex])
4620 fprintf(input, "N\n");
4621 else if (button == [alert firstOtherButtonIndex])
4622 fprintf(input, "Y\n");
4627 - (void) closeButtonPushed {
4630 UpdateExternalStatus(0);
4634 [self dismissModalViewControllerAnimated:YES];
4638 [delegate_ terminateWithSuccess];
4639 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4640 [delegate_ suspendWithAnimation:YES];
4642 [delegate_ suspend];*/
4654 system("/usr/bin/sbreload");
4660 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4661 SBReboot(SBSSpringBoardServerPort());
4663 reboot2(RB_AUTOBOOT);
4668 - (void) _retachThread {
4669 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4671 [[self view] addSubview:close_];
4672 [progress_ removeFromSuperview];
4673 [status_ removeFromSuperview];
4675 [database_ popErrorWithTitle:title_];
4676 [delegate_ progressControllerIsComplete:self];
4680 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4683 MMap mmap(file, MMap::ReadOnly);
4685 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4686 if (!(notifyconf_ == sha1.Result()))
4693 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4696 MMap mmap(file, MMap::ReadOnly);
4698 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4699 if (!(springlist_ == sha1.Result()))
4705 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4706 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4707 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4708 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4709 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4713 system("su -c /usr/bin/uicache mobile");
4716 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4718 [delegate_ setStatusBarShowsProgress:NO];
4721 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4722 [[data target] performSelector:[data selector] withObject:[data object]];
4723 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4726 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4727 UpdateExternalStatus(1);
4734 title_ = [title retain];
4736 [[self navigationItem] setTitle:title_];
4738 [status_ setText:nil];
4739 [output_ setText:@""];
4740 [progress_ setProgress:0];
4742 [close_ removeFromSuperview];
4743 [[self view] addSubview:progress_];
4744 [[self view] addSubview:status_];
4746 [delegate_ setStatusBarShowsProgress:YES];
4751 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4754 MMap mmap(file, MMap::ReadOnly);
4756 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4757 notifyconf_ = sha1.Result();
4763 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4766 MMap mmap(file, MMap::ReadOnly);
4768 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4769 springlist_ = sha1.Result();
4774 detachNewThreadSelector:@selector(_detachNewThreadData:)
4776 withObject:[[[ProgressData alloc]
4777 initWithSelector:selector
4784 - (void) repairWithSelector:(SEL)selector {
4786 detachNewThreadSelector:selector
4789 title:UCLocalize("REPAIRING")
4793 - (void) setConfigurationData:(NSString *)data {
4795 performSelectorOnMainThread:@selector(_setConfigurationData:)
4801 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4802 CYAlertView *sheet([[[CYAlertView alloc]
4804 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4805 defaultButtonIndex:0
4808 [sheet setMessage:error];
4809 [sheet yieldToPopupAlertAnimated:YES];
4813 - (void) setProgressTitle:(NSString *)title {
4815 performSelectorOnMainThread:@selector(_setProgressTitle:)
4821 - (void) setProgressPercent:(float)percent {
4823 performSelectorOnMainThread:@selector(_setProgressPercent:)
4824 withObject:[NSNumber numberWithFloat:percent]
4829 - (void) startProgress {
4832 - (void) addProgressOutput:(NSString *)output {
4834 performSelectorOnMainThread:@selector(_addProgressOutput:)
4840 - (bool) isCancelling:(size_t)received {
4844 - (void) _setConfigurationData:(NSString *)data {
4845 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4847 if (!conffile_r(data)) {
4848 lprintf("E:invalid conffile\n");
4852 NSString *ofile = conffile_r[1];
4853 //NSString *nfile = conffile_r[2];
4855 UIAlertView *alert = [[[UIAlertView alloc]
4856 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4857 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4859 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4861 UCLocalize("ACCEPT_NEW_COPY"),
4862 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4866 [alert setContext:@"conffile"];
4870 - (void) _setProgressTitle:(NSString *)title {
4871 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4872 for (size_t i(0), e([words count]); i != e; ++i) {
4873 NSString *word([words objectAtIndex:i]);
4874 if (Package *package = [database_ packageWithName:word])
4875 [words replaceObjectAtIndex:i withObject:[package name]];
4878 [status_ setText:[words componentsJoinedByString:@" "]];
4881 - (void) _setProgressPercent:(NSNumber *)percent {
4882 [progress_ setProgress:[percent floatValue]];
4885 - (void) _addProgressOutput:(NSString *)output {
4886 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4887 CGSize size = [output_ contentSize];
4888 CGPoint offset = [output_ contentOffset];
4889 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4890 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4891 [output_ scrollRectToVisible:rect animated:YES];
4895 - (BOOL) isRunning {
4902 /* Cell Content View {{{ */
4903 @protocol ContentDelegate
4904 - (void) drawContentRect:(CGRect)rect;
4907 @interface ContentView : UIView {
4908 _transient id<ContentDelegate> delegate_;
4913 @implementation ContentView
4915 - (id) initWithFrame:(CGRect)frame {
4916 if ((self = [super initWithFrame:frame]) != nil) {
4917 [self setNeedsDisplayOnBoundsChange:YES];
4921 - (void) setDelegate:(id<ContentDelegate>)delegate {
4922 delegate_ = delegate;
4925 - (void) drawRect:(CGRect)rect {
4926 [super drawRect:rect];
4927 [delegate_ drawContentRect:rect];
4932 /* Cydia TableView Cell {{{ */
4933 @interface CYTableViewCell : UITableViewCell {
4934 ContentView *content_;
4940 @implementation CYTableViewCell
4947 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4948 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4950 if (view == content_) {
4951 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4952 highlighted_ = highlighted;
4955 [super _updateHighlightColorsForView:view highlighted:highlighted];
4958 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4959 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4960 highlighted_ = selected;
4962 [super setSelected:selected animated:animated];
4963 [content_ setNeedsDisplay];
4969 /* Package Cell {{{ */
4970 @interface PackageCell : CYTableViewCell <
4975 NSString *description_;
4983 - (PackageCell *) init;
4984 - (void) setPackage:(Package *)package;
4986 - (void) drawContentRect:(CGRect)rect;
4990 @implementation PackageCell
4992 - (void) clearPackage {
5003 if (description_ != nil) {
5004 [description_ release];
5008 if (source_ != nil) {
5013 if (badge_ != nil) {
5018 if (placard_ != nil) {
5028 [self clearPackage];
5032 - (PackageCell *) init {
5033 CGRect frame(CGRectMake(0, 0, 320, 74));
5034 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5035 UIView *content([self contentView]);
5036 CGRect bounds([content bounds]);
5038 content_ = [[ContentView alloc] initWithFrame:bounds];
5039 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5040 [content addSubview:content_];
5042 [content_ setDelegate:self];
5043 [content_ setOpaque:YES];
5047 - (NSString *) accessibilityLabel {
5048 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5051 - (void) setPackage:(Package *)package {
5052 [self clearPackage];
5055 Source *source = [package source];
5057 icon_ = [[package icon] retain];
5058 name_ = [[package name] retain];
5061 description_ = [package longDescription];
5062 if (description_ == nil)
5063 description_ = [package shortDescription];
5064 if (description_ != nil)
5065 description_ = [description_ retain];
5067 commercial_ = [package isCommercial];
5069 package_ = [package retain];
5071 NSString *label = nil;
5072 bool trusted = false;
5074 if (source != nil) {
5075 label = [source label];
5076 trusted = [source trusted];
5077 } else if ([[package id] isEqualToString:@"firmware"])
5078 label = UCLocalize("APPLE");
5080 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5082 NSString *from(label);
5084 NSString *section = [package simpleSection];
5085 if (section != nil && ![section isEqualToString:label]) {
5086 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5087 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5090 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5091 source_ = [from retain];
5093 if (NSString *purpose = [package primaryPurpose])
5094 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5095 badge_ = [badge_ retain];
5100 if (NSString *mode = [package_ mode]) {
5101 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5102 color = RemovingColor_;
5103 //placard = @"removing";
5105 color = InstallingColor_;
5106 //placard = @"installing";
5109 // XXX: the removing/installing placards are not @2x
5112 color = [UIColor whiteColor];
5114 if ([package installed] != nil)
5115 placard = @"installed";
5120 [content_ setBackgroundColor:color];
5123 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5124 placard_ = [placard_ retain];
5126 [self setNeedsDisplay];
5127 [content_ setNeedsDisplay];
5130 - (void) drawContentRect:(CGRect)rect {
5131 bool highlighted(highlighted_);
5132 float width([self bounds].size.width);
5135 CGContextRef context(UIGraphicsGetCurrentContext());
5136 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5137 CGContextFillRect(context, rect);
5142 rect.size = [icon_ size];
5144 rect.size.width /= 2;
5145 rect.size.height /= 2;
5147 rect.origin.x = 25 - rect.size.width / 2;
5148 rect.origin.y = 25 - rect.size.height / 2;
5150 [icon_ drawInRect:rect];
5153 if (badge_ != nil) {
5155 rect.size = [badge_ size];
5157 rect.size.width /= 2;
5158 rect.size.height /= 2;
5160 rect.origin.x = 36 - rect.size.width / 2;
5161 rect.origin.y = 36 - rect.size.height / 2;
5163 [badge_ drawInRect:rect];
5170 UISetColor(commercial_ ? Purple_ : Black_);
5171 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5172 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5175 UISetColor(commercial_ ? Purplish_ : Gray_);
5176 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5178 if (placard_ != nil)
5179 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5184 /* Section Cell {{{ */
5185 @interface SectionCell : CYTableViewCell <
5197 - (void) setSection:(Section *)section editing:(BOOL)editing;
5201 @implementation SectionCell
5203 - (void) clearSection {
5204 if (basic_ != nil) {
5209 if (section_ != nil) {
5219 if (count_ != nil) {
5226 [self clearSection];
5232 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5233 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5234 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5235 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5236 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5238 UIView *content([self contentView]);
5239 CGRect bounds([content bounds]);
5241 content_ = [[ContentView alloc] initWithFrame:bounds];
5242 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5243 [content addSubview:content_];
5244 [content_ setBackgroundColor:[UIColor whiteColor]];
5246 [content_ setDelegate:self];
5250 - (void) onSwitch:(id)sender {
5251 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5252 if (metadata == nil) {
5253 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5254 [Sections_ setObject:metadata forKey:basic_];
5257 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5261 - (void) setSection:(Section *)section editing:(BOOL)editing {
5262 if (editing != editing_) {
5264 [switch_ removeFromSuperview];
5266 [self addSubview:switch_];
5270 [self clearSection];
5272 if (section == nil) {
5273 name_ = [UCLocalize("ALL_PACKAGES") retain];
5276 basic_ = [section name];
5278 basic_ = [basic_ retain];
5280 section_ = [section localized];
5281 if (section_ != nil)
5282 section_ = [section_ retain];
5284 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5285 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5288 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5291 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5292 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5294 [content_ setNeedsDisplay];
5297 - (void) setFrame:(CGRect)frame {
5298 [super setFrame:frame];
5300 CGRect rect([switch_ frame]);
5301 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5304 - (NSString *) accessibilityLabel {
5308 - (void) drawContentRect:(CGRect)rect {
5309 bool highlighted(highlighted_ && !editing_);
5311 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5316 float width(rect.size.width);
5322 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5324 CGSize size = [count_ sizeWithFont:Font14_];
5328 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5334 /* File Table {{{ */
5335 @interface FileTable : CYViewController <
5336 UITableViewDataSource,
5339 _transient Database *database_;
5342 NSMutableArray *files_;
5346 - (id) initWithDatabase:(Database *)database;
5347 - (void) setPackage:(Package *)package;
5351 @implementation FileTable
5354 [self releaseSubviews];
5363 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5364 return files_ == nil ? 0 : [files_ count];
5367 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5371 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5372 static NSString *reuseIdentifier = @"Cell";
5374 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5376 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5377 [cell setFont:[UIFont systemFontOfSize:16]];
5379 [cell setText:[files_ objectAtIndex:indexPath.row]];
5380 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5385 - (NSURL *) navigationURL {
5386 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5390 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5392 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5393 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5394 [list_ setRowHeight:24.0f];
5395 [list_ setDataSource:self];
5396 [list_ setDelegate:self];
5397 [[self view] addSubview:list_];
5400 - (void) viewDidLoad {
5401 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5404 - (void) releaseSubviews {
5409 - (id) initWithDatabase:(Database *)database {
5410 if ((self = [super init]) != nil) {
5411 database_ = database;
5413 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5417 - (void) setPackage:(Package *)package {
5418 if (package_ != nil) {
5419 [package_ autorelease];
5428 [files_ removeAllObjects];
5430 if (package != nil) {
5431 package_ = [package retain];
5432 name_ = [[package id] retain];
5434 if (NSArray *files = [package files])
5435 [files_ addObjectsFromArray:files];
5437 if ([files_ count] != 0) {
5438 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5439 [files_ removeObjectAtIndex:0];
5440 [files_ sortUsingSelector:@selector(compareByPath:)];
5442 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5443 [stack addObject:@"/"];
5445 for (int i(0), e([files_ count]); i != e; ++i) {
5446 NSString *file = [files_ objectAtIndex:i];
5447 while (![file hasPrefix:[stack lastObject]])
5448 [stack removeLastObject];
5449 NSString *directory = [stack lastObject];
5450 [stack addObject:[file stringByAppendingString:@"/"]];
5451 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5452 ([stack count] - 2) * 3, "",
5453 [file substringFromIndex:[directory length]]
5462 - (void) reloadData {
5465 [self setPackage:[database_ packageWithName:name_]];
5470 /* Package Controller {{{ */
5471 @interface CYPackageController : CYBrowserController <
5472 UIActionSheetDelegate
5474 _transient Database *database_;
5478 NSMutableArray *buttons_;
5479 UIBarButtonItem *button_;
5482 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5486 @implementation CYPackageController
5489 if (package_ != nil)
5502 - (NSURL *) navigationURL {
5503 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5506 /* XXX: this is not safe at all... localization of /fail/ */
5507 - (void) _clickButtonWithName:(NSString *)name {
5508 if ([name isEqualToString:UCLocalize("CLEAR")])
5509 [delegate_ clearPackage:package_];
5510 else if ([name isEqualToString:UCLocalize("INSTALL")])
5511 [delegate_ installPackage:package_];
5512 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5513 [delegate_ installPackage:package_];
5514 else if ([name isEqualToString:UCLocalize("REMOVE")])
5515 [delegate_ removePackage:package_];
5516 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5517 [delegate_ installPackage:package_];
5518 else _assert(false);
5521 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5522 NSString *context([sheet context]);
5524 if ([context isEqualToString:@"modify"]) {
5525 if (button != [sheet cancelButtonIndex]) {
5526 NSString *buttonName = [buttons_ objectAtIndex:button];
5527 [self _clickButtonWithName:buttonName];
5530 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5534 - (bool) _allowJavaScriptPanel {
5539 - (void) _customButtonClicked {
5540 int count([buttons_ count]);
5545 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5547 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5548 [buttons addObjectsFromArray:buttons_];
5550 UIActionSheet *sheet = [[[UIActionSheet alloc]
5553 cancelButtonTitle:nil
5554 destructiveButtonTitle:nil
5555 otherButtonTitles:nil
5558 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5560 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5561 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5563 [sheet setContext:@"modify"];
5565 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5569 // We don't want to allow non-commercial packages to do custom things to the install button,
5570 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5571 - (void) customButtonClicked {
5573 [super customButtonClicked];
5575 [self _customButtonClicked];
5578 - (void) reloadButtonClicked {
5579 // Don't reload a commerical package by tapping the loading button,
5580 // but if it's not an Install button, we should forward it on.
5581 if (![package_ uninstalled])
5582 [self _customButtonClicked];
5585 - (void) applyLoadingTitle {
5586 // Don't show "Loading" as the title. Ever.
5589 - (UIBarButtonItem *) rightButton {
5594 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5595 if ((self = [super init]) != nil) {
5596 database_ = database;
5597 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5598 name_ = [[NSString alloc] initWithString:name];
5602 - (void) reloadData {
5605 if (package_ != nil)
5606 [package_ autorelease];
5607 package_ = [database_ packageWithName:name_];
5609 [buttons_ removeAllObjects];
5611 if (package_ != nil) {
5614 package_ = [package_ retain];
5615 commercial_ = [package_ isCommercial];
5617 if ([package_ mode] != nil)
5618 [buttons_ addObject:UCLocalize("CLEAR")];
5619 if ([package_ source] == nil);
5620 else if ([package_ upgradableAndEssential:NO])
5621 [buttons_ addObject:UCLocalize("UPGRADE")];
5622 else if ([package_ uninstalled])
5623 [buttons_ addObject:UCLocalize("INSTALL")];
5625 [buttons_ addObject:UCLocalize("REINSTALL")];
5626 if (![package_ uninstalled])
5627 [buttons_ addObject:UCLocalize("REMOVE")];
5634 switch ([buttons_ count]) {
5635 case 0: title = nil; break;
5636 case 1: title = [buttons_ objectAtIndex:0]; break;
5637 default: title = UCLocalize("MODIFY"); break;
5640 button_ = [[UIBarButtonItem alloc]
5642 style:UIBarButtonItemStylePlain
5644 action:@selector(customButtonClicked)
5647 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5650 - (bool) isLoading {
5651 return commercial_ ? [super isLoading] : false;
5657 /* Package List Controller {{{ */
5658 @interface PackageListController : CYViewController <
5659 UITableViewDataSource,
5662 _transient Database *database_;
5664 NSMutableArray *packages_;
5665 NSMutableArray *sections_;
5667 NSMutableArray *index_;
5668 NSMutableDictionary *indices_;
5672 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5673 - (void) setDelegate:(id)delegate;
5674 - (void) resetCursor;
5678 @implementation PackageListController
5681 [packages_ release];
5682 [sections_ release];
5691 - (void) deselectWithAnimation:(BOOL)animated {
5692 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5695 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5696 CGRect base = [[self view] bounds];
5697 base.size.height -= bounds.size.height;
5698 base.origin = [list_ frame].origin;
5700 [UIView beginAnimations:nil context:NULL];
5701 [UIView setAnimationBeginsFromCurrentState:YES];
5702 [UIView setAnimationCurve:curve];
5703 [UIView setAnimationDuration:duration];
5704 [list_ setFrame:base];
5705 [UIView commitAnimations];
5708 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5709 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5712 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5713 [self resizeForKeyboardBounds:bounds duration:0];
5716 - (void) keyboardWillShow:(NSNotification *)notification {
5719 NSTimeInterval duration;
5720 UIViewAnimationCurve curve;
5721 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5722 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5723 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5724 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5726 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);
5727 UIViewController *base = self;
5728 while ([base parentViewController] != nil)
5729 base = [base parentViewController];
5730 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5731 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5733 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5736 - (void) keyboardWillHide:(NSNotification *)notification {
5737 NSTimeInterval duration;
5738 UIViewAnimationCurve curve;
5739 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5740 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5742 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5745 - (void) viewWillAppear:(BOOL)animated {
5746 [super viewWillAppear:animated];
5748 [self resizeForKeyboardBounds:CGRectZero];
5749 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5750 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5753 - (void) viewWillDisappear:(BOOL)animated {
5754 [super viewWillDisappear:animated];
5756 [self resizeForKeyboardBounds:CGRectZero];
5757 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5758 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5761 - (void) viewDidAppear:(BOOL)animated {
5762 [super viewDidAppear:animated];
5763 [self deselectWithAnimation:animated];
5766 - (void) didSelectPackage:(Package *)package {
5767 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5768 [view setDelegate:delegate_];
5769 [[self navigationController] pushViewController:view animated:YES];
5772 #if TryIndexedCollation
5773 + (BOOL) hasIndexedCollation {
5774 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5778 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5779 NSInteger count([sections_ count]);
5780 return count == 0 ? 1 : count;
5783 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5784 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5786 return [[sections_ objectAtIndex:section] name];
5789 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5790 if ([sections_ count] == 0)
5792 return [[sections_ objectAtIndex:section] count];
5795 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5796 @synchronized (database_) {
5797 if ([database_ era] != era_)
5800 Section *section([sections_ objectAtIndex:[path section]]);
5801 NSInteger row([path row]);
5802 Package *package([packages_ objectAtIndex:([section row] + row)]);
5803 return [[package retain] autorelease];
5806 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5807 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5809 cell = [[[PackageCell alloc] init] autorelease];
5810 [cell setPackage:[self packageAtIndexPath:path]];
5814 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5815 Package *package([self packageAtIndexPath:path]);
5816 package = [database_ packageWithName:[package id]];
5817 [self didSelectPackage:package];
5820 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5821 // XXX: is 20 the most optimal number here?
5822 return [packages_ count] > 20 ? index_ : nil;
5825 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5826 #if TryIndexedCollation
5827 if ([[self class] hasIndexedCollation]) {
5828 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5835 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5836 if ((self = [super init]) != nil) {
5837 database_ = database;
5838 title_ = [title copy];
5839 [[self navigationItem] setTitle:title_];
5841 #if TryIndexedCollation
5842 if ([[self class] hasIndexedCollation])
5843 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
5846 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5848 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5850 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5851 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5853 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
5854 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5855 [list_ setRowHeight:73];
5856 [[self view] addSubview:list_];
5858 [list_ setDataSource:self];
5859 [list_ setDelegate:self];
5863 - (void) setDelegate:(id)delegate {
5864 delegate_ = delegate;
5867 - (bool) hasPackage:(Package *)package {
5871 - (void) reloadData {
5874 era_ = [database_ era];
5875 NSArray *packages = [database_ packages];
5877 [packages_ removeAllObjects];
5878 [sections_ removeAllObjects];
5880 _profile(PackageTable$reloadData$Filter)
5881 for (Package *package in packages)
5882 if ([self hasPackage:package])
5883 [packages_ addObject:package];
5886 [indices_ removeAllObjects];
5888 Section *section = nil;
5890 #if TryIndexedCollation
5891 if ([[self class] hasIndexedCollation]) {
5892 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5893 NSArray *titles = [collation sectionIndexTitles];
5896 _profile(PackageTable$reloadData$Section)
5897 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5901 _profile(PackageTable$reloadData$Section$Package)
5902 package = [packages_ objectAtIndex:offset];
5903 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5906 while (secidx < index) {
5909 _profile(PackageTable$reloadData$Section$Allocate)
5910 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5913 _profile(PackageTable$reloadData$Section$Add)
5914 [sections_ addObject:section];
5918 [section addToCount];
5924 [index_ removeAllObjects];
5926 _profile(PackageTable$reloadData$Section)
5927 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5931 _profile(PackageTable$reloadData$Section$Package)
5932 package = [packages_ objectAtIndex:offset];
5933 index = [package index];
5936 if (section == nil || [section index] != index) {
5937 _profile(PackageTable$reloadData$Section$Allocate)
5938 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5941 [index_ addObject:[section name]];
5942 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5944 _profile(PackageTable$reloadData$Section$Add)
5945 [sections_ addObject:section];
5949 [section addToCount];
5954 _profile(PackageTable$reloadData$List)
5959 - (void) resetCursor {
5960 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5965 /* Filtered Package List Controller {{{ */
5966 @interface FilteredPackageListController : PackageListController {
5972 - (void) setObject:(id)object;
5973 - (void) setObject:(id)object forFilter:(SEL)filter;
5975 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5979 @implementation FilteredPackageListController
5987 - (void) setFilter:(SEL)filter {
5990 /* XXX: this is an unsafe optimization of doomy hell */
5991 Method method(class_getInstanceMethod([Package class], filter));
5992 _assert(method != NULL);
5993 imp_ = method_getImplementation(method);
5994 _assert(imp_ != NULL);
5997 - (void) setObject:(id)object {
6003 object_ = [object retain];
6006 - (void) setObject:(id)object forFilter:(SEL)filter {
6007 [self setFilter:filter];
6008 [self setObject:object];
6011 - (bool) hasPackage:(Package *)package {
6012 _profile(FilteredPackageTable$hasPackage)
6013 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6017 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6018 if ((self = [super initWithDatabase:database title:title]) != nil) {
6019 [self setFilter:filter];
6020 [self setObject:object];
6028 /* Home Controller {{{ */
6029 @interface HomeController : CYBrowserController {
6033 @implementation HomeController
6035 + (BOOL) shouldHideNavigationBar {
6039 - (NSURL *) navigationURL {
6040 return [NSURL URLWithString:@"cydia://home"];
6043 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6044 [super _setMoreHeaders:request];
6047 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6048 if (UniqueID_ != nil)
6049 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6051 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6054 - (void) aboutButtonClicked {
6055 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6057 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6058 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6059 [alert setCancelButtonIndex:0];
6062 @"Copyright (C) 2008-2011\n"
6063 "Jay Freeman (saurik)\n"
6064 "saurik@saurik.com\n"
6065 "http://www.saurik.com/"
6071 - (void) viewWillDisappear:(BOOL)animated {
6072 [super viewWillDisappear:animated];
6074 if ([[self class] shouldHideNavigationBar])
6075 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6078 - (void) viewWillAppear:(BOOL)animated {
6079 if (![self hasLoaded])
6080 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6082 [super viewWillAppear:animated];
6084 if ([[self class] shouldHideNavigationBar])
6085 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6088 - (void) viewDidLoad {
6089 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6090 initWithTitle:UCLocalize("ABOUT")
6091 style:UIBarButtonItemStylePlain
6093 action:@selector(aboutButtonClicked)
6099 /* Manage Controller {{{ */
6100 @interface ManageController : CYBrowserController {
6103 - (void) queueStatusDidChange;
6106 @implementation ManageController
6108 - (NSURL *) navigationURL {
6109 return [NSURL URLWithString:@"cydia://manage"];
6112 - (void) viewWillAppear:(BOOL)animated {
6113 if (![self hasLoaded])
6114 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6116 [super viewWillAppear:animated];
6119 - (void) viewDidLoad {
6120 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6121 initWithTitle:UCLocalize("SETTINGS")
6122 style:UIBarButtonItemStylePlain
6124 action:@selector(settingsButtonClicked)
6127 [self queueStatusDidChange];
6130 - (void) settingsButtonClicked {
6131 [delegate_ showSettings];
6135 - (void) queueButtonClicked {
6139 - (void) applyLoadingTitle {
6140 // Disable "Loading" title.
6143 - (void) applyRightButton {
6144 // Disable right button.
6148 - (void) queueStatusDidChange {
6150 if (!IsWildcat_ && Queuing_) {
6151 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6152 initWithTitle:UCLocalize("QUEUE")
6153 style:UIBarButtonItemStyleDone
6155 action:@selector(queueButtonClicked)
6158 [[self navigationItem] setRightBarButtonItem:nil];
6163 - (bool) isLoading {
6164 // Never show as loading.
6171 /* Refresh Bar {{{ */
6172 @interface RefreshBar : UINavigationBar {
6173 UIProgressIndicator *indicator_;
6174 UITextLabel *prompt_;
6175 UIProgressBar *progress_;
6176 UINavigationButton *cancel_;
6181 @implementation RefreshBar
6184 [indicator_ release];
6186 [progress_ release];
6191 - (void) positionViews {
6192 CGRect frame = [cancel_ frame];
6193 frame.size = [cancel_ sizeThatFits:frame.size];
6194 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6195 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6196 [cancel_ setFrame:frame];
6198 CGSize prgsize = {75, 100};
6200 [self frame].size.width - prgsize.width - 10,
6201 ([self frame].size.height - prgsize.height) / 2
6203 [progress_ setFrame:prgrect];
6205 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6206 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6207 CGRect indrect = {{indoffset, indoffset}, indsize};
6208 [indicator_ setFrame:indrect];
6210 CGSize prmsize = {215, indsize.height + 4};
6212 indoffset * 2 + indsize.width,
6213 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6215 [prompt_ setFrame:prmrect];
6218 - (void)setFrame:(CGRect)frame {
6219 [super setFrame:frame];
6221 [self positionViews];
6224 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6225 if ((self = [super initWithFrame:frame])) {
6226 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6228 [self setBarStyle:UIBarStyleBlack];
6230 UIBarStyle barstyle([self _barStyle:NO]);
6231 bool ugly(barstyle == UIBarStyleDefault);
6233 UIProgressIndicatorStyle style = ugly ?
6234 UIProgressIndicatorStyleMediumBrown :
6235 UIProgressIndicatorStyleMediumWhite;
6237 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6238 [indicator_ setStyle:style];
6239 [indicator_ startAnimation];
6240 [self addSubview:indicator_];
6242 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6243 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6244 [prompt_ setBackgroundColor:[UIColor clearColor]];
6245 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6246 [self addSubview:prompt_];
6248 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6249 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6250 [progress_ setStyle:0];
6251 [self addSubview:progress_];
6253 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6254 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6255 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6256 [cancel_ setBarStyle:barstyle];
6258 [self positionViews];
6263 [cancel_ removeFromSuperview];
6267 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6268 [progress_ setProgress:0];
6269 [self addSubview:cancel_];
6273 [cancel_ removeFromSuperview];
6276 - (void) setPrompt:(NSString *)prompt {
6277 [prompt_ setText:prompt];
6280 - (void) setProgress:(float)progress {
6281 [progress_ setProgress:progress];
6287 @class CYNavigationController;
6289 /* Cydia Tab Bar Controller {{{ */
6290 @interface CYTabBarController : UITabBarController <
6291 UITabBarControllerDelegate,
6294 _transient Database *database_;
6295 RefreshBar *refreshbar_;
6299 // XXX: ok, "updatedelegate_"?...
6300 _transient NSObject<CydiaDelegate> *updatedelegate_;
6303 UIViewController *remembered_;
6304 _transient UIViewController *transient_;
6307 - (NSArray *) navigationURLCollection;
6308 - (void) dropBar:(BOOL)animated;
6309 - (void) beginUpdate;
6310 - (void) raiseBar:(BOOL)animated;
6315 @implementation CYTabBarController
6317 - (void) setUnselectedViewController:(UIViewController *)transient {
6318 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6319 if (transient != nil) {
6320 if (transient_ == nil)
6321 remembered_ = [[controllers objectAtIndex:0] retain];
6322 transient_ = transient;
6323 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6324 [controllers replaceObjectAtIndex:0 withObject:transient_];
6325 [self setSelectedIndex:0];
6326 [self setViewControllers:controllers];
6327 [self concealTabBarSelection];
6328 } else if (remembered_ != nil) {
6329 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6330 transient_ = transient;
6331 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6332 [remembered_ release];
6334 [self setViewControllers:controllers];
6335 [self revealTabBarSelection];
6339 - (UIViewController *) unselectedViewController {
6343 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6344 if ([self unselectedViewController])
6345 [self setUnselectedViewController:nil];
6348 - (NSArray *) navigationURLCollection {
6349 NSMutableArray *items([NSMutableArray array]);
6351 // XXX: Should this deal with transient view controllers?
6352 for (id navigation in [self viewControllers]) {
6353 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6355 [items addObject:stack];
6361 - (void) reloadData {
6362 for (CYViewController *controller in [self viewControllers])
6363 [controller reloadData];
6365 [(CYNavigationController *)[self unselectedViewController] reloadData];
6369 [refreshbar_ release];
6370 [[NSNotificationCenter defaultCenter] removeObserver:self];
6375 - (id) initWithDatabase:(Database *)database {
6376 if ((self = [super init]) != nil) {
6377 database_ = database;
6378 [self setDelegate:self];
6380 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6381 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6383 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6387 - (void) setUpdate:(NSDate *)date {
6391 - (void) beginUpdate {
6392 [refreshbar_ start];
6395 [updatedelegate_ retainNetworkActivityIndicator];
6399 detachNewThreadSelector:@selector(performUpdate)
6405 - (void) performUpdate { _pooled
6407 status.setDelegate(self);
6408 [database_ updateWithStatus:status];
6411 performSelectorOnMainThread:@selector(completeUpdate)
6417 - (void) stopUpdateWithSelector:(SEL)selector {
6419 [updatedelegate_ releaseNetworkActivityIndicator];
6421 [self raiseBar:YES];
6424 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6427 - (void) completeUpdate {
6430 [self stopUpdateWithSelector:@selector(reloadData)];
6433 - (void) cancelUpdate {
6434 [self stopUpdateWithSelector:@selector(updateData)];
6437 - (void) cancelPressed {
6438 [self cancelUpdate];
6445 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6446 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6449 - (void) startProgress {
6452 - (void) setProgressTitle:(NSString *)title {
6454 performSelectorOnMainThread:@selector(_setProgressTitle:)
6460 - (bool) isCancelling:(size_t)received {
6464 - (void) setProgressPercent:(float)percent {
6466 performSelectorOnMainThread:@selector(_setProgressPercent:)
6467 withObject:[NSNumber numberWithFloat:percent]
6472 - (void) addProgressOutput:(NSString *)output {
6474 performSelectorOnMainThread:@selector(_addProgressOutput:)
6480 - (void) _setProgressTitle:(NSString *)title {
6481 [refreshbar_ setPrompt:title];
6484 - (void) _setProgressPercent:(NSNumber *)percent {
6485 [refreshbar_ setProgress:[percent floatValue]];
6488 - (void) _addProgressOutput:(NSString *)output {
6491 - (void) setUpdateDelegate:(id)delegate {
6492 updatedelegate_ = delegate;
6495 - (CGFloat) statusBarHeight {
6496 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6497 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6499 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6503 - (UIView *) transitionView {
6504 if ([self respondsToSelector:@selector(_transitionView)])
6505 return [self _transitionView];
6507 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6510 - (void) dropBar:(BOOL)animated {
6515 UIView *transition([self transitionView]);
6516 [[self view] addSubview:refreshbar_];
6518 CGRect barframe([refreshbar_ frame]);
6520 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6521 barframe.origin.y = [self statusBarHeight];
6523 barframe.origin.y = 0;
6525 [refreshbar_ setFrame:barframe];
6528 [UIView beginAnimations:nil context:NULL];
6530 CGRect viewframe = [transition frame];
6531 viewframe.origin.y += barframe.size.height;
6532 viewframe.size.height -= barframe.size.height;
6533 [transition setFrame:viewframe];
6536 [UIView commitAnimations];
6538 // Ensure bar has the proper width for our view, it might have changed
6539 barframe.size.width = viewframe.size.width;
6540 [refreshbar_ setFrame:barframe];
6542 // XXX: fix Apple's layout bug
6543 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6546 - (void) raiseBar:(BOOL)animated {
6551 UIView *transition([self transitionView]);
6552 [refreshbar_ removeFromSuperview];
6554 CGRect barframe([refreshbar_ frame]);
6557 [UIView beginAnimations:nil context:NULL];
6559 CGRect viewframe = [transition frame];
6560 viewframe.origin.y -= barframe.size.height;
6561 viewframe.size.height += barframe.size.height;
6562 [transition setFrame:viewframe];
6565 [UIView commitAnimations];
6567 // XXX: fix Apple's layout bug
6568 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6572 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6573 // XXX: fix Apple's layout bug
6574 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6578 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6579 bool dropped(dropped_);
6584 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6589 // XXX: fix Apple's layout bug
6590 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6593 - (void) statusBarFrameChanged:(NSNotification *)notification {
6602 /* Cydia Navigation Controller {{{ */
6603 @interface CYNavigationController : UINavigationController {
6604 _transient Database *database_;
6605 _transient id<UINavigationControllerDelegate> delegate_;
6608 - (NSArray *) navigationURLCollection;
6609 - (id) initWithDatabase:(Database *)database;
6610 - (void) reloadData;
6615 @implementation CYNavigationController
6617 - (NSArray *) navigationURLCollection {
6618 NSMutableArray *stack([NSMutableArray array]);
6620 for (CYViewController *controller in [self viewControllers]) {
6621 NSString *url = [[controller navigationURL] absoluteString];
6623 [stack addObject:url];
6629 - (void) reloadData {
6630 for (CYViewController *page in [self viewControllers]) {
6631 // Only reload controllers that have already loaded.
6632 // This prevents a page from accidentally loading too
6633 // early if it hasn't been shown on the screen yet.
6634 if ([page hasLoaded])
6639 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6640 delegate_ = delegate;
6643 - (id) initWithDatabase:(Database *)database {
6644 if ((self = [super init]) != nil) {
6645 database_ = database;
6652 /* Cydia:// Protocol {{{ */
6653 @interface CydiaURLProtocol : NSURLProtocol {
6658 @implementation CydiaURLProtocol
6660 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6661 NSURL *url([request URL]);
6664 NSString *scheme([[url scheme] lowercaseString]);
6665 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6670 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6674 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6675 id<NSURLProtocolClient> client([self client]);
6677 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6679 NSData *data(UIImagePNGRepresentation(icon));
6681 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6682 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6683 [client URLProtocol:self didLoadData:data];
6684 [client URLProtocolDidFinishLoading:self];
6688 - (void) startLoading {
6689 id<NSURLProtocolClient> client([self client]);
6690 NSURLRequest *request([self request]);
6692 NSURL *url([request URL]);
6693 NSString *href([url absoluteString]);
6695 NSString *path([href substringFromIndex:8]);
6696 NSRange slash([path rangeOfString:@"/"]);
6699 if (slash.location == NSNotFound) {
6703 command = [path substringToIndex:slash.location];
6704 path = [path substringFromIndex:(slash.location + 1)];
6707 Database *database([Database sharedInstance]);
6709 if ([command isEqualToString:@"package-icon"]) {
6712 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6713 Package *package([database packageWithName:path]);
6716 UIImage *icon([package icon]);
6717 [self _returnPNGWithImage:icon forRequest:request];
6718 } else if ([command isEqualToString:@"source-icon"]) {
6721 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6722 NSString *source(Simplify(path));
6723 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6725 icon = [UIImage applicationImageNamed:@"unknown.png"];
6726 [self _returnPNGWithImage:icon forRequest:request];
6727 } else if ([command isEqualToString:@"uikit-image"]) {
6730 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6731 UIImage *icon(_UIImageWithName(path));
6732 [self _returnPNGWithImage:icon forRequest:request];
6733 } else if ([command isEqualToString:@"section-icon"]) {
6736 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6737 NSString *section(Simplify(path));
6738 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6740 icon = [UIImage applicationImageNamed:@"unknown.png"];
6741 [self _returnPNGWithImage:icon forRequest:request];
6743 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6747 - (void) stopLoading {
6753 /* Section Controller {{{ */
6754 @interface SectionController : FilteredPackageListController {
6758 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6762 @implementation SectionController
6764 - (NSURL *) navigationURL {
6765 NSString *name = section_;
6769 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6772 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6775 title = UCLocalize("ALL_PACKAGES");
6776 else if (![name isEqual:@""])
6777 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6779 title = UCLocalize("NO_SECTION");
6781 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6788 /* Sections Controller {{{ */
6789 @interface SectionsController : CYViewController <
6790 UITableViewDataSource,
6793 _transient Database *database_;
6794 NSMutableArray *sections_;
6795 NSMutableArray *filtered_;
6800 - (id) initWithDatabase:(Database *)database;
6801 - (void) editButtonClicked;
6805 @implementation SectionsController
6808 [self releaseSubviews];
6809 [sections_ release];
6810 [filtered_ release];
6815 - (NSURL *) navigationURL {
6816 return [NSURL URLWithString:@"cydia://sections"];
6819 - (void) updateNavigationItem {
6820 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6821 if ([sections_ count] == 0) {
6822 [[self navigationItem] setRightBarButtonItem:nil];
6824 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6825 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6827 action:@selector(editButtonClicked)
6828 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6832 - (BOOL) isEditing {
6836 - (void) setEditing:(BOOL)editing {
6837 if ((editing_ = editing))
6840 [delegate_ updateData];
6842 [self updateNavigationItem];
6845 - (void) viewDidAppear:(BOOL)animated {
6846 [super viewDidAppear:animated];
6847 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6850 - (void) viewWillDisappear:(BOOL)animated {
6851 [super viewWillDisappear:animated];
6852 if (editing_) [self setEditing:NO];
6855 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6856 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6860 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6861 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6864 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6868 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6869 static NSString *reuseIdentifier = @"SectionCell";
6871 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6873 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6875 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6880 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6884 Section *section = [self sectionAtIndexPath:indexPath];
6886 SectionController *controller = [[[SectionController alloc]
6887 initWithDatabase:database_
6888 section:[section name]
6890 [controller setDelegate:delegate_];
6892 [[self navigationController] pushViewController:controller animated:YES];
6896 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6898 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6899 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6900 [list_ setRowHeight:45.0f];
6901 [list_ setDataSource:self];
6902 [list_ setDelegate:self];
6903 [[self view] addSubview:list_];
6906 - (void) viewDidLoad {
6907 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6910 - (void) releaseSubviews {
6915 - (id) initWithDatabase:(Database *)database {
6916 if ((self = [super init]) != nil) {
6917 database_ = database;
6919 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6920 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6924 - (void) reloadData {
6927 NSArray *packages = [database_ packages];
6929 [sections_ removeAllObjects];
6930 [filtered_ removeAllObjects];
6932 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6935 for (Package *package in packages) {
6936 NSString *name([package section]);
6937 NSString *key(name == nil ? @"" : name);
6941 _profile(SectionsView$reloadData$Section)
6942 section = [sections objectForKey:key];
6943 if (section == nil) {
6944 _profile(SectionsView$reloadData$Section$Allocate)
6945 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
6946 [sections setObject:section forKey:key];
6951 [section addToCount];
6953 _profile(SectionsView$reloadData$Filter)
6954 if (![package valid] || ![package visible])
6962 [sections_ addObjectsFromArray:[sections allValues]];
6964 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6966 for (Section *section in sections_) {
6967 size_t count([section row]);
6971 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6972 [section setCount:count];
6973 [filtered_ addObject:section];
6976 [self updateNavigationItem];
6981 - (void)editButtonClicked {
6982 [self setEditing:!editing_];
6988 /* Changes Controller {{{ */
6989 @interface ChangesController : CYViewController <
6990 UITableViewDataSource,
6993 _transient Database *database_;
6995 CFMutableArrayRef packages_;
6996 NSMutableArray *sections_;
6999 BOOL hasSentFirstLoad_;
7002 - (id) initWithDatabase:(Database *)database;
7006 @implementation ChangesController
7009 [self releaseSubviews];
7010 CFRelease(packages_);
7011 [sections_ release];
7016 - (NSURL *) navigationURL {
7017 return [NSURL URLWithString:@"cydia://changes"];
7020 - (void) viewWillAppear:(BOOL)animated {
7021 // Loads after it appears, so don't load beforehand.
7023 [super viewWillAppear:animated];
7026 - (void) viewDidAppear:(BOOL)animated {
7027 [super viewDidAppear:animated];
7029 if (!hasSentFirstLoad_) {
7030 hasSentFirstLoad_ = YES;
7031 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7033 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7037 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7038 NSInteger count([sections_ count]);
7039 return count == 0 ? 1 : count;
7042 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7043 if ([sections_ count] == 0)
7045 return [[sections_ objectAtIndex:section] name];
7048 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7049 if ([sections_ count] == 0)
7051 return [[sections_ objectAtIndex:section] count];
7054 - (Package *) packageAtIndex:(NSUInteger)index {
7055 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7058 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7059 @synchronized (database_) {
7060 if ([database_ era] != era_)
7063 NSUInteger sectionIndex([path section]);
7064 if (sectionIndex >= [sections_ count])
7066 Section *section([sections_ objectAtIndex:sectionIndex]);
7067 NSInteger row([path row]);
7068 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7071 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7072 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7074 cell = [[[PackageCell alloc] init] autorelease];
7075 [cell setPackage:[self packageAtIndexPath:path]];
7079 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7080 Package *package([self packageAtIndexPath:path]);
7081 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7082 [view setDelegate:delegate_];
7083 [[self navigationController] pushViewController:view animated:YES];
7087 - (void) refreshButtonClicked {
7088 [delegate_ beginUpdate];
7089 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7092 - (void) upgradeButtonClicked {
7093 [delegate_ distUpgrade];
7097 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7099 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7100 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7101 [list_ setRowHeight:73];
7102 [list_ setDataSource:self];
7103 [list_ setDelegate:self];
7104 [[self view] addSubview:list_];
7107 - (void) viewDidLoad {
7108 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7111 - (void) releaseSubviews {
7116 - (id) initWithDatabase:(Database *)database {
7117 if ((self = [super init]) != nil) {
7118 database_ = database;
7120 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7121 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7125 - (void) _reloadPackages:(NSArray *)packages {
7126 CFRelease(packages_);
7127 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7130 _profile(ChangesController$_reloadPackages$Filter)
7131 for (Package *package in packages)
7132 if ([package upgradableAndEssential:YES] || [package visible])
7133 CFArrayAppendValue(packages_, package);
7136 _profile(ChangesController$_reloadPackages$radixSort)
7137 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7142 - (void) reloadData {
7143 @synchronized (database_) {
7144 era_ = [database_ era];
7145 NSArray *packages = [database_ packages];
7147 [sections_ removeAllObjects];
7150 UIProgressHUD *hud([delegate_ addProgressHUD]);
7151 [hud setText:UCLocalize("LOADING")];
7152 //NSLog(@"HUD:%@::%@", delegate_, hud);
7153 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7154 [delegate_ removeProgressHUD:hud];
7156 [self _reloadPackages:packages];
7159 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7160 Section *ignored = nil;
7161 Section *section = nil;
7165 bool unseens = false;
7167 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7169 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7170 Package *package = [self packageAtIndex:offset];
7172 BOOL uae = [package upgradableAndEssential:YES];
7176 time_t seen([package seen]);
7178 if (section == nil || last != seen) {
7182 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7185 _profile(ChangesController$reloadData$Allocate)
7186 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7187 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7188 [sections_ addObject:section];
7192 [section addToCount];
7193 } else if ([package ignored]) {
7194 if (ignored == nil) {
7195 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7197 [ignored addToCount];
7200 [upgradable addToCount];
7205 CFRelease(formatter);
7208 Section *last = [sections_ lastObject];
7209 size_t count = [last count];
7210 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7211 [sections_ removeLastObject];
7214 if ([ignored count] != 0)
7215 [sections_ insertObject:ignored atIndex:0];
7217 [sections_ insertObject:upgradable atIndex:0];
7222 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7223 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7224 style:UIBarButtonItemStylePlain
7226 action:@selector(upgradeButtonClicked)
7229 if (![delegate_ updating])
7230 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7231 initWithTitle:UCLocalize("REFRESH")
7232 style:UIBarButtonItemStylePlain
7234 action:@selector(refreshButtonClicked)
7242 /* Search Controller {{{ */
7243 @interface SearchController : FilteredPackageListController <
7246 UISearchBar *search_;
7250 - (id) initWithDatabase:(Database *)database;
7251 - (void) setSearchTerm:(NSString *)term;
7252 - (void) reloadData;
7256 @implementation SearchController
7263 - (NSURL *) navigationURL {
7264 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7265 return [NSURL URLWithString:@"cydia://search"];
7267 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7270 - (void) setSearchTerm:(NSString *)searchTerm {
7271 [search_ setText:searchTerm];
7275 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7276 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7277 [search_ resignFirstResponder];
7281 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7282 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7286 - (id) initWithDatabase:(Database *)database {
7287 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7288 search_ = [[UISearchBar alloc] init];
7292 - (void)viewDidAppear:(BOOL)animated {
7293 [super viewDidAppear:animated];
7295 if (!searchloaded_) {
7296 searchloaded_ = YES;
7297 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7298 [search_ layoutSubviews];
7299 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7301 UITextField *textField;
7302 if ([search_ respondsToSelector:@selector(searchField)])
7303 textField = [search_ searchField];
7305 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7307 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7308 [search_ setDelegate:self];
7309 [textField setEnablesReturnKeyAutomatically:NO];
7310 [[self navigationItem] setTitleView:textField];
7314 - (void) reloadData {
7315 [self setObject:[search_ text]];
7320 - (void) didSelectPackage:(Package *)package {
7321 [search_ resignFirstResponder];
7322 [super didSelectPackage:package];
7327 /* Package Settings Controller {{{ */
7328 @interface PackageSettingsController : CYViewController <
7329 UITableViewDataSource,
7332 _transient Database *database_;
7335 UITableView *table_;
7336 UISwitch *subscribedSwitch_;
7337 UISwitch *ignoredSwitch_;
7338 UITableViewCell *subscribedCell_;
7339 UITableViewCell *ignoredCell_;
7342 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7346 @implementation PackageSettingsController
7349 [self releaseSubviews];
7356 - (NSURL *) navigationURL {
7357 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7360 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7361 if (package_ == nil)
7367 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7368 if (package_ == nil)
7374 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7375 return UCLocalize("CHANGE_PACKAGE_SETTINGS");
7378 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7379 return UCLocalize("SHOW_ALL_CHANGES_EX");
7382 - (void) onSubscribed:(id)control {
7383 bool value([control isOn]);
7384 if (package_ == nil)
7386 if ([package_ setSubscribed:value])
7387 [delegate_ updateData];
7390 - (void) onIgnored:(id)control {
7391 // TODO: set Held state - possibly call out to dpkg, etc.
7394 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7395 if (package_ == nil)
7398 switch ([indexPath row]) {
7399 case 0: return subscribedCell_;
7400 case 1: return ignoredCell_;
7409 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7411 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7412 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7413 [table_ setDataSource:self];
7414 [table_ setDelegate:self];
7415 [[self view] addSubview:table_];
7417 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7418 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7419 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7421 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7422 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7423 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7424 // Disable this switch, since it only reflects (not modifies) the ignored state.
7425 [ignoredSwitch_ setUserInteractionEnabled:NO];
7427 subscribedCell_ = [[UITableViewCell alloc] init];
7428 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7429 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7430 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7432 ignoredCell_ = [[UITableViewCell alloc] init];
7433 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7434 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7435 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7436 // FIXME: Ignored state is not saved.
7437 [ignoredCell_ setUserInteractionEnabled:NO];
7440 - (void) viewDidLoad {
7441 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7444 - (void) releaseSubviews {
7445 [ignoredCell_ release];
7448 [subscribedCell_ release];
7449 subscribedCell_ = nil;
7454 [ignoredSwitch_ release];
7455 ignoredSwitch_ = nil;
7457 [subscribedSwitch_ release];
7458 subscribedSwitch_ = nil;
7461 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7462 if ((self = [super init])) {
7463 database_ = database;
7464 name_ = [package retain];
7468 - (void) reloadData {
7471 if (package_ != nil)
7472 [package_ autorelease];
7473 package_ = [database_ packageWithName:name_];
7474 if (package_ != nil) {
7476 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7477 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7480 [table_ reloadData];
7486 /* Installed Controller {{{ */
7487 @interface InstalledController : FilteredPackageListController {
7491 - (id) initWithDatabase:(Database *)database;
7493 - (void) updateRoleButton;
7494 - (void) queueStatusDidChange;
7498 @implementation InstalledController
7504 - (NSURL *) navigationURL {
7505 return [NSURL URLWithString:@"cydia://installed"];
7508 - (id) initWithDatabase:(Database *)database {
7509 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7510 [self updateRoleButton];
7511 [self queueStatusDidChange];
7516 - (void) queueButtonClicked {
7521 - (void) queueStatusDidChange {
7525 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7526 initWithTitle:UCLocalize("QUEUE")
7527 style:UIBarButtonItemStyleDone
7529 action:@selector(queueButtonClicked)
7532 [[self navigationItem] setLeftBarButtonItem:nil];
7538 - (void) updateRoleButton {
7539 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7540 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7541 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7542 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7544 action:@selector(roleButtonClicked)
7548 - (void) roleButtonClicked {
7549 [self setObject:[NSNumber numberWithBool:expert_]];
7553 [self updateRoleButton];
7559 /* Source Cell {{{ */
7560 @interface SourceCell : CYTableViewCell <
7568 - (void) setSource:(Source *)source;
7572 @implementation SourceCell
7574 - (void) clearSource {
7584 - (void) setSource:(Source *)source {
7588 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7590 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7591 icon_ = [icon_ retain];
7593 origin_ = [[source name] retain];
7594 label_ = [[source uri] retain];
7596 [content_ setNeedsDisplay];
7604 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7605 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7606 UIView *content([self contentView]);
7607 CGRect bounds([content bounds]);
7609 content_ = [[ContentView alloc] initWithFrame:bounds];
7610 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7611 [content_ setBackgroundColor:[UIColor whiteColor]];
7612 [content addSubview:content_];
7614 [content_ setDelegate:self];
7615 [content_ setOpaque:YES];
7619 - (NSString *) accessibilityLabel {
7623 - (void) drawContentRect:(CGRect)rect {
7624 bool highlighted(highlighted_);
7625 float width(rect.size.width);
7628 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7635 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7639 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7644 /* Source Controller {{{ */
7645 @interface SourceController : FilteredPackageListController {
7646 _transient Source *source_;
7650 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7654 @implementation SourceController
7656 - (NSURL *) navigationURL {
7657 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7660 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7662 key_ = [[source key] retain];
7664 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7668 - (void) reloadData {
7669 NSArray *sources = [database_ sources];
7670 for (Source *source in sources) {
7671 if ([[source key] isEqual:key_]) {
7674 key_ = [[source key] retain];
7679 [self setObject:source_];
7686 /* Sources Controller {{{ */
7687 @interface SourcesController : CYViewController <
7688 UITableViewDataSource,
7691 _transient Database *database_;
7693 NSMutableArray *sources_;
7697 UIProgressHUD *hud_;
7700 //NSURLConnection *installer_;
7701 NSURLConnection *trivial_;
7702 NSURLConnection *trivial_bz2_;
7703 NSURLConnection *trivial_gz_;
7704 //NSURLConnection *automatic_;
7709 - (id) initWithDatabase:(Database *)database;
7710 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7714 @implementation SourcesController
7716 - (void) _releaseConnection:(NSURLConnection *)connection {
7717 if (connection != nil) {
7718 [connection cancel];
7719 //[connection setDelegate:nil];
7720 [connection release];
7725 [self releaseSubviews];
7731 //[self _releaseConnection:installer_];
7732 [self _releaseConnection:trivial_];
7733 [self _releaseConnection:trivial_gz_];
7734 [self _releaseConnection:trivial_bz2_];
7735 //[self _releaseConnection:automatic_];
7741 - (NSURL *) navigationURL {
7742 return [NSURL URLWithString:@"cydia://sources"];
7745 - (void) viewDidAppear:(BOOL)animated {
7746 [super viewDidAppear:animated];
7747 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7750 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7751 return offset_ == 0 ? 1 : 2;
7754 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7755 switch (section + (offset_ == 0 ? 1 : 0)) {
7756 case 0: return UCLocalize("ENTERED_BY_USER");
7757 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7763 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7764 int count = [sources_ count];
7766 case 0: return (offset_ == 0 ? count : offset_);
7767 case 1: return count - offset_;
7773 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7775 switch (indexPath.section) {
7776 case 0: idx = indexPath.row; break;
7777 case 1: idx = indexPath.row + offset_; break;
7781 return [sources_ objectAtIndex:idx];
7784 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7785 static NSString *cellIdentifier = @"SourceCell";
7787 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7788 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7789 [cell setSource:[self sourceAtIndexPath:indexPath]];
7790 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7795 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7796 Source *source = [self sourceAtIndexPath:indexPath];
7798 SourceController *controller = [[[SourceController alloc]
7799 initWithDatabase:database_
7803 [controller setDelegate:delegate_];
7805 [[self navigationController] pushViewController:controller animated:YES];
7808 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7809 Source *source = [self sourceAtIndexPath:indexPath];
7810 return [source record] != nil;
7813 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7814 Source *source = [self sourceAtIndexPath:indexPath];
7815 [Sources_ removeObjectForKey:[source key]];
7816 [delegate_ syncData];
7820 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
7823 @"./", @"Distribution",
7824 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
7826 [delegate_ syncData];
7829 - (NSString *) getWarning {
7830 NSString *href(href_);
7831 NSRange colon([href rangeOfString:@"://"]);
7832 if (colon.location != NSNotFound)
7833 href = [href substringFromIndex:(colon.location + 3)];
7834 href = [href stringByAddingPercentEscapes];
7835 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7836 href = [href stringByCachingURLWithCurrentCDN];
7838 NSURL *url([NSURL URLWithString:href]);
7840 NSStringEncoding encoding;
7841 NSError *error(nil);
7843 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7844 return [warning length] == 0 ? nil : warning;
7848 - (void) _endConnection:(NSURLConnection *)connection {
7849 // XXX: the memory management in this method is horribly awkward
7851 NSURLConnection **field = NULL;
7852 if (connection == trivial_)
7854 else if (connection == trivial_bz2_)
7855 field = &trivial_bz2_;
7856 else if (connection == trivial_gz_)
7857 field = &trivial_gz_;
7858 _assert(field != NULL);
7859 [connection release];
7864 trivial_bz2_ == nil &&
7870 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7873 UIAlertView *alert = [[[UIAlertView alloc]
7874 initWithTitle:UCLocalize("SOURCE_WARNING")
7877 cancelButtonTitle:UCLocalize("CANCEL")
7879 UCLocalize("ADD_ANYWAY"),
7883 [alert setContext:@"warning"];
7884 [alert setNumberOfRows:1];
7888 } else if (error_ != nil) {
7889 UIAlertView *alert = [[[UIAlertView alloc]
7890 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7891 message:[error_ localizedDescription]
7893 cancelButtonTitle:UCLocalize("OK")
7894 otherButtonTitles:nil
7897 [alert setContext:@"urlerror"];
7900 UIAlertView *alert = [[[UIAlertView alloc]
7901 initWithTitle:UCLocalize("NOT_REPOSITORY")
7902 message:UCLocalize("NOT_REPOSITORY_EX")
7904 cancelButtonTitle:UCLocalize("OK")
7905 otherButtonTitles:nil
7908 [alert setContext:@"trivial"];
7912 [delegate_ setStatusBarShowsProgress:NO];
7913 [delegate_ removeProgressHUD:hud_];
7923 if (error_ != nil) {
7930 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
7931 switch ([response statusCode]) {
7937 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
7938 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7940 error_ = [error retain];
7941 [self _endConnection:connection];
7944 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
7945 [self _endConnection:connection];
7948 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
7949 NSMutableURLRequest *request = [NSMutableURLRequest
7950 requestWithURL:[NSURL URLWithString:href]
7951 cachePolicy:NSURLRequestUseProtocolCachePolicy
7952 timeoutInterval:120.0
7955 [request setHTTPMethod:method];
7957 if (Machine_ != NULL)
7958 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
7959 if (UniqueID_ != nil)
7960 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
7962 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
7964 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
7967 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7968 NSString *context([alert context]);
7970 if ([context isEqualToString:@"source"]) {
7973 NSString *href = [[alert textField] text];
7975 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
7977 if (![href hasSuffix:@"/"])
7978 href_ = [href stringByAppendingString:@"/"];
7981 href_ = [href_ retain];
7983 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
7984 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
7985 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
7986 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
7990 // XXX: this is stupid
7991 hud_ = [[delegate_ addProgressHUD] retain];
7992 [hud_ setText:UCLocalize("VERIFYING_URL")];
8001 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8002 } else if ([context isEqualToString:@"trivial"])
8003 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8004 else if ([context isEqualToString:@"urlerror"])
8005 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8006 else if ([context isEqualToString:@"warning"]) {
8021 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8026 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8028 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8029 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8030 [list_ setRowHeight:56];
8031 [list_ setDataSource:self];
8032 [list_ setDelegate:self];
8033 [[self view] addSubview:list_];
8036 - (void) viewDidLoad {
8037 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8038 [self updateButtonsForEditingStatus:NO animated:NO];
8041 - (void) releaseSubviews {
8046 - (id) initWithDatabase:(Database *)database {
8047 if ((self = [super init]) != nil) {
8048 database_ = database;
8049 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8053 - (void) reloadData {
8057 if (!list.ReadMainList())
8060 [sources_ removeAllObjects];
8061 [sources_ addObjectsFromArray:[database_ sources]];
8063 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8066 int count([sources_ count]);
8068 for (int i = 0; i != count; i++) {
8069 if ([[sources_ objectAtIndex:i] record] == nil)
8074 [list_ setEditing:NO];
8075 [self updateButtonsForEditingStatus:NO animated:NO];
8079 - (void) showAddSourcePrompt {
8080 UIAlertView *alert = [[[UIAlertView alloc]
8081 initWithTitle:UCLocalize("ENTER_APT_URL")
8084 cancelButtonTitle:UCLocalize("CANCEL")
8086 UCLocalize("ADD_SOURCE"),
8090 [alert setContext:@"source"];
8091 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8093 [alert setNumberOfRows:1];
8094 [alert addTextFieldWithValue:@"http://" label:@""];
8096 UITextInputTraits *traits = [[alert textField] textInputTraits];
8097 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8098 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8099 [traits setKeyboardType:UIKeyboardTypeURL];
8100 // XXX: UIReturnKeyDone
8101 [traits setReturnKeyType:UIReturnKeyNext];
8106 - (void) addButtonClicked {
8107 [self showAddSourcePrompt];
8110 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8111 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8112 initWithTitle:UCLocalize("ADD")
8113 style:UIBarButtonItemStylePlain
8115 action:@selector(addButtonClicked)
8116 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8118 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8119 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8120 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8122 action:@selector(editButtonClicked)
8123 ] autorelease] animated:animated];
8125 if (IsWildcat_ && !editing)
8126 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8127 initWithTitle:UCLocalize("SETTINGS")
8128 style:UIBarButtonItemStylePlain
8130 action:@selector(settingsButtonClicked)
8134 - (void) settingsButtonClicked {
8135 [delegate_ showSettings];
8138 - (void) editButtonClicked {
8139 [list_ setEditing:![list_ isEditing] animated:YES];
8141 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8147 /* Settings Controller {{{ */
8148 @interface SettingsController : CYViewController <
8149 UITableViewDataSource,
8152 _transient Database *database_;
8153 // XXX: ok, "roledelegate_"?...
8154 _transient id roledelegate_;
8155 UITableView *table_;
8156 UISegmentedControl *segment_;
8160 - (void) showDoneButton;
8161 - (void) resizeSegmentedControl;
8165 @implementation SettingsController
8168 [self releaseSubviews];
8174 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8176 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8177 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8178 [table_ setDelegate:self];
8179 [table_ setDataSource:self];
8180 [[self view] addSubview:table_];
8182 NSArray *items = [NSArray arrayWithObjects:
8184 UCLocalize("HACKER"),
8185 UCLocalize("DEVELOPER"),
8187 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8188 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8189 [container_ addSubview:segment_];
8192 - (void) viewDidLoad {
8193 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8196 if ([Role_ isEqualToString:@"User"]) index = 0;
8197 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8198 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8200 [segment_ setSelectedSegmentIndex:index];
8201 [self showDoneButton];
8204 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8205 [self resizeSegmentedControl];
8208 - (void) releaseSubviews {
8215 [container_ release];
8219 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8220 if ((self = [super init])) {
8221 database_ = database;
8222 roledelegate_ = delegate;
8226 - (void) resizeSegmentedControl {
8227 CGFloat width = [[self view] frame].size.width;
8228 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8231 - (void) viewWillAppear:(BOOL)animated {
8232 [super viewWillAppear:animated];
8234 [self resizeSegmentedControl];
8237 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8238 [self resizeSegmentedControl];
8241 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8242 [self resizeSegmentedControl];
8246 NSString *role(nil);
8248 switch ([segment_ selectedSegmentIndex]) {
8249 case 0: role = @"User"; break;
8250 case 1: role = @"Hacker"; break;
8251 case 2: role = @"Developer"; break;
8256 if (![role isEqualToString:Role_]) {
8257 bool rolling(Role_ == nil);
8260 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8264 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8268 [roledelegate_ loadData];
8270 [roledelegate_ updateData];
8274 - (void) segmentChanged:(UISegmentedControl *)control {
8275 [self showDoneButton];
8278 - (void) saveAndClose {
8281 [[self navigationItem] setRightBarButtonItem:nil];
8282 [[self navigationController] dismissModalViewControllerAnimated:YES];
8285 - (void) doneButtonClicked {
8286 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8287 [spinner startAnimating];
8288 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8289 [[self navigationItem] setRightBarButtonItem:spinItem];
8291 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8294 - (void) showDoneButton {
8295 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8296 initWithTitle:UCLocalize("DONE")
8297 style:UIBarButtonItemStyleDone
8299 action:@selector(doneButtonClicked)
8300 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8303 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8304 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8308 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8312 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8313 return nil; // This method is required by the protocol.
8316 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8318 return UCLocalize("ROLE_EX");
8320 return [NSString stringWithFormat:
8321 @"%@: %@\n%@: %@\n%@: %@",
8322 UCLocalize("USER"), UCLocalize("USER_EX"),
8323 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8324 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8329 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8330 return section == 3 ? 44.0f : 0;
8333 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8334 return section == 3 ? container_ : nil;
8337 - (void) reloadData {
8339 [table_ reloadData];
8344 /* Stash Controller {{{ */
8345 @interface StashController : CYViewController {
8346 UIActivityIndicatorView *spinner_;
8352 @implementation StashController
8355 [self releaseSubviews];
8361 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8362 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8364 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8365 CGRect spinrect = [spinner_ frame];
8366 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8367 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8368 [spinner_ setFrame:spinrect];
8369 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8370 [[self view] addSubview:spinner_];
8371 [spinner_ startAnimating];
8374 captrect.size.width = [[self view] frame].size.width;
8375 captrect.size.height = 40.0f;
8376 captrect.origin.x = 0;
8377 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8378 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8379 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8380 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8381 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8382 [caption_ setTextColor:[UIColor whiteColor]];
8383 [caption_ setBackgroundColor:[UIColor clearColor]];
8384 [caption_ setShadowColor:[UIColor blackColor]];
8385 [caption_ setTextAlignment:UITextAlignmentCenter];
8386 [[self view] addSubview:caption_];
8389 statusrect.size.width = [[self view] frame].size.width;
8390 statusrect.size.height = 30.0f;
8391 statusrect.origin.x = 0;
8392 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8393 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8394 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8395 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8396 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8397 [status_ setTextColor:[UIColor whiteColor]];
8398 [status_ setBackgroundColor:[UIColor clearColor]];
8399 [status_ setShadowColor:[UIColor blackColor]];
8400 [status_ setTextAlignment:UITextAlignmentCenter];
8401 [[self view] addSubview:status_];
8404 - (void) releaseSubviews {
8418 @interface Cydia : UIApplication <
8419 ConfirmationControllerDelegate,
8420 ProgressControllerDelegate,
8422 UINavigationControllerDelegate,
8423 UITabBarControllerDelegate
8425 // XXX: evaluate all fields for _transient
8428 CYTabBarController *tabbar_;
8430 NSMutableArray *essential_;
8431 NSMutableArray *broken_;
8433 Database *database_;
8440 StashController *stash_;
8449 @implementation Cydia
8451 - (void) beginUpdate {
8452 [tabbar_ beginUpdate];
8456 return [tabbar_ updating];
8460 if ([broken_ count] != 0) {
8461 int count = [broken_ count];
8463 UIAlertView *alert = [[[UIAlertView alloc]
8464 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8465 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8467 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8469 UCLocalize("TEMPORARY_IGNORE"),
8473 [alert setContext:@"fixhalf"];
8475 } else if (!Ignored_ && [essential_ count] != 0) {
8476 int count = [essential_ count];
8478 UIAlertView *alert = [[[UIAlertView alloc]
8479 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8480 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8482 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8484 UCLocalize("UPGRADE_ESSENTIAL"),
8485 UCLocalize("COMPLETE_UPGRADE"),
8489 [alert setContext:@"upgrade"];
8494 - (void) _saveConfig {
8500 NSString *error(nil);
8502 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8504 NSError *error(nil);
8505 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8506 NSLog(@"failure to save metadata data: %@", error);
8511 NSLog(@"failure to serialize metadata: %@", error);
8516 // Navigation controller for the queuing badge.
8517 - (CYNavigationController *) queueNavigationController {
8518 NSArray *controllers = [tabbar_ viewControllers];
8519 return [controllers objectAtIndex:3];
8522 - (void) _updateData {
8525 [tabbar_ reloadData];
8527 CYNavigationController *navigation = [self queueNavigationController];
8529 id queuedelegate = nil;
8530 if ([[navigation viewControllers] count] > 0)
8531 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8533 [queuedelegate queueStatusDidChange];
8534 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8537 - (void) _refreshIfPossible {
8538 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8540 bool recently = false;
8541 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8542 if (update != nil) {
8543 NSTimeInterval interval([update timeIntervalSinceNow]);
8544 if (interval <= 0 && interval > -(15*60))
8548 // Don't automatic refresh if:
8549 // - We already refreshed recently.
8550 // - We already auto-refreshed this launch.
8551 // - Auto-refresh is disabled.
8552 if (recently || loaded_ || ManualRefresh) {
8553 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8555 // If we are cancelling, we need to make sure it knows it's already loaded.
8559 // We are going to load, so remember that.
8563 SCNetworkReachabilityFlags flags; {
8564 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8565 SCNetworkReachabilityGetFlags(reachability, &flags);
8566 CFRelease(reachability);
8569 // XXX: this elaborate mess is what Apple is using to determine this? :(
8570 // XXX: do we care if the user has to intervene? maybe that's ok?
8572 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8573 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8574 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8575 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8576 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8577 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8581 // If we can reach the server, auto-refresh!
8583 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8588 - (void) refreshIfPossible {
8589 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8592 - (void) _reloadData {
8593 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8594 [hud setText:UCLocalize("RELOADING_DATA")];
8596 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8599 [self removeProgressHUD:hud];
8603 [essential_ removeAllObjects];
8604 [broken_ removeAllObjects];
8606 NSArray *packages([database_ packages]);
8607 for (Package *package in packages) {
8609 [broken_ addObject:package];
8610 if ([package upgradableAndEssential:NO]) {
8611 if ([package essential])
8612 [essential_ addObject:package];
8617 NSLog(@"changes:#%u", changes);
8619 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8622 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8623 [changesItem setBadgeValue:badge];
8624 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8625 [self setApplicationIconBadgeNumber:changes];
8628 [changesItem setBadgeValue:nil];
8629 [changesItem setAnimatedBadge:NO];
8630 [self setApplicationIconBadgeNumber:0];
8635 [self refreshIfPossible];
8638 - (void) updateData {
8647 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8648 _assert(file != NULL);
8650 for (NSString *key in [Sources_ allKeys]) {
8651 NSDictionary *source([Sources_ objectForKey:key]);
8653 fprintf(file, "%s %s %s\n",
8654 [[source objectForKey:@"Type"] UTF8String],
8655 [[source objectForKey:@"URI"] UTF8String],
8656 [[source objectForKey:@"Distribution"] UTF8String]
8664 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8665 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8667 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8668 [tabbar_ presentModalViewController:navigation animated:YES];
8671 detachNewThreadSelector:@selector(update_)
8674 title:UCLocalize("UPDATING_SOURCES")
8678 - (void) reloadData {
8679 @synchronized (self) {
8685 pkgProblemResolver *resolver = [database_ resolver];
8687 resolver->InstallProtect();
8688 if (!resolver->Resolve(true))
8693 // XXX: this is a really crappy way of doing this.
8694 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8695 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8696 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8697 if ([tabbar_ updating])
8698 [tabbar_ cancelUpdate];
8700 if (![database_ prepare])
8703 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8704 [page setDelegate:self];
8705 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8706 [confirm_ setDelegate:self];
8709 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8710 [tabbar_ presentModalViewController:confirm_ animated:YES];
8716 @synchronized (self) {
8721 - (void) clearPackage:(Package *)package {
8722 @synchronized (self) {
8729 - (void) installPackages:(NSArray *)packages {
8730 @synchronized (self) {
8731 for (Package *package in packages)
8738 - (void) installPackage:(Package *)package {
8739 @synchronized (self) {
8746 - (void) removePackage:(Package *)package {
8747 @synchronized (self) {
8754 - (void) distUpgrade {
8755 @synchronized (self) {
8756 if (![database_ upgrade])
8763 @synchronized (self) {
8768 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8771 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8773 if (navigation != nil) {
8774 [navigation pushViewController:progress animated:YES];
8776 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8778 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8779 [tabbar_ presentModalViewController:navigation animated:YES];
8783 detachNewThreadSelector:@selector(perform)
8786 title:UCLocalize("RUNNING")
8792 - (void) progressControllerIsComplete:(ProgressController *)progress {
8797 - (void) showSettings {
8798 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8799 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8801 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8802 [tabbar_ presentModalViewController:nav animated:YES];
8805 - (void) retainNetworkActivityIndicator {
8806 if (activity_++ == 0)
8807 [self setNetworkActivityIndicatorVisible:YES];
8810 - (void) releaseNetworkActivityIndicator {
8811 if (--activity_ == 0)
8812 [self setNetworkActivityIndicatorVisible:NO];
8815 - (void) cancelAndClear:(bool)clear {
8816 @synchronized (self) {
8828 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8829 NSString *context([alert context]);
8831 if ([context isEqualToString:@"fixhalf"]) {
8832 if (button == [alert cancelButtonIndex]) {
8833 @synchronized (self) {
8834 for (Package *broken in broken_) {
8837 NSString *id = [broken id];
8838 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8839 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8840 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8841 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8847 } else if (button == [alert firstOtherButtonIndex]) {
8848 [broken_ removeAllObjects];
8852 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8853 } else if ([context isEqualToString:@"upgrade"]) {
8854 if (button == [alert firstOtherButtonIndex]) {
8855 @synchronized (self) {
8856 for (Package *essential in essential_)
8857 [essential install];
8862 } else if (button == [alert firstOtherButtonIndex] + 1) {
8864 } else if (button == [alert cancelButtonIndex]) {
8868 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8872 - (void) system:(NSString *)command { _pooled
8874 system([command UTF8String]);
8878 - (void) applicationWillSuspend {
8880 [super applicationWillSuspend];
8883 - (BOOL) isSafeToSuspend {
8884 // Use external process status API internally.
8885 // This is probably a really bad idea.
8886 // XXX: what is the point of this? does this solve anything at all?
8887 uint64_t status = 0;
8889 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8890 notify_get_state(notify_token, &status);
8891 notify_cancel(notify_token);
8894 return locked_ == 0 && status == 0;
8897 - (void) applicationSuspend:(__GSEvent *)event {
8898 if ([self isSafeToSuspend])
8899 [super applicationSuspend:event];
8902 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8903 if ([self isSafeToSuspend])
8904 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8907 - (void) _setSuspended:(BOOL)value {
8908 if ([self isSafeToSuspend])
8909 [super _setSuspended:value];
8912 - (UIProgressHUD *) addProgressHUD {
8913 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8914 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8916 [window_ setUserInteractionEnabled:NO];
8919 UIViewController *target = tabbar_;
8920 while ([target modalViewController] != nil) target = [target modalViewController];
8921 [[target view] addSubview:hud];
8927 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8929 [hud removeFromSuperview];
8930 [window_ setUserInteractionEnabled:YES];
8934 - (CYViewController *) pageForPackage:(NSString *)name {
8935 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
8938 - (CYViewController *) pageForURL:(NSURL *)url {
8939 NSString *scheme([[url scheme] lowercaseString]);
8940 if ([[url absoluteString] length] <= [scheme length] + 3)
8942 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
8943 NSArray *components([path pathComponents]);
8945 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
8946 return [self pageForPackage:[components objectAtIndex:1]];
8948 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
8951 NSString *base([components objectAtIndex:0]);
8953 CYViewController *controller = nil;
8955 if ([base isEqualToString:@"url"]) {
8956 // This kind of URL can contain slashes in the argument, so we can't parse them below.
8957 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
8958 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
8959 } else if ([components count] == 1) {
8960 if ([base isEqualToString:@"manage"]) {
8961 controller = [[[ManageController alloc] init] autorelease];
8964 if ([base isEqualToString:@"sources"]) {
8965 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8968 if ([base isEqualToString:@"home"]) {
8969 controller = [[[HomeController alloc] init] autorelease];
8972 if ([base isEqualToString:@"sections"]) {
8973 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
8976 if ([base isEqualToString:@"search"]) {
8977 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8980 if ([base isEqualToString:@"changes"]) {
8981 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
8984 if ([base isEqualToString:@"installed"]) {
8985 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8987 } else if ([components count] == 2) {
8988 NSString *argument = [components objectAtIndex:1];
8990 if ([base isEqualToString:@"package"]) {
8991 controller = [self pageForPackage:argument];
8994 if ([base isEqualToString:@"search"]) {
8995 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8996 [(SearchController *)controller setSearchTerm:argument];
8999 if ([base isEqualToString:@"sections"]) {
9000 if ([argument isEqualToString:@"all"])
9002 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9005 if ([base isEqualToString:@"sources"]) {
9006 if ([argument isEqualToString:@"add"]) {
9007 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9008 [(SourcesController *)controller showAddSourcePrompt];
9010 NSArray *sources = [database_ sources];
9011 for (Source *source in sources) {
9012 if ([[source key] isEqual:argument]) {
9013 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9020 if ([base isEqualToString:@"launch"]) {
9021 [self launchApplicationWithIdentifier:argument suspended:NO];
9024 } else if ([components count] == 3) {
9025 NSString *arg1 = [components objectAtIndex:1];
9026 NSString *arg2 = [components objectAtIndex:2];
9028 if ([base isEqualToString:@"package"]) {
9029 if ([arg2 isEqualToString:@"settings"]) {
9030 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9031 } else if ([arg2 isEqualToString:@"files"]) {
9032 if (Package *package = [database_ packageWithName:arg1]) {
9033 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9034 [(FileTable *)controller setPackage:package];
9040 [controller setDelegate:self];
9044 - (BOOL) openCydiaURL:(NSURL *)url {
9045 CYViewController *page([self pageForURL:url]);
9048 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9049 [nav setViewControllers:[NSArray arrayWithObject:page]];
9050 [tabbar_ setUnselectedViewController:nav];
9056 - (void) applicationOpenURL:(NSURL *)url {
9057 [super applicationOpenURL:url];
9059 if (!loaded_) starturl_ = [url retain];
9060 else [self openCydiaURL:url];
9063 - (void) applicationWillResignActive:(UIApplication *)application {
9064 // Stop refreshing if you get a phone call or lock the device.
9065 if ([tabbar_ updating])
9066 [tabbar_ cancelUpdate];
9068 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9069 [super applicationWillResignActive:application];
9072 - (void) applicationWillTerminate:(UIApplication *)application {
9074 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9075 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9076 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9081 - (void) addStashController {
9083 stash_ = [[StashController alloc] init];
9084 [window_ addSubview:[stash_ view]];
9087 - (void) removeStashController {
9088 [[stash_ view] removeFromSuperview];
9094 [self setIdleTimerDisabled:YES];
9096 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9097 [self setStatusBarShowsProgress:YES];
9098 UpdateExternalStatus(1);
9100 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9102 UpdateExternalStatus(0);
9103 [self setStatusBarShowsProgress:NO];
9105 [self removeStashController];
9107 if (ExecFork() == 0) {
9108 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9109 perror("launchctl stop");
9113 - (void) setupViewControllers {
9114 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9116 NSMutableArray *items([NSMutableArray arrayWithObjects:
9117 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9118 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9119 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9120 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9124 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9125 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9127 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9130 NSMutableArray *controllers([NSMutableArray array]);
9131 for (UITabBarItem *item in items) {
9132 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9133 [controller setTabBarItem:item];
9134 [controllers addObject:controller];
9136 [tabbar_ setViewControllers:controllers];
9138 [tabbar_ setUpdateDelegate:self];
9141 - (CYEmulatedLoadingController *)showEmulatedLoadingControllerInView:(UIView *)view {
9142 static CYEmulatedLoadingController *fake = nil;
9146 fake = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9147 [view addSubview:[fake view]];
9149 [[fake view] removeFromSuperview];
9157 - (void) applicationDidFinishLaunching:(id)unused {
9161 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9162 [self setApplicationSupportsShakeToEdit:NO];
9164 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9165 initWithMemoryCapacity:524288
9166 diskCapacity:10485760
9167 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9170 [CYBrowserController _initialize];
9172 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9174 Font12_ = [[UIFont systemFontOfSize:12] retain];
9175 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9176 Font14_ = [[UIFont systemFontOfSize:14] retain];
9177 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9178 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9180 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9181 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9183 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9184 [window_ orderFront:self];
9185 [window_ makeKey:self];
9186 [window_ setHidden:NO];
9189 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9190 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9191 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9192 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9193 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9194 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9195 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9196 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9197 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9200 [self addStashController];
9201 // XXX: this would be much cleaner as a yieldToSelector:
9202 // that way the removeStashController could happen right here inline
9203 // we also could no longer require the useless stash_ field anymore
9204 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9208 database_ = [Database sharedInstance];
9210 [window_ setUserInteractionEnabled:NO];
9211 [self setupViewControllers];
9212 [self showEmulatedLoadingControllerInView:window_];
9214 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9221 [window_ setUserInteractionEnabled:YES];
9223 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9224 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9226 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9227 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9231 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9232 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9233 [window_ setUserInteractionEnabled:NO];
9239 [window_ addSubview:[tabbar_ view]];
9240 [self showEmulatedLoadingControllerInView:nil];
9241 [window_ setUserInteractionEnabled:YES];
9243 int selectedIndex = 0;
9244 NSMutableArray *items = nil;
9246 bool recently = false;
9247 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9248 if (closed != nil) {
9249 NSTimeInterval interval([closed timeIntervalSinceNow]);
9250 // XXX: Is 15 minutes the optimal time here?
9251 if (interval <= 0 && interval > -(15*60))
9255 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9256 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9259 for (NSArray *entry in items)
9260 if ([entry count] <= 0)
9263 if (!recently || !items || !enough) {
9265 items = [NSMutableArray array];
9266 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9267 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9268 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9270 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9272 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9273 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9275 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9278 [tabbar_ setSelectedIndex:selectedIndex];
9279 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9280 NSArray *stack = [items objectAtIndex:tab];
9281 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9282 NSMutableArray *current = [NSMutableArray array];
9284 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9285 NSString *addr = [stack objectAtIndex:nav];
9286 NSURL *url = [NSURL URLWithString:addr];
9287 CYViewController *page = [self pageForURL:url];
9289 [current addObject:page];
9292 [navigation setViewControllers:current];
9295 // (Try to) show the startup URL.
9296 if (starturl_ != nil) {
9297 [self openCydiaURL:starturl_];
9298 [starturl_ release];
9303 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9304 if (item != nil && IsWildcat_) {
9305 [sheet showFromBarButtonItem:item animated:YES];
9307 [sheet showInView:window_];
9314 id Alloc_(id self, SEL selector) {
9315 id object = alloc_(self, selector);
9316 lprintf("[%s]A-%p\n", self->isa->name, object);
9321 id Dealloc_(id self, SEL selector) {
9322 id object = dealloc_(self, selector);
9323 lprintf("[%s]D-%p\n", self->isa->name, object);
9327 Class $WebDefaultUIKitDelegate;
9329 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9330 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9331 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9332 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9335 static NSNumber *shouldPlayKeyboardSounds;
9339 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9341 case 1104: // Keyboard Button Clicked
9342 case 1105: // Keyboard Delete Repeated
9343 if (shouldPlayKeyboardSounds == nil) {
9344 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9345 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9348 if (![shouldPlayKeyboardSounds boolValue])
9352 _UIHardware$_playSystemSound$(self, _cmd, sound);
9356 Class $UIApplication;
9358 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9359 static BOOL initialized = NO;
9360 static BOOL started = NO;
9362 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9363 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9365 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9366 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9367 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9368 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9370 if (initialized && !enabled) {
9372 [bundle performSelector:@selector(_accessibilityStopServer)];
9373 } else if (enabled) {
9377 [bundle performSelector:@selector(_accessibilityStartServer)];
9383 int main(int argc, char *argv[]) { _pooled
9386 if (Class $UIDevice = objc_getClass("UIDevice")) {
9387 UIDevice *device([$UIDevice currentDevice]);
9388 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9392 UIScreen *screen([UIScreen mainScreen]);
9393 if ([screen respondsToSelector:@selector(scale)])
9394 ScreenScale_ = [screen scale];
9398 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9399 if (ScreenScale_ > 1)
9400 [parts addObject:@"@2x"];
9401 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9402 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9404 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9406 /* Library Hacks {{{ */
9407 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9409 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9410 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9411 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9412 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9413 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9416 $UIHardware = objc_getClass("UIHardware");
9417 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9418 if (UIHardware$_playSystemSound$ != NULL) {
9419 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9420 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9423 $UIApplication = objc_getClass("UIApplication");
9424 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9425 if (UIApplication$_updateApplicationAccessibility != NULL) {
9426 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9427 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9430 /* Set Locale {{{ */
9431 Locale_ = CFLocaleCopyCurrent();
9432 Languages_ = [NSLocale preferredLanguages];
9433 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9434 //NSLog(@"%@", [Languages_ description]);
9437 if (Languages_ == nil || [Languages_ count] == 0)
9438 // XXX: consider just setting to C and then falling through?
9441 lang = [[Languages_ objectAtIndex:0] UTF8String];
9442 setenv("LANG", lang, true);
9445 //std::setlocale(LC_ALL, lang);
9446 NSLog(@"Setting Language: %s", lang);
9449 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9451 /* Parse Arguments {{{ */
9452 bool substrate(false);
9458 for (int argi(1); argi != argc; ++argi)
9459 if (strcmp(argv[argi], "--") == 0) {
9461 argv[argi] = argv[0];
9467 for (int argi(1); argi != arge; ++argi)
9468 if (strcmp(args[argi], "--substrate") == 0)
9471 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9475 App_ = [[NSBundle mainBundle] bundlePath];
9476 Home_ = NSHomeDirectory();
9482 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9483 alloc_ = alloc->method_imp;
9484 alloc->method_imp = (IMP) &Alloc_;*/
9486 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9487 dealloc_ = dealloc->method_imp;
9488 dealloc->method_imp = (IMP) &Dealloc_;*/
9490 /* System Information {{{ */
9494 size = sizeof(maxproc);
9495 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9496 perror("sysctlbyname(\"kern.maxproc\", ?)");
9497 else if (maxproc < 64) {
9499 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9500 perror("sysctlbyname(\"kern.maxproc\", #)");
9503 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9504 char *osversion = new char[size];
9505 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9506 perror("sysctlbyname(\"kern.osversion\", ?)");
9508 System_ = [NSString stringWithUTF8String:osversion];
9510 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9511 char *machine = new char[size];
9512 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9513 perror("sysctlbyname(\"hw.machine\", ?)");
9517 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9518 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9519 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9520 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9524 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9525 NSData *data((NSData *) ecid);
9526 size_t length([data length]);
9527 uint8_t bytes[length];
9528 [data getBytes:bytes];
9529 char string[length * 2 + 1];
9530 for (size_t i(0); i != length; ++i)
9531 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9532 ChipID_ = [NSString stringWithUTF8String:string];
9536 IOObjectRelease(service);
9540 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9542 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9543 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9544 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9546 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9547 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9548 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9550 if (mcc != NULL && mnc != NULL)
9551 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9558 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9559 Build_ = [system objectForKey:@"ProductBuildVersion"];
9560 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9561 Product_ = [info objectForKey:@"SafariProductVersion"];
9562 Safari_ = [info objectForKey:@"CFBundleVersion"];
9565 /* Load Database {{{ */
9567 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9569 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9571 if (Metadata_ == NULL)
9572 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9574 Settings_ = [Metadata_ objectForKey:@"Settings"];
9576 Packages_ = [Metadata_ objectForKey:@"Packages"];
9577 Sections_ = [Metadata_ objectForKey:@"Sections"];
9578 Sources_ = [Metadata_ objectForKey:@"Sources"];
9580 Token_ = [Metadata_ objectForKey:@"Token"];
9583 if (Settings_ != nil)
9584 Role_ = [Settings_ objectForKey:@"Role"];
9586 if (Sections_ == nil) {
9587 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9588 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9591 if (Sources_ == nil) {
9592 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9593 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9598 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9601 if (Packages_ != nil) {
9603 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9607 [Metadata_ removeObjectForKey:@"Packages"];
9613 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9615 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9616 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9617 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9618 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9619 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9620 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9622 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9624 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9625 unlink("/tmp/.cydia.fw");
9627 } else if (access("/User", F_OK) != 0 || version < 2) {
9630 system("/usr/libexec/cydia/firmware.sh");
9634 _assert([[NSFileManager defaultManager]
9635 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9636 withIntermediateDirectories:YES
9641 if (access("/tmp/cydia.chk", F_OK) == 0) {
9642 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9643 _assert(errno == ENOENT);
9644 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9645 _assert(errno == ENOENT);
9648 /* APT Initialization {{{ */
9649 _assert(pkgInitConfig(*_config));
9650 _assert(pkgInitSystem(*_config, _system));
9653 _config->Set("APT::Acquire::Translation", lang);
9655 // XXX: this timeout might be important :(
9656 //_config->Set("Acquire::http::Timeout", 15);
9658 _config->Set("Acquire::http::MaxParallel", 3);
9660 /* Color Choices {{{ */
9661 space_ = CGColorSpaceCreateDeviceRGB();
9663 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9664 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9665 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9666 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9667 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9668 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9669 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9670 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9671 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9673 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9674 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9676 /* UIKit Configuration {{{ */
9677 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9678 if ($GSFontSetUseLegacyFontMetrics != NULL)
9679 $GSFontSetUseLegacyFontMetrics(YES);
9681 // XXX: I have a feeling this was important
9682 //UIKeyboardDisableAutomaticAppearance();
9685 Colon_ = UCLocalize("COLON_DELIMITED");
9686 Elision_ = UCLocalize("ELISION");
9687 Error_ = UCLocalize("ERROR");
9688 Warning_ = UCLocalize("WARNING");
9691 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9693 CGColorSpaceRelease(space_);